@raphiniert/ra-data-postgrest 1.2.0 → 2.0.0-alpha.0

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.
@@ -1,412 +0,0 @@
1
- import { fetchUtils, DataProvider, Identifier } from 'ra-core';
2
-
3
- /**
4
- * Maps react-admin queries to a postgrest REST API
5
- *
6
- * This REST dialect uses postgrest syntax
7
- *
8
- * @see https://postgrest.org/en/stable/api.html#embedded-filters
9
- *
10
- * @example
11
- *
12
- * getList => GET http://my.api.url/posts?order=title.asc&offset=0&limit=24&filterField=eq.value
13
- * getOne => GET http://my.api.url/posts?id=eq.123
14
- * getMany => GET http://my.api.url/posts?id=in.(123,456,789)
15
- * getManyReference => GET http://my.api.url/posts?author_id=eq.345
16
- * create => POST http://my.api.url/posts
17
- * update => PATCH http://my.api.url/posts?id=eq.123
18
- * updateMany => PATCH http://my.api.url/posts?id=in.(123,456,789)
19
- * delete => DELETE http://my.api.url/posts?id=eq.123
20
- * deleteMany => DELETE http://my.api.url/posts?id=in.(123,456,789)
21
- *
22
- * @example
23
- *
24
- * import * as React from 'react';
25
- * import { Admin, Resource } from 'react-admin';
26
- * import postgrestRestProvider from '@promitheus/ra-data-postgrest';
27
- *
28
- * import { PostList } from './posts';
29
- *
30
- * const App = () => (
31
- * <Admin dataProvider={postgrestRestProvider('http://path.to.my.api/')}>
32
- * <Resource name="posts" list={PostList} />
33
- * </Admin>
34
- * );
35
- *
36
- * export default App;
37
- */
38
- function parseFilters(filter, defaultListOp) {
39
- let result = {};
40
- Object.keys(filter).forEach(function (key) {
41
- // key: the name of the object key
42
-
43
- const splitKey = key.split('@');
44
- const operation = splitKey.length == 2 ? splitKey[1] : defaultListOp;
45
-
46
- let values;
47
- if (operation.includes('like')) {
48
- // we split the search term in words
49
- values = filter[key].trim().split(' ');
50
- } else {
51
- values = [filter[key]];
52
- }
53
-
54
- values.forEach(value => {
55
- // if operator is intentionally blank, rpc syntax
56
- let op = operation.includes('like') ? `${operation}.*${value}*` : operation.length == 0 ? `${value}` : `${operation}.${value}`;
57
-
58
- if (result[splitKey[0]] === undefined) {
59
- // first operator for the key, we add it to the dict
60
- result[splitKey[0]] = op;
61
- }
62
- else
63
- {
64
- if (!Array.isArray(result[splitKey[0]])) {
65
- // second operator, we transform to an array
66
- result[splitKey[0]] = [result[splitKey[0]], op]
67
- } else {
68
- // third and subsequent, we add to array
69
- result[splitKey[0]].push(op);
70
- }
71
- }
72
- });
73
-
74
- });
75
-
76
- return result;
77
- }
78
-
79
- // compound keys capability
80
- type PrimaryKey = Array<string>;
81
-
82
- const getPrimaryKey = (resource : string, primaryKeys: Map<string, PrimaryKey>) => {
83
- return primaryKeys.get(resource) || ['id'];
84
- }
85
-
86
- const decodeId = (id: Identifier, primaryKey: PrimaryKey): string[] => {
87
- if (isCompoundKey(primaryKey)) {
88
- return JSON.parse(id.toString());
89
- } else {
90
- return [id.toString()];
91
- }
92
- }
93
-
94
- const encodeId = (data: any, primaryKey: PrimaryKey): Identifier => {
95
- if (isCompoundKey(primaryKey)) {
96
- return JSON.stringify(primaryKey.map(key => data[key]));
97
- } else {
98
- return data[primaryKey[0]];
99
- }
100
- }
101
-
102
- const dataWithId = (data: any, primaryKey: PrimaryKey) => {
103
- if (primaryKey === ['id']) {
104
- return data;
105
- }
106
-
107
- return Object.assign(data, {
108
- id: encodeId(data, primaryKey)
109
- });
110
- }
111
-
112
- const isCompoundKey = (primaryKey: PrimaryKey) : Boolean => {
113
- return primaryKey.length > 1;
114
- }
115
-
116
- const getQuery = (primaryKey : PrimaryKey, ids: Identifier | Array<Identifier>, resource: string) : string => {
117
- if (Array.isArray(ids) && ids.length > 1) {
118
- // no standardized query with multiple ids possible for rpc endpoints which are api-exposed database functions
119
- if (resource.startsWith('rpc/')) {
120
- console.error('PostgREST\'s rpc endpoints are not intended to be handled as views. Therefore, no query generation for multiple key values implemented!');
121
-
122
- return ;
123
- }
124
-
125
- if (isCompoundKey(primaryKey)) {
126
- return `or=(
127
- ${ids.map(id => {
128
- const primaryKeyParams = decodeId(id, primaryKey);
129
- return `and(${primaryKey.map((key, i) => `${key}.eq.${primaryKeyParams[i]}`).join(',')})`;
130
- })
131
- }
132
- )`;
133
- } else {
134
- return new URLSearchParams({ [primaryKey[0]]: `in.(${ids.join(',')})` }).toString();
135
- }
136
- } else {
137
- // if ids is one Identifier
138
- const id : Identifier = ids.toString();
139
- const primaryKeyParams = decodeId(id, primaryKey);
140
-
141
- if (isCompoundKey(primaryKey)) {
142
- if (resource.startsWith('rpc/'))
143
- return `${primaryKey.map((key : string, i: any) => `${key}=${primaryKeyParams[i]}`).join('&')}`;
144
- else
145
- return `and=(${primaryKey.map((key : string, i: any) => `${key}.eq.${primaryKeyParams[i]}`).join(',')})`;
146
- } else {
147
- return new URLSearchParams([[primaryKey[0], `eq.${id}`]]).toString();
148
- }
149
- }
150
- }
151
-
152
- const getKeyData = (primaryKey : PrimaryKey, data: object) : object => {
153
- if (isCompoundKey(primaryKey)) {
154
- return primaryKey.reduce(
155
- (keyData, key) => ({
156
- ...keyData,
157
- [key]: data[key]
158
- }),
159
- {});
160
- } else {
161
- return { [primaryKey[0]]: data[primaryKey[0]] };
162
- }
163
- }
164
-
165
- const getOrderBy = (field : string, order: string, primaryKey : PrimaryKey) => {
166
- if (field == 'id') {
167
- return primaryKey.map(key => (`${key}.${order.toLowerCase()}`)).join(',');
168
- } else {
169
- return `${field}.${order.toLowerCase()}`;
170
- }
171
- };
172
-
173
- const defaultPrimaryKeys = new Map<string, PrimaryKey>();
174
-
175
- export default (apiUrl, httpClient = fetchUtils.fetchJson, defaultListOp = 'eq',
176
- primaryKeys: Map<string, PrimaryKey> = defaultPrimaryKeys): DataProvider => ({
177
- getList: (resource, params) => {
178
- const primaryKey = getPrimaryKey(resource, primaryKeys);
179
-
180
- const { page, perPage } = params.pagination;
181
- const { field, order } = params.sort;
182
- const parsedFilter = parseFilters(params.filter, defaultListOp);
183
-
184
- const query = {
185
- order: getOrderBy(field, order, primaryKey),
186
- offset: String((page - 1) * perPage),
187
- limit: String(perPage),
188
- // append filters
189
- ...parsedFilter
190
- };
191
-
192
- // add header that Content-Range is in returned header
193
- const options = {
194
- headers: new Headers({
195
- Accept: 'application/json',
196
- Prefer: 'count=exact'
197
- })
198
- };
199
-
200
- const url = `${apiUrl}/${resource}?${new URLSearchParams(query)}`;
201
-
202
- return httpClient(url, options).then(({ headers, json }) => {
203
- if (!headers.has('content-range')) {
204
- throw new Error(
205
- `The Content-Range header is missing in the HTTP Response. The postgREST data provider expects
206
- responses for lists of resources to contain this header with the total number of results to build
207
- the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?`
208
- );
209
- }
210
- return {
211
- data: json.map(obj => dataWithId(obj, primaryKey)),
212
- total: parseInt(
213
- headers
214
- .get('content-range')
215
- .split('/')
216
- .pop(),
217
- 10
218
- )
219
- };
220
- });
221
- },
222
-
223
- getOne: (resource, params) => {
224
- const id = params.id;
225
- const primaryKey = getPrimaryKey(resource, primaryKeys);
226
-
227
- const query = getQuery(primaryKey, id, resource);
228
-
229
- const url = `${apiUrl}/${resource}?${query}`;
230
-
231
- return httpClient(url, {
232
- headers: new Headers({ 'accept': 'application/vnd.pgrst.object+json' }),
233
- }).then(({ json }) => ({
234
- data: dataWithId(json, primaryKey),
235
- }))
236
- },
237
-
238
- getMany: (resource, params) => {
239
- const ids = params.ids;
240
- const primaryKey = getPrimaryKey(resource, primaryKeys);
241
-
242
- const query = getQuery(primaryKey, ids, resource);
243
-
244
- const url = `${apiUrl}/${resource}?${query}`;
245
-
246
- return httpClient(url).then(({ json }) => ({ data: json.map(data => dataWithId(data, primaryKey)) }));
247
- },
248
-
249
- getManyReference: (resource, params) => {
250
- const { page, perPage } = params.pagination;
251
- const { field, order } = params.sort;
252
- const parsedFilter = parseFilters(params.filter, defaultListOp);
253
- const primaryKey = getPrimaryKey(resource, primaryKeys);
254
-
255
- const query = params.target ? {
256
- [params.target]: `eq.${params.id}`,
257
- order: getOrderBy(field, order, primaryKey),
258
- offset: String((page - 1) * perPage),
259
- limit: String(perPage),
260
- ...parsedFilter,
261
- }:{
262
- order: getOrderBy(field, order, primaryKey),
263
- offset: String((page - 1) * perPage),
264
- limit: String(perPage),
265
- ...parsedFilter,
266
- };
267
-
268
- // add header that Content-Range is in returned header
269
- const options = {
270
- headers: new Headers({
271
- Accept: 'application/json',
272
- Prefer: 'count=exact'
273
- })
274
- }
275
-
276
- const url = `${apiUrl}/${resource}?${new URLSearchParams(query)}`;
277
-
278
- return httpClient(url, options).then(({ headers, json }) => {
279
- if (!headers.has('content-range')) {
280
- throw new Error(
281
- `The Content-Range header is missing in the HTTP Response. The postgREST data provider expects
282
- responses for lists of resources to contain this header with the total number of results to build
283
- the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?`
284
- );
285
- }
286
- return {
287
- data: json.map(data => dataWithId(data, primaryKey)),
288
- total: parseInt(
289
- headers
290
- .get('content-range')
291
- .split('/')
292
- .pop(),
293
- 10
294
- ),
295
- };
296
- });
297
- },
298
-
299
- update: (resource, params) => {
300
- const { id, data } = params;
301
- const primaryKey = getPrimaryKey(resource, primaryKeys);
302
-
303
- const query = getQuery(primaryKey, id, resource);
304
-
305
- const primaryKeyData = getKeyData(primaryKey, data);
306
-
307
- const url = `${apiUrl}/${resource}?${query}`;
308
-
309
- const body = JSON.stringify({
310
- ...data,
311
- ...primaryKeyData
312
- });
313
-
314
- return httpClient(url, {
315
- method: 'PATCH',
316
- headers: new Headers({
317
- 'Accept': 'application/vnd.pgrst.object+json',
318
- 'Prefer': 'return=representation',
319
- 'Content-Type': 'application/json'
320
- }),
321
- body,
322
- }).then(({ json }) => ({ data: dataWithId(json, primaryKey) }));
323
- },
324
-
325
- updateMany: (resource, params) => {
326
- const ids = params.ids;
327
- const primaryKey = getPrimaryKey(resource, primaryKeys);
328
-
329
- const query = getQuery(primaryKey, ids, resource);
330
-
331
- const body = JSON.stringify(
332
- params.data.map(obj => {
333
- const { id, ...data } = obj;
334
- const primaryKeyData = getKeyData(primaryKey, data);
335
-
336
- return {
337
- ...data,
338
- ...primaryKeyData
339
- };
340
- })
341
- );
342
-
343
- const url = `${apiUrl}/${resource}?${query}`;
344
-
345
- return httpClient(url, {
346
- method: 'PATCH',
347
- headers: new Headers({
348
- 'Prefer': 'return=representation',
349
- 'Content-Type': 'application/json',
350
- }),
351
- body,
352
- }).then(({ json }) => ({
353
- data: json.map(data => encodeId(data, primaryKey))
354
- }));
355
- },
356
-
357
- create: (resource, params) => {
358
- const primaryKey = getPrimaryKey(resource, primaryKeys);
359
-
360
- const url = `${apiUrl}/${resource}`;
361
-
362
- return httpClient(url, {
363
- method: 'POST',
364
- headers: new Headers({
365
- 'Accept': 'application/vnd.pgrst.object+json',
366
- 'Prefer': 'return=representation',
367
- 'Content-Type': 'application/json'
368
- }),
369
- body: JSON.stringify(params.data),
370
- }).then(({ json }) => ({
371
- data: {
372
- ...params.data,
373
- id: encodeId(json, primaryKey)
374
- }
375
- }));
376
- },
377
-
378
- delete: (resource, params) => {
379
- const id = params.id;
380
- const primaryKey = getPrimaryKey(resource, primaryKeys);
381
-
382
- const query = getQuery(primaryKey, id, resource);
383
-
384
- const url = `${apiUrl}/${resource}?${query}`;
385
-
386
- return httpClient(url, {
387
- method: 'DELETE',
388
- headers: new Headers({
389
- 'Accept': 'application/vnd.pgrst.object+json',
390
- 'Prefer': 'return=representation',
391
- 'Content-Type': 'application/json'
392
- }),
393
- }).then(({ json }) => ({ data: dataWithId(json, primaryKey) }));
394
- },
395
-
396
- deleteMany: (resource, params) => {
397
- const ids = params.ids;
398
- const primaryKey = getPrimaryKey(resource, primaryKeys);
399
-
400
- const query = getQuery(primaryKey, ids, resource);
401
-
402
- const url = `${apiUrl}/${resource}?${query}`;
403
-
404
- return httpClient(url, {
405
- method: 'DELETE',
406
- headers: new Headers({
407
- 'Prefer': 'return=representation',
408
- 'Content-Type': 'application/json'
409
- }),
410
- }).then(({ json }) => ({ data: json.map(data => encodeId(data, primaryKey)) }));
411
- },
412
- });