@svadmin/sanity 0.3.0 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "@svadmin/sanity",
3
- "version": "0.3.0",
3
+ "version": "0.5.12",
4
4
  "description": "Sanity DataProvider for svadmin",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
- "files": ["src/**/*"],
7
+ "files": [
8
+ "src/**/*"
9
+ ],
8
10
  "main": "src/index.ts",
9
11
  "types": "src/index.ts",
10
12
  "exports": {
@@ -14,7 +16,12 @@
14
16
  }
15
17
  },
16
18
  "peerDependencies": {
17
- "@svadmin/core": "^0.3.0"
19
+ "@svadmin/core": "^0.5.0"
18
20
  },
19
- "license": "MIT"
21
+ "license": "MIT",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/zuohuadong/svadmin.git",
25
+ "directory": "packages/sanity"
26
+ }
20
27
  }
@@ -1,15 +1,25 @@
1
1
  import type {
2
2
  DataProvider, GetListParams, GetListResult, GetOneParams, GetOneResult,
3
3
  CreateParams, CreateResult, UpdateParams, UpdateResult, DeleteParams, DeleteResult,
4
- GetManyParams, GetManyResult, CustomParams, CustomResult
4
+ GetManyParams, GetManyResult, CustomParams, CustomResult, Filter, Sort, BaseRecord
5
5
  } from '@svadmin/core';
6
6
 
7
+ interface SanityDoc {
8
+ _id: string;
9
+ _type: string;
10
+ [key: string]: unknown;
11
+ }
12
+
13
+ interface SanityMutationResult {
14
+ results?: Array<{ id: string }>;
15
+ }
16
+
7
17
  // Sanity.io uses GROQ query language
8
- function buildGroqFilter(filters?: any[]): string {
18
+ function buildGroqFilter(filters?: Filter[]): string {
9
19
  if (!filters?.length) return '';
10
20
  return filters
11
- .filter((f: any) => 'field' in f)
12
- .map((f: any) => {
21
+ .filter((f): f is Filter & { field: string } => 'field' in f)
22
+ .map((f) => {
13
23
  switch (f.operator) {
14
24
  case 'eq': return `${f.field} == "${f.value}"`;
15
25
  case 'ne': return `${f.field} != "${f.value}"`;
@@ -28,7 +38,7 @@ export function createSanityDataProvider(projectId: string, dataset: string, tok
28
38
  const headers: Record<string, string> = { 'Content-Type': 'application/json' };
29
39
  if (token) headers['Authorization'] = `Bearer ${token}`;
30
40
 
31
- async function query(groq: string, params: Record<string, unknown> = {}): Promise<any> {
41
+ async function query(groq: string, params: Record<string, unknown> = {}): Promise<unknown> {
32
42
  const url = new URL(`${apiUrl}/data/query/${dataset}`);
33
43
  url.searchParams.set('query', groq);
34
44
  for (const [k, v] of Object.entries(params)) url.searchParams.set(`$${k}`, JSON.stringify(v));
@@ -38,7 +48,7 @@ export function createSanityDataProvider(projectId: string, dataset: string, tok
38
48
  return data.result;
39
49
  }
40
50
 
41
- async function mutate(mutations: any[]): Promise<any> {
51
+ async function mutate(mutations: Record<string, unknown>[]): Promise<SanityMutationResult> {
42
52
  const res = await fetch(`${apiUrl}/data/mutate/${dataset}`, {
43
53
  method: 'POST', headers, body: JSON.stringify({ mutations }),
44
54
  });
@@ -49,50 +59,51 @@ export function createSanityDataProvider(projectId: string, dataset: string, tok
49
59
  return {
50
60
  getApiUrl: () => apiUrl,
51
61
 
52
- async getList<T>({ resource, pagination, sorters, filters }: GetListParams): Promise<GetListResult<T>> {
62
+ async getList<T extends BaseRecord = BaseRecord>({ resource, pagination, sorters, filters }: GetListParams): Promise<GetListResult<T>> {
53
63
  const { current = 1, pageSize = 10 } = pagination ?? {};
54
64
  const start = (current - 1) * pageSize;
55
65
  const end = start + pageSize;
56
66
  const filterStr = buildGroqFilter(filters);
57
67
  const typeFilter = `_type == "${resource}"`;
58
68
  const where = filterStr ? `${typeFilter} && ${filterStr}` : typeFilter;
59
- const orderStr = sorters?.length ? ` | order(${sorters.map(s => `${s.field} ${s.order}`).join(', ')})` : '';
69
+ const orderStr = sorters?.length ? ` | order(${sorters.map((s: Sort) => `${s.field} ${s.order}`).join(', ')})` : '';
60
70
 
61
71
  const [data, total] = await Promise.all([
62
72
  query(`*[${where}]${orderStr}[${start}...${end}]`),
63
73
  query(`count(*[${where}])`),
64
74
  ]);
65
- return { data: (data ?? []).map((d: any) => ({ ...d, id: d._id })) as T[], total: total ?? 0 };
75
+ return { data: ((data as SanityDoc[]) ?? []).map((d) => ({ ...d, id: d._id })) as T[], total: (total as number) ?? 0 };
66
76
  },
67
77
 
68
- async getOne<T>({ resource, id }: GetOneParams): Promise<GetOneResult<T>> {
69
- const data = await query(`*[_type == "${resource}" && _id == $id][0]`, { id });
78
+ async getOne<T extends BaseRecord = BaseRecord>({ resource, id }: GetOneParams): Promise<GetOneResult<T>> {
79
+ const raw = await query(`*[_type == "${resource}" && _id == $id][0]`, { id });
80
+ const data = raw as SanityDoc;
70
81
  return { data: { ...data, id: data._id } as T };
71
82
  },
72
83
 
73
- async create<T>({ resource, variables }: CreateParams): Promise<CreateResult<T>> {
74
- const doc = { _type: resource, ...variables };
84
+ async create<T extends BaseRecord = BaseRecord>({ resource, variables }: CreateParams): Promise<CreateResult<T>> {
85
+ const doc = { _type: resource, ...(variables as Record<string, unknown>) };
75
86
  const result = await mutate([{ create: doc }]);
76
87
  const id = result.results?.[0]?.id;
77
- return { data: { ...variables, id, _id: id } as T };
88
+ return { data: { ...(variables as Record<string, unknown>), id, _id: id } as unknown as T };
78
89
  },
79
90
 
80
- async update<T>({ resource, id, variables }: UpdateParams): Promise<UpdateResult<T>> {
91
+ async update<T extends BaseRecord = BaseRecord>({ resource, id, variables }: UpdateParams): Promise<UpdateResult<T>> {
81
92
  await mutate([{ patch: { id, set: variables } }]);
82
- return { data: { ...variables, id, _id: id } as T };
93
+ return { data: { ...(variables as Record<string, unknown>), id, _id: id } as unknown as T };
83
94
  },
84
95
 
85
- async deleteOne<T>({ resource, id }: DeleteParams): Promise<DeleteResult<T>> {
96
+ async deleteOne<T extends BaseRecord = BaseRecord>({ resource, id }: DeleteParams): Promise<DeleteResult<T>> {
86
97
  await mutate([{ delete: { id } }]);
87
98
  return { data: { id } as T };
88
99
  },
89
100
 
90
- async getMany<T>({ resource, ids }: GetManyParams): Promise<GetManyResult<T>> {
101
+ async getMany<T extends BaseRecord = BaseRecord>({ resource, ids }: GetManyParams): Promise<GetManyResult<T>> {
91
102
  const data = await query(`*[_type == "${resource}" && _id in $ids]`, { ids });
92
- return { data: (data ?? []).map((d: any) => ({ ...d, id: d._id })) as T[] };
103
+ return { data: ((data as SanityDoc[]) ?? []).map((d) => ({ ...d, id: d._id })) as T[] };
93
104
  },
94
105
 
95
- async custom<T>({ url, method, payload, headers: h }: CustomParams): Promise<CustomResult<T>> {
106
+ async custom<T = unknown>({ url, method, payload, headers: h }: CustomParams): Promise<CustomResult<T>> {
96
107
  const res = await fetch(url, { method: method.toUpperCase(), headers: { ...headers, ...h }, body: payload ? JSON.stringify(payload) : undefined });
97
108
  if (!res.ok) throw new Error(`Custom request failed: ${res.status}`);
98
109
  return { data: (await res.json()) as T };
package/src/index.ts CHANGED
@@ -1 +1 @@
1
- export { createSanityDataProvider } from './data-provider';
1
+ export { createSanityDataProvider } from './data-provider';