@raphiniert/ra-data-postgrest 1.1.3 → 1.1.7

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/CHANGELOG.md CHANGED
@@ -2,6 +2,27 @@
2
2
 
3
3
  Find all notable changes of this project in this file.
4
4
 
5
+ ## v1.1.7 - 2022-01-07
6
+ ### Fixes
7
+ - fixed bad behaivor with compound keys while using field named `id` [issue #27](https://github.com/raphiniert-com/ra-data-postgrest/issues/27) and [issue #19](https://github.com/raphiniert-com/ra-data-postgrest/pull/19) - @[kenfehling](https://github.com/kenfehling)
8
+
9
+ ### New feature
10
+ - added rpc filter support, which is explained [here](https://github.com/raphiniert-com/ra-data-postgrest#special-filter-feature-rpc-functions) - @[TheRealAstroboy](https://github.com/TheRealAstroboy)
11
+
12
+ ## v1.1.6 - 2021-01-16
13
+ ### Fixes
14
+ - fixed eq. prefix for non-compound keys [issue #23](https://github.com/raphiniert-com/ra-data-postgrest/issues/23) - @[andymed-jlp](https://github.com/andymed-jlp)
15
+
16
+ ## v1.1.5 - 2021-01-16
17
+ ### Fixes
18
+ - fixed query string generation of rpc endpoints [issue #22](https://github.com/raphiniert-com/ra-data-postgrest/issues/22)
19
+
20
+ ### Breaking changes
21
+ - Support was dropped for generating the query string given many ids in case of an rpc endpoint. If your application has some psql functions which parse the standard input, I recommend to rework your db design. If this change causes strong damage to your application, please contact me in order to find a proper generic solution. Query strings of single rpc calls now drop the operator (`eq.`) and are generated properly.
22
+
23
+ ## v1.1.4 - 2021-01-16
24
+ - deployment error
25
+
5
26
  ## v1.1.3 - 2020-11-30
6
27
  ### Fixes
7
28
  - [#20](https://github.com/raphiniert-com/ra-data-postgrest/pull/20), fixed small bug in update - @[mkkane](https://github.com/mkkane)
package/README.md CHANGED
@@ -135,6 +135,19 @@ The dataProvider is designed to enable you to specify the comparator in your rea
135
135
 
136
136
  One can simply append the comparator with an `@` to the source. In this example the field `post_title` would be filtered with `ilike` whereas `post_author` would be filtered using `eq` which is the default if no special comparator is specified.
137
137
 
138
+ ### Special Filter Feature (RPC Functions)
139
+ The dataProvider is designed to enable you to use Get RPC functions:
140
+
141
+ ```GET /rpc/add_them?post_author=Herbert HTTP/1.1```
142
+ The function parameter names match the query parameters ```&post_author=Herbert``` if you end the field with an `@` (neither default comparator nor special comparator)
143
+
144
+ ```jsx
145
+ <Filter {...props}>
146
+ <TextInput label="Search" source="post_title" alwaysOn />
147
+ <TextInput label="Search" source="post_author@" alwaysOn />
148
+ // some more filters
149
+ </Filter>
150
+ ```
138
151
 
139
152
  ### Compound primary keys
140
153
  If one has data resources without primary keys named `id`, one will have to define this specifically. Also, if there is a primary key, which is defined over multiple columns:
@@ -111,7 +111,7 @@ var encodeId = function (data, primaryKey) {
111
111
  }
112
112
  };
113
113
  var dataWithId = function (data, primaryKey) {
114
- if (primaryKey === ['id'] || (data && data.id)) {
114
+ if (primaryKey === ['id']) {
115
115
  return data;
116
116
  }
117
117
  return Object.assign(data, {
@@ -121,14 +121,19 @@ var dataWithId = function (data, primaryKey) {
121
121
  var isCompoundKey = function (primaryKey) {
122
122
  return primaryKey.length > 1;
123
123
  };
124
- var getQuery = function (primaryKey, ids) {
124
+ var getQuery = function (primaryKey, ids, resource) {
125
125
  var _a, _b;
126
- if (Array.isArray(ids)) {
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
+ }
127
132
  if (isCompoundKey(primaryKey)) {
128
- return "or=(" + ids.map(function (id) {
133
+ return "or=(\n " + ids.map(function (id) {
129
134
  var primaryKeyParams = decodeId(id, primaryKey);
130
135
  return "and(" + primaryKey.map(function (key, i) { return key + ".eq." + primaryKeyParams[i]; }).join(',') + ")";
131
- }) + ")";
136
+ }) + "\n )";
132
137
  }
133
138
  else {
134
139
  return stringify((_a = {}, _a[primaryKey[0]] = "in.(" + ids.join(',') + ")", _a));
@@ -136,10 +141,13 @@ var getQuery = function (primaryKey, ids) {
136
141
  }
137
142
  else {
138
143
  // if ids is one Identifier
139
- var id = ids;
144
+ var id = ids.toString();
140
145
  var primaryKeyParams_1 = decodeId(id, primaryKey);
141
146
  if (isCompoundKey(primaryKey)) {
142
- return "and=(" + primaryKey.map(function (key, i) { return key + ".eq." + primaryKeyParams_1[i]; }).join(',') + ")";
147
+ if (resource.startsWith('rpc/'))
148
+ return "" + primaryKey.map(function (key, i) { return key + "=" + primaryKeyParams_1[i]; }).join('&');
149
+ else
150
+ return "and=(" + primaryKey.map(function (key, i) { return key + ".eq." + primaryKeyParams_1[i]; }).join(',') + ")";
143
151
  }
144
152
  else {
145
153
  return stringify((_b = {}, _b[primaryKey[0]] = "eq." + id, _b));
@@ -203,7 +211,7 @@ export default (function (apiUrl, httpClient, defaultListOp, primaryKeys) {
203
211
  getOne: function (resource, params) {
204
212
  var id = params.id;
205
213
  var primaryKey = getPrimaryKey(resource, primaryKeys);
206
- var query = getQuery(primaryKey, id);
214
+ var query = getQuery(primaryKey, id, resource);
207
215
  var url = apiUrl + "/" + resource + "?" + query;
208
216
  return httpClient(url, {
209
217
  headers: new Headers({ 'accept': 'application/vnd.pgrst.object+json' }),
@@ -217,7 +225,7 @@ export default (function (apiUrl, httpClient, defaultListOp, primaryKeys) {
217
225
  getMany: function (resource, params) {
218
226
  var ids = params.ids;
219
227
  var primaryKey = getPrimaryKey(resource, primaryKeys);
220
- var query = getQuery(primaryKey, ids);
228
+ var query = getQuery(primaryKey, ids, resource);
221
229
  var url = apiUrl + "/" + resource + "?" + query;
222
230
  return httpClient(url).then(function (_a) {
223
231
  var json = _a.json;
@@ -256,7 +264,7 @@ export default (function (apiUrl, httpClient, defaultListOp, primaryKeys) {
256
264
  update: function (resource, params) {
257
265
  var id = params.id, data = params.data;
258
266
  var primaryKey = getPrimaryKey(resource, primaryKeys);
259
- var query = getQuery(primaryKey, id);
267
+ var query = getQuery(primaryKey, id, resource);
260
268
  var primaryKeyData = getKeyData(primaryKey, data);
261
269
  var url = apiUrl + "/" + resource + "?" + query;
262
270
  var body = JSON.stringify(__assign(__assign({}, data), primaryKeyData));
@@ -276,7 +284,7 @@ export default (function (apiUrl, httpClient, defaultListOp, primaryKeys) {
276
284
  updateMany: function (resource, params) {
277
285
  var ids = params.ids;
278
286
  var primaryKey = getPrimaryKey(resource, primaryKeys);
279
- var query = getQuery(primaryKey, ids);
287
+ var query = getQuery(primaryKey, ids, resource);
280
288
  var body = JSON.stringify(params.data.map(function (obj) {
281
289
  var id = obj.id, data = __rest(obj, ["id"]);
282
290
  var primaryKeyData = getKeyData(primaryKey, data);
@@ -318,7 +326,7 @@ export default (function (apiUrl, httpClient, defaultListOp, primaryKeys) {
318
326
  delete: function (resource, params) {
319
327
  var id = params.id;
320
328
  var primaryKey = getPrimaryKey(resource, primaryKeys);
321
- var query = getQuery(primaryKey, id);
329
+ var query = getQuery(primaryKey, id, resource);
322
330
  var url = apiUrl + "/" + resource + "?" + query;
323
331
  return httpClient(url, {
324
332
  method: 'DELETE',
@@ -335,7 +343,7 @@ export default (function (apiUrl, httpClient, defaultListOp, primaryKeys) {
335
343
  deleteMany: function (resource, params) {
336
344
  var ids = params.ids;
337
345
  var primaryKey = getPrimaryKey(resource, primaryKeys);
338
- var query = getQuery(primaryKey, ids);
346
+ var query = getQuery(primaryKey, ids, resource);
339
347
  var url = apiUrl + "/" + resource + "?" + query;
340
348
  return httpClient(url, {
341
349
  method: 'DELETE',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raphiniert/ra-data-postgrest",
3
- "version": "1.1.3",
3
+ "version": "1.1.7",
4
4
  "description": "postgREST data provider for react-admin",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",
@@ -53,7 +53,9 @@ function parseFilters(filter, defaultListOp) {
53
53
  }
54
54
 
55
55
  values.forEach(value => {
56
- let op = operation.includes('like') ? `${operation}.*${value}*` : `${operation}.${value}`;
56
+ // if operator is intentionally blank, rpc syntax
57
+ let op = operation.includes('like') ? `${operation}.*${value}*` : operation.length == 0 ? `${value}` : `${operation}.${value}`;
58
+
57
59
  if (result[splitKey[0]] === undefined) {
58
60
  // first operator for the key, we add it to the dict
59
61
  result[splitKey[0]] = op;
@@ -99,7 +101,7 @@ const encodeId = (data: any, primaryKey: PrimaryKey): Identifier => {
99
101
  }
100
102
 
101
103
  const dataWithId = (data: any, primaryKey: PrimaryKey) => {
102
- if (primaryKey === ['id'] || (data && data.id)) {
104
+ if (primaryKey === ['id']) {
103
105
  return data;
104
106
  }
105
107
 
@@ -112,24 +114,36 @@ const isCompoundKey = (primaryKey: PrimaryKey) : Boolean => {
112
114
  return primaryKey.length > 1;
113
115
  }
114
116
 
115
- const getQuery = (primaryKey : PrimaryKey, ids: Identifier | Array<Identifier>) : string => {
116
- if (Array.isArray(ids)) {
117
+ const getQuery = (primaryKey : PrimaryKey, ids: Identifier | Array<Identifier>, resource: string) : string => {
118
+ if (Array.isArray(ids) && ids.length > 1) {
119
+ // no standardized query with multiple ids possible for rpc endpoints which are api-exposed database functions
120
+ if (resource.startsWith('rpc/')) {
121
+ console.error('PostgREST\'s rpc endpoints are not intended to be handled as views. Therefore, no query generation for multiple key values implemented!');
122
+
123
+ return ;
124
+ }
125
+
117
126
  if (isCompoundKey(primaryKey)) {
118
- return `or=(${ids.map(id => {
119
- const primaryKeyParams = decodeId(id, primaryKey);
120
- return `and(${primaryKey.map((key, i) => `${key}.eq.${primaryKeyParams[i]}`).join(',')})`;
121
- }
122
- )})`
127
+ return `or=(
128
+ ${ids.map(id => {
129
+ const primaryKeyParams = decodeId(id, primaryKey);
130
+ return `and(${primaryKey.map((key, i) => `${key}.eq.${primaryKeyParams[i]}`).join(',')})`;
131
+ })
132
+ }
133
+ )`;
123
134
  } else {
124
135
  return stringify({ [primaryKey[0]]: `in.(${ids.join(',')})` });
125
136
  }
126
137
  } else {
127
138
  // if ids is one Identifier
128
- const id = ids;
139
+ const id : Identifier = ids.toString();
129
140
  const primaryKeyParams = decodeId(id, primaryKey);
130
141
 
131
142
  if (isCompoundKey(primaryKey)) {
132
- return `and=(${primaryKey.map((key : string, i: any) => `${key}.eq.${primaryKeyParams[i]}`).join(',')})`;
143
+ if (resource.startsWith('rpc/'))
144
+ return `${primaryKey.map((key : string, i: any) => `${key}=${primaryKeyParams[i]}`).join('&')}`;
145
+ else
146
+ return `and=(${primaryKey.map((key : string, i: any) => `${key}.eq.${primaryKeyParams[i]}`).join(',')})`;
133
147
  } else {
134
148
  return stringify({ [primaryKey[0]]: `eq.${id}` });
135
149
  }
@@ -211,7 +225,7 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson, defaultListOp = 'eq',
211
225
  const id = params.id;
212
226
  const primaryKey = getPrimaryKey(resource, primaryKeys);
213
227
 
214
- const query = getQuery(primaryKey, id);
228
+ const query = getQuery(primaryKey, id, resource);
215
229
 
216
230
  const url = `${apiUrl}/${resource}?${query}`;
217
231
 
@@ -226,7 +240,7 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson, defaultListOp = 'eq',
226
240
  const ids = params.ids;
227
241
  const primaryKey = getPrimaryKey(resource, primaryKeys);
228
242
 
229
- const query = getQuery(primaryKey, ids);
243
+ const query = getQuery(primaryKey, ids, resource);
230
244
 
231
245
  const url = `${apiUrl}/${resource}?${query}`;
232
246
 
@@ -239,12 +253,17 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson, defaultListOp = 'eq',
239
253
  const parsedFilter = parseFilters(params.filter, defaultListOp);
240
254
  const primaryKey = getPrimaryKey(resource, primaryKeys);
241
255
 
242
- const query = {
256
+ const query = params.target ? {
243
257
  [params.target]: `eq.${params.id}`,
244
258
  order: getOrderBy(field, order, primaryKey),
245
259
  offset: (page - 1) * perPage,
246
260
  limit: perPage,
247
261
  ...parsedFilter,
262
+ }:{
263
+ order: getOrderBy(field, order, primaryKey),
264
+ offset: (page - 1) * perPage,
265
+ limit: perPage,
266
+ ...parsedFilter,
248
267
  };
249
268
 
250
269
  // add header that Content-Range is in returned header
@@ -282,7 +301,7 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson, defaultListOp = 'eq',
282
301
  const { id, data } = params;
283
302
  const primaryKey = getPrimaryKey(resource, primaryKeys);
284
303
 
285
- const query = getQuery(primaryKey, id);
304
+ const query = getQuery(primaryKey, id, resource);
286
305
 
287
306
  const primaryKeyData = getKeyData(primaryKey, data);
288
307
 
@@ -308,7 +327,7 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson, defaultListOp = 'eq',
308
327
  const ids = params.ids;
309
328
  const primaryKey = getPrimaryKey(resource, primaryKeys);
310
329
 
311
- const query = getQuery(primaryKey, ids);
330
+ const query = getQuery(primaryKey, ids, resource);
312
331
 
313
332
  const body = JSON.stringify(
314
333
  params.data.map(obj => {
@@ -361,7 +380,7 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson, defaultListOp = 'eq',
361
380
  const id = params.id;
362
381
  const primaryKey = getPrimaryKey(resource, primaryKeys);
363
382
 
364
- const query = getQuery(primaryKey, id);
383
+ const query = getQuery(primaryKey, id, resource);
365
384
 
366
385
  const url = `${apiUrl}/${resource}?${query}`;
367
386
 
@@ -379,7 +398,7 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson, defaultListOp = 'eq',
379
398
  const ids = params.ids;
380
399
  const primaryKey = getPrimaryKey(resource, primaryKeys);
381
400
 
382
- const query = getQuery(primaryKey, ids);
401
+ const query = getQuery(primaryKey, ids, resource);
383
402
 
384
403
  const url = `${apiUrl}/${resource}?${query}`;
385
404
 
@@ -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;
@@ -1,354 +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 query_string_1 = require("query-string");
26
- var ra_core_1 = require("ra-core");
27
- /**
28
- * Maps react-admin queries to a postgrest REST API
29
- *
30
- * This REST dialect uses postgrest syntax
31
- *
32
- * @see https://postgrest.org/en/stable/api.html#embedded-filters
33
- *
34
- * @example
35
- *
36
- * getList => GET http://my.api.url/posts?order=title.asc&offset=0&limit=24&filterField=eq.value
37
- * getOne => GET http://my.api.url/posts?id=eq.123
38
- * getMany => GET http://my.api.url/posts?id=in.(123,456,789)
39
- * getManyReference => GET http://my.api.url/posts?author_id=eq.345
40
- * create => POST http://my.api.url/posts
41
- * update => PATCH http://my.api.url/posts?id=eq.123
42
- * updateMany => PATCH http://my.api.url/posts?id=in.(123,456,789)
43
- * delete => DELETE http://my.api.url/posts?id=eq.123
44
- * deleteMany => DELETE http://my.api.url/posts?id=in.(123,456,789)
45
- *
46
- * @example
47
- *
48
- * import * as React from 'react';
49
- * import { Admin, Resource } from 'react-admin';
50
- * import postgrestRestProvider from '@raphiniert/ra-data-postgrest';
51
- *
52
- * import { PostList } from './posts';
53
- *
54
- * const App = () => (
55
- * <Admin dataProvider={postgrestRestProvider('http://path.to.my.api/')}>
56
- * <Resource name="posts" list={PostList} />
57
- * </Admin>
58
- * );
59
- *
60
- * export default App;
61
- */
62
- function parseFilters(filter, defaultListOp) {
63
- var result = {};
64
- Object.keys(filter).forEach(function (key) {
65
- // key: the name of the object key
66
- var splitKey = key.split('@');
67
- var operation = splitKey.length == 2 ? splitKey[1] : defaultListOp;
68
- var values;
69
- if (operation.includes('like')) {
70
- // we split the search term in words
71
- values = filter[key].trim().split(' ');
72
- }
73
- else {
74
- values = [filter[key]];
75
- }
76
- values.forEach(function (value) {
77
- var op = operation.includes('like') ? operation + ".*" + value + "*" : operation + "." + 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'] || (data && data.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) {
127
- var _a, _b;
128
- if (Array.isArray(ids)) {
129
- if (isCompoundKey(primaryKey)) {
130
- return "or=(" + ids.map(function (id) {
131
- var primaryKeyParams = decodeId(id, primaryKey);
132
- return "and(" + primaryKey.map(function (key, i) { return key + ".eq." + primaryKeyParams[i]; }).join(',') + ")";
133
- }) + ")";
134
- }
135
- else {
136
- return query_string_1.stringify((_a = {}, _a[primaryKey[0]] = "in.(" + ids.join(',') + ")", _a));
137
- }
138
- }
139
- else {
140
- // if ids is one Identifier
141
- var id = ids;
142
- var primaryKeyParams_1 = decodeId(id, primaryKey);
143
- if (isCompoundKey(primaryKey)) {
144
- return "and=(" + primaryKey.map(function (key, i) { return key + ".eq." + primaryKeyParams_1[i]; }).join(',') + ")";
145
- }
146
- else {
147
- return query_string_1.stringify((_b = {}, _b[primaryKey[0]] = "eq." + id, _b));
148
- }
149
- }
150
- };
151
- var getKeyData = function (primaryKey, data) {
152
- var _a;
153
- if (isCompoundKey(primaryKey)) {
154
- return primaryKey.reduce(function (keyData, key) {
155
- var _a;
156
- return (__assign(__assign({}, keyData), (_a = {}, _a[key] = data[key], _a)));
157
- }, {});
158
- }
159
- else {
160
- return _a = {}, _a[primaryKey[0]] = data[primaryKey[0]], _a;
161
- }
162
- };
163
- var getOrderBy = function (field, order, primaryKey) {
164
- if (field == 'id') {
165
- return primaryKey.map(function (key) { return (key + "." + order.toLowerCase()); }).join(',');
166
- }
167
- else {
168
- return field + "." + order.toLowerCase();
169
- }
170
- };
171
- var defaultPrimaryKeys = new Map();
172
- exports.default = (function (apiUrl, httpClient, defaultListOp, primaryKeys) {
173
- if (httpClient === void 0) { httpClient = ra_core_1.fetchUtils.fetchJson; }
174
- if (defaultListOp === void 0) { defaultListOp = 'eq'; }
175
- if (primaryKeys === void 0) { primaryKeys = defaultPrimaryKeys; }
176
- return ({
177
- getList: function (resource, params) {
178
- var primaryKey = getPrimaryKey(resource, primaryKeys);
179
- var _a = params.pagination, page = _a.page, perPage = _a.perPage;
180
- var _b = params.sort, field = _b.field, order = _b.order;
181
- var parsedFilter = parseFilters(params.filter, defaultListOp);
182
- var query = __assign({ order: getOrderBy(field, order, primaryKey), offset: (page - 1) * perPage, limit: perPage }, parsedFilter);
183
- // add header that Content-Range is in returned header
184
- var options = {
185
- headers: new Headers({
186
- Accept: 'application/json',
187
- Prefer: 'count=exact'
188
- })
189
- };
190
- var url = apiUrl + "/" + resource + "?" + query_string_1.stringify(query);
191
- return httpClient(url, options).then(function (_a) {
192
- var headers = _a.headers, json = _a.json;
193
- if (!headers.has('content-range')) {
194
- 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?");
195
- }
196
- return {
197
- data: json.map(function (obj) { return dataWithId(obj, primaryKey); }),
198
- total: parseInt(headers
199
- .get('content-range')
200
- .split('/')
201
- .pop(), 10)
202
- };
203
- });
204
- },
205
- getOne: function (resource, params) {
206
- var id = params.id;
207
- var primaryKey = getPrimaryKey(resource, primaryKeys);
208
- var query = getQuery(primaryKey, id);
209
- var url = apiUrl + "/" + resource + "?" + query;
210
- return httpClient(url, {
211
- headers: new Headers({ 'accept': 'application/vnd.pgrst.object+json' }),
212
- }).then(function (_a) {
213
- var json = _a.json;
214
- return ({
215
- data: dataWithId(json, primaryKey),
216
- });
217
- });
218
- },
219
- getMany: function (resource, params) {
220
- var ids = params.ids;
221
- var primaryKey = getPrimaryKey(resource, primaryKeys);
222
- var query = getQuery(primaryKey, ids);
223
- var url = apiUrl + "/" + resource + "?" + query;
224
- return httpClient(url).then(function (_a) {
225
- var json = _a.json;
226
- return ({ data: json.map(function (data) { return dataWithId(data, primaryKey); }) });
227
- });
228
- },
229
- getManyReference: function (resource, params) {
230
- var _a;
231
- var _b = params.pagination, page = _b.page, perPage = _b.perPage;
232
- var _c = params.sort, field = _c.field, order = _c.order;
233
- var parsedFilter = parseFilters(params.filter, defaultListOp);
234
- var primaryKey = getPrimaryKey(resource, primaryKeys);
235
- var query = __assign((_a = {}, _a[params.target] = "eq." + params.id, _a.order = getOrderBy(field, order, primaryKey), _a.offset = (page - 1) * perPage, _a.limit = perPage, _a), parsedFilter);
236
- // add header that Content-Range is in returned header
237
- var options = {
238
- headers: new Headers({
239
- Accept: 'application/json',
240
- Prefer: 'count=exact'
241
- })
242
- };
243
- var url = apiUrl + "/" + resource + "?" + query_string_1.stringify(query);
244
- return httpClient(url, options).then(function (_a) {
245
- var headers = _a.headers, json = _a.json;
246
- if (!headers.has('content-range')) {
247
- 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?");
248
- }
249
- return {
250
- data: json.map(function (data) { return dataWithId(data, primaryKey); }),
251
- total: parseInt(headers
252
- .get('content-range')
253
- .split('/')
254
- .pop(), 10),
255
- };
256
- });
257
- },
258
- update: function (resource, params) {
259
- var id = params.id, data = params.data;
260
- var primaryKey = getPrimaryKey(resource, primaryKeys);
261
- var query = getQuery(primaryKey, id);
262
- var primaryKeyData = getKeyData(primaryKey, data);
263
- var url = apiUrl + "/" + resource + "?" + query;
264
- var body = JSON.stringify(__assign(__assign({}, data), primaryKeyData));
265
- return httpClient(url, {
266
- method: 'PATCH',
267
- headers: new Headers({
268
- 'Accept': 'application/vnd.pgrst.object+json',
269
- 'Prefer': 'return=representation',
270
- 'Content-Type': 'application/json'
271
- }),
272
- body: body,
273
- }).then(function (_a) {
274
- var json = _a.json;
275
- return ({ data: dataWithId(json, primaryKey) });
276
- });
277
- },
278
- updateMany: function (resource, params) {
279
- var ids = params.ids;
280
- var primaryKey = getPrimaryKey(resource, primaryKeys);
281
- var query = getQuery(primaryKey, ids);
282
- var body = JSON.stringify(params.data.map(function (obj) {
283
- var id = obj.id, data = __rest(obj, ["id"]);
284
- var primaryKeyData = getKeyData(primaryKey, data);
285
- return __assign(__assign({}, data), primaryKeyData);
286
- }));
287
- var url = apiUrl + "/" + resource + "?" + query;
288
- return httpClient(url, {
289
- method: 'PATCH',
290
- headers: new Headers({
291
- 'Prefer': 'return=representation',
292
- 'Content-Type': 'application/json',
293
- }),
294
- body: body,
295
- }).then(function (_a) {
296
- var json = _a.json;
297
- return ({
298
- data: json.map(function (data) { return encodeId(data, primaryKey); })
299
- });
300
- });
301
- },
302
- create: function (resource, params) {
303
- var primaryKey = getPrimaryKey(resource, primaryKeys);
304
- var url = apiUrl + "/" + resource;
305
- return httpClient(url, {
306
- method: 'POST',
307
- headers: new Headers({
308
- 'Accept': 'application/vnd.pgrst.object+json',
309
- 'Prefer': 'return=representation',
310
- 'Content-Type': 'application/json'
311
- }),
312
- body: JSON.stringify(params.data),
313
- }).then(function (_a) {
314
- var json = _a.json;
315
- return ({
316
- data: __assign(__assign({}, params.data), { id: encodeId(json, primaryKey) })
317
- });
318
- });
319
- },
320
- delete: function (resource, params) {
321
- var id = params.id;
322
- var primaryKey = getPrimaryKey(resource, primaryKeys);
323
- var query = getQuery(primaryKey, id);
324
- var url = apiUrl + "/" + resource + "?" + query;
325
- return httpClient(url, {
326
- method: 'DELETE',
327
- headers: new Headers({
328
- 'Accept': 'application/vnd.pgrst.object+json',
329
- 'Prefer': 'return=representation',
330
- 'Content-Type': 'application/json'
331
- }),
332
- }).then(function (_a) {
333
- var json = _a.json;
334
- return ({ data: dataWithId(json, primaryKey) });
335
- });
336
- },
337
- deleteMany: function (resource, params) {
338
- var ids = params.ids;
339
- var primaryKey = getPrimaryKey(resource, primaryKeys);
340
- var query = getQuery(primaryKey, ids);
341
- var url = apiUrl + "/" + resource + "?" + query;
342
- return httpClient(url, {
343
- method: 'DELETE',
344
- headers: new Headers({
345
- 'Prefer': 'return=representation',
346
- 'Content-Type': 'application/json'
347
- }),
348
- }).then(function (_a) {
349
- var json = _a.json;
350
- return ({ data: json.map(function (data) { return encodeId(data, primaryKey); }) });
351
- });
352
- },
353
- });
354
- });
package/lib/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- import dataProvider from './dataProvider';
2
- import authProvider from './authProvider';
3
- export { authProvider };
4
- export default dataProvider;
package/lib/index.js DELETED
@@ -1,10 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.authProvider = void 0;
7
- var dataProvider_1 = __importDefault(require("./dataProvider"));
8
- var authProvider_1 = __importDefault(require("./authProvider"));
9
- exports.authProvider = authProvider_1.default;
10
- exports.default = dataProvider_1.default;