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