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