@raphiniert/ra-data-postgrest 1.1.6 → 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,13 @@
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
+
5
12
  ## v1.1.6 - 2021-01-16
6
13
  ### Fixes
7
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)
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, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raphiniert/ra-data-postgrest",
3
- "version": "1.1.6",
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
 
@@ -251,12 +253,17 @@ export default (apiUrl, httpClient = fetchUtils.fetchJson, defaultListOp = 'eq',
251
253
  const parsedFilter = parseFilters(params.filter, defaultListOp);
252
254
  const primaryKey = getPrimaryKey(resource, primaryKeys);
253
255
 
254
- const query = {
256
+ const query = params.target ? {
255
257
  [params.target]: `eq.${params.id}`,
256
258
  order: getOrderBy(field, order, primaryKey),
257
259
  offset: (page - 1) * perPage,
258
260
  limit: perPage,
259
261
  ...parsedFilter,
262
+ }:{
263
+ order: getOrderBy(field, order, primaryKey),
264
+ offset: (page - 1) * perPage,
265
+ limit: perPage,
266
+ ...parsedFilter,
260
267
  };
261
268
 
262
269
  // add header that Content-Range is in returned header
@@ -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,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 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, resource) {
127
- var _a, _b;
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 " + ids.map(function (id) {
136
- var primaryKeyParams = decodeId(id, primaryKey);
137
- return "and(" + primaryKey.map(function (key, i) { return key + ".eq." + primaryKeyParams[i]; }).join(',') + ")";
138
- }) + "\n )";
139
- }
140
- else {
141
- return query_string_1.stringify((_a = {}, _a[primaryKey[0]] = "in.(" + ids.join(',') + ")", _a));
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 "" + primaryKey.map(function (key, i) { return key + "=" + primaryKeyParams_1[i]; }).join('&');
151
- else
152
- return "and=(" + primaryKey.map(function (key, i) { return key + ".eq." + primaryKeyParams_1[i]; }).join(',') + ")";
153
- }
154
- else {
155
- return query_string_1.stringify((_b = {}, _b[primaryKey[0]] = "eq." + id, _b));
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 (key + "." + order.toLowerCase()); }).join(',');
174
- }
175
- else {
176
- return field + "." + 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: (page - 1) * perPage, limit: 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 = apiUrl + "/" + resource + "?" + query_string_1.stringify(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 = apiUrl + "/" + resource + "?" + 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 = apiUrl + "/" + resource + "?" + 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 = __assign((_a = {}, _a[params.target] = "eq." + params.id, _a.order = getOrderBy(field, order, primaryKey), _a.offset = (page - 1) * perPage, _a.limit = perPage, _a), 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 = apiUrl + "/" + resource + "?" + query_string_1.stringify(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 = apiUrl + "/" + resource + "?" + 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 = apiUrl + "/" + resource + "?" + 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 = apiUrl + "/" + 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 = apiUrl + "/" + resource + "?" + 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 = apiUrl + "/" + resource + "?" + 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
- });
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;