-
Notifications
You must be signed in to change notification settings - Fork 34
/
index.ts
460 lines (410 loc) · 15.6 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import {
DataProvider,
GetListParams,
GetOneParams,
GetManyParams,
GetManyReferenceParams,
UpdateParams,
UpdateManyParams,
CreateParams,
DeleteParams,
DeleteManyParams,
} from 'ra-core';
import {
PrimaryKey,
PostgRestOperator,
getPrimaryKey,
parseFilters,
getOrderBy,
dataWithVirtualId,
dataWithoutVirtualId,
removePrimaryKey,
getQuery,
encodeId,
PostgRestSortOrder,
} from './urlBuilder';
import qs from 'qs';
import isEqual from 'lodash/isEqual';
/**
* Maps react-admin queries to a postgrest REST API
*
* This REST dialect uses postgrest syntax
*
* @see https://postgrest.org/en/stable/api.html#embedded-filters
*
* @example
*
* getList => GET http://my.api.url/posts?order=title.asc&offset=0&limit=24&filterField=eq.value
* getOne => GET http://my.api.url/posts?id=eq.123
* getMany => GET http://my.api.url/posts?id=in.(123,456,789)
* getManyReference => GET http://my.api.url/posts?author_id=eq.345
* create => POST http://my.api.url/posts
* update => PATCH http://my.api.url/posts?id=eq.123
* updateMany => PATCH http://my.api.url/posts?id=in.(123,456,789)
* delete => DELETE http://my.api.url/posts?id=eq.123
* deleteMany => DELETE http://my.api.url/posts?id=in.(123,456,789)
*
* @example
*
* import * as React from 'react';
* import { Admin, Resource, fetchUtils } from 'react-admin';
* import postgrestRestProvider,
* { IDataProviderConfig,
* defaultPrimaryKeys,
* defaultSchema } from '@raphiniert/ra-data-postgrest';
*
* import { PostList } from './posts';
*
* const config: IDataProviderConfig = {
* apiUrl: 'http://path.to.my.api/',
* httpClient: fetchUtils.fetchJson,
* defaultListOp: 'eq',
* primaryKeys: defaultPrimaryKeys,
* schema: defaultSchema
* }
*
* const App = () => (
* <Admin dataProvider={postgrestRestProvider(config)}>
* <Resource name="posts" list={PostList} />
* </Admin>
* );
*
* export default App;
*/
export type MetaOption = string | undefined;
export const defaultPrimaryKeys = new Map<string, PrimaryKey>();
export const defaultSchema = () => '';
export { PostgRestSortOrder };
export interface IDataProviderConfig {
apiUrl: string;
httpClient: (string, Options) => Promise<any>;
defaultListOp: PostgRestOperator;
sortOrder?: PostgRestSortOrder;
primaryKeys: Map<string, PrimaryKey>;
schema: () => string;
}
const useCustomSchema = (
schema: () => string,
metaSchema: MetaOption,
method: string
) => {
let funcHeaderSchema = schema;
if (metaSchema !== undefined) {
funcHeaderSchema = () => metaSchema;
}
if (funcHeaderSchema().length > 0) {
let schemaHeader = '';
if (['GET', 'HEAD'].includes(method)) {
schemaHeader = 'Accept-Profile';
} else if (['POST', 'PATCH', 'PUT', 'DELETE'].includes(method)) {
schemaHeader = 'Content-Profile';
} else return {};
return { [schemaHeader]: funcHeaderSchema() };
} else return {};
};
export default (config: IDataProviderConfig): DataProvider => ({
getList: (resource, params: Partial<GetListParams> = {}) => {
const primaryKey = getPrimaryKey(resource, config.primaryKeys);
const { page, perPage } = params.pagination;
const { field, order } = params.sort || {};
const { filter, select } = parseFilters(params, config.defaultListOp);
const metaSchema = params.meta?.schema;
let query = {
offset: String((page - 1) * perPage),
limit: String(perPage),
// append filters
...filter,
};
if (field) {
query.order = getOrderBy(
field,
order,
primaryKey,
config.sortOrder
);
if (
params.meta?.nullsfirst &&
!query.order.includes('nullsfirst')
) {
query.order = query.order.includes('nullslast')
? query.order.replace('nullslast', 'nullsfirst')
: `${query.order}.nullsfirst`;
}
if (
params.meta?.nullsfirst === false &&
query.order.includes('nullsfirst')
) {
query.order = query.order.replace('.nullsfirst', '');
}
if (params.meta?.nullslast && !query.order.includes('nullslast')) {
query.order = query.order.includes('nullsfirst')
? query.order.replace('nullsfirst', 'nullslast')
: `${query.order}.nullslast`;
}
if (
params.meta?.nullslast === false &&
query.order.includes('nullslast')
) {
query.order = query.order.replace('.nullslast', '');
}
}
if (select) {
query.select = select;
}
// add header that Content-Range is in returned header
const options = {
headers: new Headers({
Accept: 'application/json',
Prefer: 'count=exact',
...(params.meta?.headers || {}),
...useCustomSchema(config.schema, metaSchema, 'GET'),
}),
};
const url = `${config.apiUrl}/${resource}?${qs.stringify(query)}`;
return config.httpClient(url, options).then(({ headers, json }) => {
if (!headers.has('content-range')) {
throw new Error(
`The Content-Range header is missing in the HTTP Response. The postgREST data provider expects
responses for lists of resources to contain this header with the total number of results to build
the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?`
);
}
return {
data: json.map(obj => dataWithVirtualId(obj, primaryKey)),
total: parseInt(
headers.get('content-range').split('/').pop(),
10
),
};
});
},
getOne: (resource, params: Partial<GetOneParams> = {}) => {
const { id, meta } = params;
const primaryKey = getPrimaryKey(resource, config.primaryKeys);
const query = getQuery(primaryKey, id, resource, meta);
const url = `${config.apiUrl}/${resource}?${qs.stringify(query)}`;
const metaSchema = params.meta?.schema;
return config
.httpClient(url, {
headers: new Headers({
accept: 'application/vnd.pgrst.object+json',
...(params.meta?.headers || {}),
...useCustomSchema(config.schema, metaSchema, 'GET'),
}),
})
.then(({ json }) => ({
data: dataWithVirtualId(json, primaryKey),
}));
},
getMany: (resource, params: Partial<GetManyParams> = {}) => {
const ids = params.ids;
if (ids.length === 0) {
return Promise.resolve({ data: [] });
}
const primaryKey = getPrimaryKey(resource, config.primaryKeys);
const query = getQuery(primaryKey, ids, resource, params.meta);
const url = `${config.apiUrl}/${resource}?${qs.stringify(query)}`;
const metaSchema = params.meta?.schema;
return config
.httpClient(url, {
headers: new Headers({
...useCustomSchema(config.schema, metaSchema, 'GET'),
}),
})
.then(({ json }) => ({
data: json.map(data => dataWithVirtualId(data, primaryKey)),
}));
},
getManyReference: (
resource,
params: Partial<GetManyReferenceParams> = {}
) => {
const { page, perPage } = params.pagination;
const { field, order } = params.sort;
const { filter, select } = parseFilters(params, config.defaultListOp);
const primaryKey = getPrimaryKey(resource, config.primaryKeys);
const metaSchema = params.meta?.schema;
let query = params.target
? {
[params.target]: `eq.${params.id}`,
order: getOrderBy(field, order, primaryKey, config.sortOrder),
offset: String((page - 1) * perPage),
limit: String(perPage),
...filter,
}
: {
order: getOrderBy(field, order, primaryKey),
offset: String((page - 1) * perPage),
limit: String(perPage),
...filter,
};
if (select) {
query.select = select;
}
// add header that Content-Range is in returned header
const options = {
headers: new Headers({
Accept: 'application/json',
Prefer: 'count=exact',
...(params.meta?.headers || {}),
...useCustomSchema(config.schema, metaSchema, 'GET'),
}),
};
const url = `${config.apiUrl}/${resource}?${qs.stringify(query)}`;
return config.httpClient(url, options).then(({ headers, json }) => {
if (!headers.has('content-range')) {
throw new Error(
`The Content-Range header is missing in the HTTP Response. The postgREST data provider expects
responses for lists of resources to contain this header with the total number of results to build
the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?`
);
}
return {
data: json.map(data => dataWithVirtualId(data, primaryKey)),
total: parseInt(
headers.get('content-range').split('/').pop(),
10
),
};
});
},
update: (resource, params: Partial<UpdateParams> = {}) => {
const { id, data, meta, previousData } = params;
const primaryKey = getPrimaryKey(resource, config.primaryKeys);
const query = getQuery(primaryKey, id, resource, meta);
const url = `${config.apiUrl}/${resource}?${qs.stringify(query)}`;
const changedData = getChanges(data, previousData);
if (Object.keys(changedData).length === 0) {
return Promise.resolve({ data: { ...previousData } });
}
const metaSchema = params.meta?.schema;
const body = JSON.stringify({
...dataWithoutVirtualId(
removePrimaryKey(changedData, primaryKey),
primaryKey
),
});
return config
.httpClient(url, {
method: 'PATCH',
headers: new Headers({
Accept: 'application/vnd.pgrst.object+json',
Prefer: 'return=representation',
'Content-Type': 'application/json',
...(params.meta?.headers || {}),
...useCustomSchema(config.schema, metaSchema, 'PATCH'),
}),
body,
})
.then(({ json }) => ({
data: dataWithVirtualId(json, primaryKey),
}));
},
updateMany: (resource, params: Partial<UpdateManyParams> = {}) => {
const { ids, meta, data } = params;
const primaryKey = getPrimaryKey(resource, config.primaryKeys);
const query = getQuery(primaryKey, ids, resource, meta);
const url = `${config.apiUrl}/${resource}?${qs.stringify(query)}`;
const body = JSON.stringify({
...dataWithoutVirtualId(
removePrimaryKey(data, primaryKey),
primaryKey
),
});
const metaSchema = params.meta?.schema;
return config
.httpClient(url, {
method: 'PATCH',
headers: new Headers({
Prefer: 'return=representation',
'Content-Type': 'application/json',
...(params.meta?.headers || {}),
...useCustomSchema(config.schema, metaSchema, 'PATCH'),
}),
body,
})
.then(({ json }) => ({
data: json.map(data => encodeId(data, primaryKey)),
}));
},
create: (resource, params: Partial<CreateParams> = {}) => {
const { meta } = params;
const primaryKey = getPrimaryKey(resource, config.primaryKeys);
const query = getQuery(primaryKey, undefined, resource, meta);
const queryStr = qs.stringify(query);
const url = `${config.apiUrl}/${resource}${
queryStr.length > 0 ? '?' : ''
}${queryStr}`;
const metaSchema = params.meta?.schema;
return config
.httpClient(url, {
method: 'POST',
headers: new Headers({
Accept: 'application/vnd.pgrst.object+json',
Prefer: 'return=representation',
'Content-Type': 'application/json',
...(params.meta?.headers || {}),
...useCustomSchema(config.schema, metaSchema, 'POST'),
}),
body: JSON.stringify(
dataWithoutVirtualId(params.data, primaryKey)
),
})
.then(({ json }) => ({
data: {
...json,
id: encodeId(json, primaryKey),
},
}));
},
delete: (resource, params: Partial<DeleteParams> = {}) => {
const { id, meta } = params;
const primaryKey = getPrimaryKey(resource, config.primaryKeys);
const query = getQuery(primaryKey, id, resource, meta);
const url = `${config.apiUrl}/${resource}?${qs.stringify(query)}`;
const metaSchema = params.meta?.schema;
return config
.httpClient(url, {
method: 'DELETE',
headers: new Headers({
Accept: 'application/vnd.pgrst.object+json',
Prefer: 'return=representation',
'Content-Type': 'application/json',
...(params.meta?.headers || {}),
...useCustomSchema(config.schema, metaSchema, 'DELETE'),
}),
})
.then(({ json }) => ({
data: dataWithVirtualId(json, primaryKey),
}));
},
deleteMany: (resource, params: Partial<DeleteManyParams> = {}) => {
const { ids, meta } = params;
const primaryKey = getPrimaryKey(resource, config.primaryKeys);
const query = getQuery(primaryKey, ids, resource, meta);
const url = `${config.apiUrl}/${resource}?${qs.stringify(query)}`;
const metaSchema = params.meta?.schema;
return config
.httpClient(url, {
method: 'DELETE',
headers: new Headers({
Prefer: 'return=representation',
'Content-Type': 'application/json',
...(params.meta?.headers || {}),
...useCustomSchema(config.schema, metaSchema, 'DELETE'),
}),
})
.then(({ json }) => ({
data: json.map(data => encodeId(data, primaryKey)),
}));
},
});
const getChanges = (data: any, previousData: any) => {
const changes = Object.keys(data).reduce((changes, key) => {
if (!isEqual(data[key], previousData[key])) {
changes[key] = data[key];
}
return changes;
}, {});
return changes;
};