@raphiniert/ra-data-postgrest 1.2.1 → 2.0.0-alpha.1

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/src/index.ts CHANGED
@@ -1,5 +1,338 @@
1
- import dataProvider from './dataProvider';
2
- import authProvider from './authProvider';
1
+ import {
2
+ fetchUtils,
3
+ DataProvider,
4
+ GetListParams,
5
+ GetOneParams,
6
+ GetManyParams,
7
+ GetManyReferenceParams,
8
+ UpdateParams,
9
+ UpdateManyParams,
10
+ CreateParams,
11
+ DeleteParams,
12
+ DeleteManyParams,
13
+ } from 'ra-core';
14
+ import {
15
+ PrimaryKey,
16
+ PostgRestOperator,
17
+ getPrimaryKey,
18
+ parseFilters,
19
+ getOrderBy,
20
+ dataWithId,
21
+ getQuery,
22
+ getKeyData,
23
+ encodeId,
24
+ decodeId,
25
+ isCompoundKey,
26
+ } from './urlBuilder';
27
+ import qs from 'qs';
3
28
 
4
- export { authProvider };
5
- export default dataProvider;
29
+ /**
30
+ * Maps react-admin queries to a postgrest REST API
31
+ *
32
+ * This REST dialect uses postgrest syntax
33
+ *
34
+ * @see https://postgrest.org/en/stable/api.html#embedded-filters
35
+ *
36
+ * @example
37
+ *
38
+ * getList => GET http://my.api.url/posts?order=title.asc&offset=0&limit=24&filterField=eq.value
39
+ * getOne => GET http://my.api.url/posts?id=eq.123
40
+ * getMany => GET http://my.api.url/posts?id=in.(123,456,789)
41
+ * getManyReference => GET http://my.api.url/posts?author_id=eq.345
42
+ * create => POST http://my.api.url/posts
43
+ * update => PATCH http://my.api.url/posts?id=eq.123
44
+ * updateMany => PATCH http://my.api.url/posts?id=in.(123,456,789)
45
+ * delete => DELETE http://my.api.url/posts?id=eq.123
46
+ * deleteMany => DELETE http://my.api.url/posts?id=in.(123,456,789)
47
+ *
48
+ * @example
49
+ *
50
+ * import * as React from 'react';
51
+ * import { Admin, Resource } from 'react-admin';
52
+ * import postgrestRestProvider from '@raphiniert/ra-data-postgrest';
53
+ *
54
+ * import { PostList } from './posts';
55
+ *
56
+ * const App = () => (
57
+ * <Admin dataProvider={postgrestRestProvider('http://path.to.my.api/')}>
58
+ * <Resource name="posts" list={PostList} />
59
+ * </Admin>
60
+ * );
61
+ *
62
+ * export default App;
63
+ */
64
+
65
+ const defaultPrimaryKeys = new Map<string, PrimaryKey>();
66
+
67
+ export default (
68
+ apiUrl: string,
69
+ httpClient = fetchUtils.fetchJson,
70
+ defaultListOp: PostgRestOperator = 'eq',
71
+ primaryKeys: Map<string, PrimaryKey> = defaultPrimaryKeys
72
+ ): DataProvider => ({
73
+ getList: (resource, params: Partial<GetListParams> = {}) => {
74
+ const primaryKey = getPrimaryKey(resource, primaryKeys);
75
+
76
+ const { page, perPage } = params.pagination;
77
+ const { field, order } = params.sort || {};
78
+ const { filter, select } = parseFilters(params, defaultListOp);
79
+
80
+ let query = {
81
+ offset: String((page - 1) * perPage),
82
+ limit: String(perPage),
83
+ // append filters
84
+ ...filter,
85
+ };
86
+
87
+ if (field) {
88
+ query.order = getOrderBy(field, order, primaryKey);
89
+ }
90
+
91
+ if (select) {
92
+ query.select = select;
93
+ }
94
+
95
+ // add header that Content-Range is in returned header
96
+ const options = {
97
+ headers: new Headers({
98
+ Accept: 'application/json',
99
+ Prefer: 'count=exact',
100
+ ...(params.meta?.headers || {}),
101
+ }),
102
+ };
103
+
104
+ const url = `${apiUrl}/${resource}?${qs.stringify(query)}`;
105
+
106
+ return httpClient(url, options).then(({ headers, json }) => {
107
+ if (!headers.has('content-range')) {
108
+ throw new Error(
109
+ `The Content-Range header is missing in the HTTP Response. The postgREST data provider expects
110
+ responses for lists of resources to contain this header with the total number of results to build
111
+ the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?`
112
+ );
113
+ }
114
+ return {
115
+ data: json.map(obj => dataWithId(obj, primaryKey)),
116
+ total: parseInt(
117
+ headers.get('content-range').split('/').pop(),
118
+ 10
119
+ ),
120
+ };
121
+ });
122
+ },
123
+
124
+ getOne: (resource, params: Partial<GetOneParams> = {}) => {
125
+ const { id, meta } = params;
126
+ const primaryKey = getPrimaryKey(resource, primaryKeys);
127
+
128
+ const query = getQuery(primaryKey, id, resource, meta);
129
+
130
+ const url = `${apiUrl}/${resource}?${qs.stringify(query)}`;
131
+
132
+ return httpClient(url, {
133
+ headers: new Headers({
134
+ accept: 'application/vnd.pgrst.object+json',
135
+ ...(params.meta?.headers || {}),
136
+ }),
137
+ }).then(({ json }) => ({
138
+ data: dataWithId(json, primaryKey),
139
+ }));
140
+ },
141
+
142
+ getMany: (resource, params: Partial<GetManyParams> = {}) => {
143
+ const ids = params.ids;
144
+ const primaryKey = getPrimaryKey(resource, primaryKeys);
145
+
146
+ const query = getQuery(primaryKey, ids, resource, params.meta);
147
+ const url = `${apiUrl}/${resource}?${qs.stringify(query)}`;
148
+
149
+ return httpClient(url).then(({ json }) => ({
150
+ data: json.map(data => dataWithId(data, primaryKey)),
151
+ }));
152
+ },
153
+
154
+ getManyReference: (
155
+ resource,
156
+ params: Partial<GetManyReferenceParams> = {}
157
+ ) => {
158
+ const { page, perPage } = params.pagination;
159
+ const { field, order } = params.sort;
160
+
161
+ const { filter, select } = parseFilters(params, defaultListOp);
162
+ const primaryKey = getPrimaryKey(resource, primaryKeys);
163
+
164
+ let query = params.target
165
+ ? {
166
+ [params.target]: `eq.${params.id}`,
167
+ order: getOrderBy(field, order, primaryKey),
168
+ offset: String((page - 1) * perPage),
169
+ limit: String(perPage),
170
+ ...filter,
171
+ }
172
+ : {
173
+ order: getOrderBy(field, order, primaryKey),
174
+ offset: String((page - 1) * perPage),
175
+ limit: String(perPage),
176
+ ...filter,
177
+ };
178
+
179
+ if (select) {
180
+ query.select = select;
181
+ }
182
+
183
+ // add header that Content-Range is in returned header
184
+ const options = {
185
+ headers: new Headers({
186
+ Accept: 'application/json',
187
+ Prefer: 'count=exact',
188
+ ...(params.meta?.headers || {}),
189
+ }),
190
+ };
191
+
192
+ const url = `${apiUrl}/${resource}?${qs.stringify(query)}`;
193
+
194
+ return httpClient(url, options).then(({ headers, json }) => {
195
+ if (!headers.has('content-range')) {
196
+ throw new Error(
197
+ `The Content-Range header is missing in the HTTP Response. The postgREST data provider expects
198
+ responses for lists of resources to contain this header with the total number of results to build
199
+ the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?`
200
+ );
201
+ }
202
+ return {
203
+ data: json.map(data => dataWithId(data, primaryKey)),
204
+ total: parseInt(
205
+ headers.get('content-range').split('/').pop(),
206
+ 10
207
+ ),
208
+ };
209
+ });
210
+ },
211
+
212
+ update: (resource, params: Partial<UpdateParams> = {}) => {
213
+ const { id, data, meta } = params;
214
+ const primaryKey = getPrimaryKey(resource, primaryKeys);
215
+
216
+ const query = getQuery(primaryKey, id, resource, meta);
217
+
218
+ const primaryKeyData = getKeyData(primaryKey, data);
219
+
220
+ const url = `${apiUrl}/${resource}?${qs.stringify(query)}`;
221
+
222
+ const body = JSON.stringify({
223
+ ...data,
224
+ ...primaryKeyData,
225
+ });
226
+
227
+ return httpClient(url, {
228
+ method: 'PATCH',
229
+ headers: new Headers({
230
+ Accept: 'application/vnd.pgrst.object+json',
231
+ Prefer: 'return=representation',
232
+ 'Content-Type': 'application/json',
233
+ ...(params.meta?.headers || {}),
234
+ }),
235
+ body,
236
+ }).then(({ json }) => ({ data: dataWithId(json, primaryKey) }));
237
+ },
238
+
239
+ updateMany: (resource, params: Partial<UpdateManyParams> = {}) => {
240
+ const ids = params.ids;
241
+ const primaryKey = getPrimaryKey(resource, primaryKeys);
242
+
243
+ const body = JSON.stringify(
244
+ params.ids.map(id => {
245
+ const { data } = params;
246
+ const primaryKeyParams = decodeId(id, primaryKey);
247
+
248
+ const primaryKeyData = {};
249
+ if (isCompoundKey(primaryKey)) {
250
+ primaryKey.forEach((key, index) => {
251
+ primaryKeyData[key] = primaryKeyParams[index];
252
+ });
253
+ } else {
254
+ primaryKeyData[primaryKey[0]] = primaryKeyParams[0];
255
+ }
256
+
257
+ return {
258
+ ...data,
259
+ ...primaryKeyData,
260
+ };
261
+ })
262
+ );
263
+
264
+ const url = `${apiUrl}/${resource}`;
265
+
266
+ return httpClient(url, {
267
+ method: 'PATCH',
268
+ headers: new Headers({
269
+ Prefer: 'return=representation',
270
+ 'Content-Type': 'application/json',
271
+ ...(params.meta?.headers || {}),
272
+ }),
273
+ body,
274
+ }).then(({ json }) => ({
275
+ data: json.map(data => encodeId(data, primaryKey)),
276
+ }));
277
+ },
278
+
279
+ create: (resource, params: Partial<CreateParams> = {}) => {
280
+ const primaryKey = getPrimaryKey(resource, primaryKeys);
281
+ const url = `${apiUrl}/${resource}`;
282
+
283
+ return httpClient(url, {
284
+ method: 'POST',
285
+ headers: new Headers({
286
+ Accept: 'application/vnd.pgrst.object+json',
287
+ Prefer: 'return=representation',
288
+ 'Content-Type': 'application/json',
289
+ ...(params.meta?.headers || {}),
290
+ }),
291
+ body: JSON.stringify(params.data),
292
+ }).then(({ json }) => ({
293
+ data: {
294
+ ...json,
295
+ id: encodeId(json, primaryKey),
296
+ },
297
+ }));
298
+ },
299
+
300
+ delete: (resource, params: Partial<DeleteParams> = {}) => {
301
+ const { id, meta } = params;
302
+ const primaryKey = getPrimaryKey(resource, primaryKeys);
303
+
304
+ const query = getQuery(primaryKey, id, resource, meta);
305
+
306
+ const url = `${apiUrl}/${resource}?${qs.stringify(query)}`;
307
+
308
+ return httpClient(url, {
309
+ method: 'DELETE',
310
+ headers: new Headers({
311
+ Accept: 'application/vnd.pgrst.object+json',
312
+ Prefer: 'return=representation',
313
+ 'Content-Type': 'application/json',
314
+ ...(params.meta?.headers || {}),
315
+ }),
316
+ }).then(({ json }) => ({ data: dataWithId(json, primaryKey) }));
317
+ },
318
+
319
+ deleteMany: (resource, params: Partial<DeleteManyParams> = {}) => {
320
+ const { ids, meta } = params;
321
+ const primaryKey = getPrimaryKey(resource, primaryKeys);
322
+
323
+ const query = getQuery(primaryKey, ids, resource, meta);
324
+
325
+ const url = `${apiUrl}/${resource}?${qs.stringify(query)}`;
326
+
327
+ return httpClient(url, {
328
+ method: 'DELETE',
329
+ headers: new Headers({
330
+ Prefer: 'return=representation',
331
+ 'Content-Type': 'application/json',
332
+ ...(params.meta?.headers || {}),
333
+ }),
334
+ }).then(({ json }) => ({
335
+ data: json.map(data => encodeId(data, primaryKey)),
336
+ }));
337
+ },
338
+ });
@@ -0,0 +1,248 @@
1
+ import { Identifier } from 'ra-core';
2
+
3
+ /**
4
+ * Interface to clearly seperate the operator like < oder >
5
+ * from the name and the value of the filter
6
+ */
7
+ interface PostgRestFilter {
8
+ name: string;
9
+ operator?: PostgRestOperator;
10
+ value: string;
11
+ }
12
+
13
+ /**
14
+ * List of all possible operators in PostgRest
15
+ * (https://postgrest.org/en/stable/api.html#operators)
16
+ */
17
+ const postgrestOperators = [
18
+ 'eq',
19
+ 'gt',
20
+ 'gte',
21
+ 'lt',
22
+ 'lte',
23
+ 'neq',
24
+ 'like',
25
+ 'ilike',
26
+ 'match',
27
+ 'imatch',
28
+ 'in',
29
+ 'is',
30
+ 'fts',
31
+ 'plfts',
32
+ 'phfts',
33
+ 'wfts',
34
+ 'cs',
35
+ 'cd',
36
+ 'ov',
37
+ 'sl',
38
+ 'sr',
39
+ 'nxr',
40
+ 'nxl',
41
+ 'adj',
42
+ 'not',
43
+ 'or',
44
+ 'and',
45
+ ] as const;
46
+
47
+ type ParsedFiltersResult = {
48
+ filter: any;
49
+ select: any;
50
+ };
51
+
52
+ export type PostgRestOperator = (typeof postgrestOperators)[number];
53
+
54
+ export const parseFilters = (
55
+ params: any,
56
+ defaultListOp: PostgRestOperator
57
+ ): Partial<ParsedFiltersResult> => {
58
+ const { filter, meta = {} } = params;
59
+
60
+ let result: Partial<ParsedFiltersResult> = {};
61
+ result.filter = {};
62
+ Object.keys(filter).forEach(function (key) {
63
+ // key: the name of the object key
64
+
65
+ const splitKey = key.split('@');
66
+ const operation: PostgRestOperator =
67
+ splitKey.length == 2
68
+ ? (splitKey[1] as PostgRestOperator)
69
+ : defaultListOp;
70
+
71
+ let values: Array<string>;
72
+ if (['like', 'ilike'].includes(operation)) {
73
+ // we split the search term in words
74
+ values = filter[key].trim().split(/\s+/);
75
+ } else {
76
+ values = [filter[key]];
77
+ }
78
+
79
+ values.forEach(value => {
80
+ // if operator is intentionally blank, rpc syntax
81
+ let op = operation.includes('like')
82
+ ? `${operation}.*${value}*`
83
+ : operation.length == 0
84
+ ? `${value}`
85
+ : `${operation}.${value}`;
86
+
87
+ if (result.filter[splitKey[0]] === undefined) {
88
+ // first operator for the key, we add it to the dict
89
+ result.filter[splitKey[0]] = op;
90
+ } else {
91
+ if (!Array.isArray(result[splitKey[0]])) {
92
+ // second operator, we transform to an array
93
+ result.filter[splitKey[0]] = [
94
+ result.filter[splitKey[0]],
95
+ op,
96
+ ];
97
+ } else {
98
+ // third and subsequent, we add to array
99
+ result.filter[splitKey[0]].push(op);
100
+ }
101
+ }
102
+ });
103
+ });
104
+
105
+ if (meta?.columns) {
106
+ result.select = Array.isArray(meta.columns)
107
+ ? meta.columns.join(',')
108
+ : meta.columns;
109
+ }
110
+
111
+ return result;
112
+ };
113
+
114
+ // compound keys capability
115
+ export type PrimaryKey = Array<string>;
116
+
117
+ export const getPrimaryKey = (
118
+ resource: string,
119
+ primaryKeys: Map<string, PrimaryKey>
120
+ ) => {
121
+ return primaryKeys.get(resource) || ['id'];
122
+ };
123
+
124
+ export const decodeId = (
125
+ id: Identifier,
126
+ primaryKey: PrimaryKey
127
+ ): string[] | number[] => {
128
+ if (isCompoundKey(primaryKey)) {
129
+ return JSON.parse(id.toString());
130
+ } else {
131
+ return [id.toString()];
132
+ }
133
+ };
134
+
135
+ export const encodeId = (data: any, primaryKey: PrimaryKey): Identifier => {
136
+ if (isCompoundKey(primaryKey)) {
137
+ return JSON.stringify(primaryKey.map(key => data[key]));
138
+ } else {
139
+ return data[primaryKey[0]];
140
+ }
141
+ };
142
+
143
+ export const dataWithId = (data: any, primaryKey: PrimaryKey) => {
144
+ if (JSON.stringify(primaryKey) === JSON.stringify(['id'])) {
145
+ return data;
146
+ }
147
+
148
+ return Object.assign(data, {
149
+ id: encodeId(data, primaryKey),
150
+ });
151
+ };
152
+
153
+ export const isCompoundKey = (primaryKey: PrimaryKey): Boolean => {
154
+ return primaryKey.length > 1;
155
+ };
156
+
157
+ export const getQuery = (
158
+ primaryKey: PrimaryKey,
159
+ ids: Identifier | Array<Identifier>,
160
+ resource: string,
161
+ meta: any = null
162
+ ): any => {
163
+ let result: any = {};
164
+ if (Array.isArray(ids) && ids.length > 1) {
165
+ // no standardized query with multiple ids possible for rpc endpoints which are api-exposed database functions
166
+ if (resource.startsWith('rpc/')) {
167
+ console.error(
168
+ "PostgREST's rpc endpoints are not intended to be handled as views. Therefore, no query generation for multiple key values implemented!"
169
+ );
170
+
171
+ return;
172
+ }
173
+
174
+ if (isCompoundKey(primaryKey)) {
175
+ result = {
176
+ or: `(${ids.map(id => {
177
+ const primaryKeyParams = decodeId(id, primaryKey);
178
+ return `and(${primaryKey
179
+ .map((key, i) => `${key}.eq.${primaryKeyParams[i]}`)
180
+ .join(',')})`;
181
+ })})`,
182
+ };
183
+ } else {
184
+ result = {
185
+ [primaryKey[0]]: `in.(${ids.join(',')})`,
186
+ };
187
+ }
188
+ } else {
189
+ // if ids is one Identifier
190
+ const id: Identifier = ids.toString();
191
+ const primaryKeyParams = decodeId(id, primaryKey);
192
+
193
+ if (isCompoundKey(primaryKey)) {
194
+ if (resource.startsWith('rpc/')) {
195
+ result = {};
196
+ primaryKey.map(
197
+ (key: string, i: any) =>
198
+ (result[key] = `${primaryKeyParams[i]}`)
199
+ );
200
+ } else {
201
+ result = {
202
+ and: `(${primaryKey.map(
203
+ (key: string, i: any) =>
204
+ `${key}.eq.${primaryKeyParams[i]}`
205
+ )})`,
206
+ };
207
+ }
208
+ } else {
209
+ result = {
210
+ [primaryKey[0]]: `eq.${id}`,
211
+ };
212
+ }
213
+ }
214
+
215
+ if (meta && meta.columns) {
216
+ result.select = Array.isArray(meta.columns)
217
+ ? meta.columns.join(',')
218
+ : meta.columns;
219
+ }
220
+
221
+ return result;
222
+ };
223
+
224
+ export const getKeyData = (primaryKey: PrimaryKey, data: object): object => {
225
+ if (isCompoundKey(primaryKey)) {
226
+ return primaryKey.reduce(
227
+ (keyData, key) => ({
228
+ ...keyData,
229
+ [key]: data[key],
230
+ }),
231
+ {}
232
+ );
233
+ } else {
234
+ return { [primaryKey[0]]: data[primaryKey[0]] };
235
+ }
236
+ };
237
+
238
+ export const getOrderBy = (
239
+ field: string,
240
+ order: string,
241
+ primaryKey: PrimaryKey
242
+ ) => {
243
+ if (field == 'id') {
244
+ return primaryKey.map(key => `${key}.${order.toLowerCase()}`).join(',');
245
+ } else {
246
+ return `${field}.${order.toLowerCase()}`;
247
+ }
248
+ };
@@ -1,11 +0,0 @@
1
- declare const _default: {
2
- login: ({ username, password }: {
3
- username: any;
4
- password: any;
5
- }) => Promise<void>;
6
- logout: (params: any) => Promise<void>;
7
- checkAuth: (params: any) => Promise<void>;
8
- checkError: (error: any) => Promise<void>;
9
- getPermissions: (params: any) => Promise<any>;
10
- };
11
- export default _default;
@@ -1,58 +0,0 @@
1
- export default {
2
- login: function (_a) {
3
- var username = _a.username, password = _a.password;
4
- var request = new Request('rest/rpc/login', {
5
- method: 'POST',
6
- body: JSON.stringify({ email: username, password: password }),
7
- headers: new Headers({
8
- 'Content-Type': 'application/json',
9
- 'Accept': 'application/vnd.pgrst.object+json',
10
- 'Prefer': 'return=representation'
11
- }),
12
- });
13
- return fetch(request)
14
- .then(function (response) {
15
- if (response.status < 200 || response.status >= 300) {
16
- throw new Error(response.statusText);
17
- }
18
- return response.json();
19
- })
20
- .then(function (data) {
21
- localStorage.setItem('me', JSON.stringify(data));
22
- });
23
- },
24
- logout: function (params) {
25
- var request = new Request('rest/rpc/logout', {
26
- method: 'POST',
27
- headers: new Headers({
28
- 'Content-Type': 'application/json',
29
- 'Accept': 'application/vnd.pgrst.object+json',
30
- 'Prefer': 'return=representation'
31
- }),
32
- });
33
- return fetch(request)
34
- .then(function (response) {
35
- if (response.status < 200 || response.status >= 300) {
36
- throw new Error(response.statusText);
37
- }
38
- return response.json();
39
- })
40
- .then(function (data) {
41
- localStorage.removeItem('me');
42
- });
43
- },
44
- checkAuth: function (params) { return (localStorage.getItem('me') ? Promise.resolve() : Promise.reject()); },
45
- checkError: function (error) {
46
- var status = error.status;
47
- if (status === 401 || status === 403) {
48
- localStorage.removeItem('me');
49
- return Promise.reject();
50
- }
51
- return Promise.resolve();
52
- },
53
- getPermissions: function (params) {
54
- var _a;
55
- var role = (_a = JSON.parse(localStorage.getItem('me'))) === null || _a === void 0 ? void 0 : _a.role;
56
- return role ? Promise.resolve(role) : Promise.reject();
57
- },
58
- };
@@ -1,9 +0,0 @@
1
- import { fetchUtils, DataProvider } from 'ra-core';
2
- type PrimaryKey = Array<string>;
3
- declare const _default: (apiUrl: any, httpClient?: (url: any, options?: fetchUtils.Options) => Promise<{
4
- status: number;
5
- headers: Headers;
6
- body: string;
7
- json: any;
8
- }>, defaultListOp?: string, primaryKeys?: Map<string, PrimaryKey>) => DataProvider;
9
- export default _default;