@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.
package/lib/index.js CHANGED
@@ -1,10 +1,243 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
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);
4
12
  };
5
13
  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;
14
+ var ra_core_1 = require("ra-core");
15
+ var urlBuilder_1 = require("./urlBuilder");
16
+ /**
17
+ * Maps react-admin queries to a postgrest REST API
18
+ *
19
+ * This REST dialect uses postgrest syntax
20
+ *
21
+ * @see https://postgrest.org/en/stable/api.html#embedded-filters
22
+ *
23
+ * @example
24
+ *
25
+ * getList => GET http://my.api.url/posts?order=title.asc&offset=0&limit=24&filterField=eq.value
26
+ * getOne => GET http://my.api.url/posts?id=eq.123
27
+ * getMany => GET http://my.api.url/posts?id=in.(123,456,789)
28
+ * getManyReference => GET http://my.api.url/posts?author_id=eq.345
29
+ * create => POST http://my.api.url/posts
30
+ * update => PATCH http://my.api.url/posts?id=eq.123
31
+ * updateMany => PATCH http://my.api.url/posts?id=in.(123,456,789)
32
+ * delete => DELETE http://my.api.url/posts?id=eq.123
33
+ * deleteMany => DELETE http://my.api.url/posts?id=in.(123,456,789)
34
+ *
35
+ * @example
36
+ *
37
+ * import * as React from 'react';
38
+ * import { Admin, Resource } from 'react-admin';
39
+ * import postgrestRestProvider from '@promitheus/ra-data-postgrest';
40
+ *
41
+ * import { PostList } from './posts';
42
+ *
43
+ * const App = () => (
44
+ * <Admin dataProvider={postgrestRestProvider('http://path.to.my.api/')}>
45
+ * <Resource name="posts" list={PostList} />
46
+ * </Admin>
47
+ * );
48
+ *
49
+ * export default App;
50
+ */
51
+ var defaultPrimaryKeys = new Map();
52
+ exports.default = (function (apiUrl, httpClient, defaultListOp, primaryKeys) {
53
+ if (httpClient === void 0) { httpClient = ra_core_1.fetchUtils.fetchJson; }
54
+ if (defaultListOp === void 0) { defaultListOp = 'eq'; }
55
+ if (primaryKeys === void 0) { primaryKeys = defaultPrimaryKeys; }
56
+ return ({
57
+ getList: function (resource, params) {
58
+ var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, primaryKeys);
59
+ var _a = params.pagination, page = _a.page, perPage = _a.perPage;
60
+ var _b = params.sort, field = _b.field, order = _b.order;
61
+ var parsedFilter = (0, urlBuilder_1.parseFilters)(params.filter, defaultListOp);
62
+ var query = __assign({ order: (0, urlBuilder_1.getOrderBy)(field, order, primaryKey), offset: String((page - 1) * perPage), limit: String(perPage) }, parsedFilter);
63
+ // add header that Content-Range is in returned header
64
+ var options = {
65
+ headers: new Headers({
66
+ Accept: 'application/json',
67
+ Prefer: 'count=exact',
68
+ }),
69
+ };
70
+ var url = "".concat(apiUrl, "/").concat(resource, "?").concat(new URLSearchParams(query));
71
+ return httpClient(url, options).then(function (_a) {
72
+ var headers = _a.headers, json = _a.json;
73
+ if (!headers.has('content-range')) {
74
+ 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?");
75
+ }
76
+ return {
77
+ data: json.map(function (obj) { return (0, urlBuilder_1.dataWithId)(obj, primaryKey); }),
78
+ total: parseInt(headers.get('content-range').split('/').pop(), 10),
79
+ };
80
+ });
81
+ },
82
+ getOne: function (resource, params) {
83
+ var id = params.id;
84
+ var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, primaryKeys);
85
+ var query = (0, urlBuilder_1.getQuery)(primaryKey, id, resource);
86
+ var url = "".concat(apiUrl, "/").concat(resource, "?").concat(query);
87
+ return httpClient(url, {
88
+ headers: new Headers({
89
+ accept: 'application/vnd.pgrst.object+json',
90
+ }),
91
+ }).then(function (_a) {
92
+ var json = _a.json;
93
+ return ({
94
+ data: (0, urlBuilder_1.dataWithId)(json, primaryKey),
95
+ });
96
+ });
97
+ },
98
+ getMany: function (resource, params) {
99
+ var ids = params.ids;
100
+ var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, primaryKeys);
101
+ var query = (0, urlBuilder_1.getQuery)(primaryKey, ids, resource);
102
+ var url = "".concat(apiUrl, "/").concat(resource, "?").concat(query);
103
+ return httpClient(url).then(function (_a) {
104
+ var json = _a.json;
105
+ return ({
106
+ data: json.map(function (data) { return (0, urlBuilder_1.dataWithId)(data, primaryKey); }),
107
+ });
108
+ });
109
+ },
110
+ getManyReference: function (resource, params) {
111
+ var _a;
112
+ var _b = params.pagination, page = _b.page, perPage = _b.perPage;
113
+ var _c = params.sort, field = _c.field, order = _c.order;
114
+ var parsedFilter = (0, urlBuilder_1.parseFilters)(params.filter, defaultListOp);
115
+ var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, primaryKeys);
116
+ var query = params.target
117
+ ? __assign((_a = {}, _a[params.target] = "eq.".concat(params.id), _a.order = (0, urlBuilder_1.getOrderBy)(field, order, primaryKey), _a.offset = String((page - 1) * perPage), _a.limit = String(perPage), _a), parsedFilter) : __assign({ order: (0, urlBuilder_1.getOrderBy)(field, order, primaryKey), offset: String((page - 1) * perPage), limit: String(perPage) }, parsedFilter);
118
+ // add header that Content-Range is in returned header
119
+ var options = {
120
+ headers: new Headers({
121
+ Accept: 'application/json',
122
+ Prefer: 'count=exact',
123
+ }),
124
+ };
125
+ var url = "".concat(apiUrl, "/").concat(resource, "?").concat(new URLSearchParams(query));
126
+ return httpClient(url, options).then(function (_a) {
127
+ var headers = _a.headers, json = _a.json;
128
+ if (!headers.has('content-range')) {
129
+ 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?");
130
+ }
131
+ return {
132
+ data: json.map(function (data) { return (0, urlBuilder_1.dataWithId)(data, primaryKey); }),
133
+ total: parseInt(headers.get('content-range').split('/').pop(), 10),
134
+ };
135
+ });
136
+ },
137
+ update: function (resource, params) {
138
+ var id = params.id, data = params.data;
139
+ var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, primaryKeys);
140
+ var query = (0, urlBuilder_1.getQuery)(primaryKey, id, resource);
141
+ var primaryKeyData = (0, urlBuilder_1.getKeyData)(primaryKey, data);
142
+ var url = "".concat(apiUrl, "/").concat(resource, "?").concat(query);
143
+ var body = JSON.stringify(__assign(__assign({}, data), primaryKeyData));
144
+ return httpClient(url, {
145
+ method: 'PATCH',
146
+ headers: new Headers({
147
+ Accept: 'application/vnd.pgrst.object+json',
148
+ Prefer: 'return=representation',
149
+ 'Content-Type': 'application/json',
150
+ }),
151
+ body: body,
152
+ }).then(function (_a) {
153
+ var json = _a.json;
154
+ return ({ data: (0, urlBuilder_1.dataWithId)(json, primaryKey) });
155
+ });
156
+ },
157
+ updateMany: function (resource, params) {
158
+ var ids = params.ids;
159
+ var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, primaryKeys);
160
+ var body = JSON.stringify(params.ids.map(function (id) {
161
+ var data = params.data;
162
+ var primaryKeyParams = (0, urlBuilder_1.decodeId)(id, primaryKey);
163
+ var primaryKeyData = {};
164
+ if ((0, urlBuilder_1.isCompoundKey)(primaryKey)) {
165
+ primaryKey.forEach(function (key, index) {
166
+ primaryKeyData[key] = primaryKeyParams[index];
167
+ });
168
+ }
169
+ else {
170
+ primaryKeyData[primaryKey[0]] = primaryKeyParams[0];
171
+ }
172
+ return __assign(__assign({}, data), primaryKeyData);
173
+ }));
174
+ var url = "".concat(apiUrl, "/").concat(resource);
175
+ return httpClient(url, {
176
+ method: 'PATCH',
177
+ headers: new Headers({
178
+ Prefer: 'return=representation',
179
+ 'Content-Type': 'application/json',
180
+ }),
181
+ body: body,
182
+ }).then(function (_a) {
183
+ var json = _a.json;
184
+ return ({
185
+ data: json.map(function (data) { return (0, urlBuilder_1.encodeId)(data, primaryKey); }),
186
+ });
187
+ });
188
+ },
189
+ create: function (resource, params) {
190
+ var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, primaryKeys);
191
+ var url = "".concat(apiUrl, "/").concat(resource);
192
+ return httpClient(url, {
193
+ method: 'POST',
194
+ headers: new Headers({
195
+ Accept: 'application/vnd.pgrst.object+json',
196
+ Prefer: 'return=representation',
197
+ 'Content-Type': 'application/json',
198
+ }),
199
+ body: JSON.stringify(params.data),
200
+ }).then(function (_a) {
201
+ var json = _a.json;
202
+ return ({
203
+ data: __assign(__assign({}, params.data), { id: (0, urlBuilder_1.encodeId)(json, primaryKey) }),
204
+ });
205
+ });
206
+ },
207
+ delete: function (resource, params) {
208
+ var id = params.id;
209
+ var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, primaryKeys);
210
+ var query = (0, urlBuilder_1.getQuery)(primaryKey, id, resource);
211
+ var url = "".concat(apiUrl, "/").concat(resource, "?").concat(query);
212
+ return httpClient(url, {
213
+ method: 'DELETE',
214
+ headers: new Headers({
215
+ Accept: 'application/vnd.pgrst.object+json',
216
+ Prefer: 'return=representation',
217
+ 'Content-Type': 'application/json',
218
+ }),
219
+ }).then(function (_a) {
220
+ var json = _a.json;
221
+ return ({ data: (0, urlBuilder_1.dataWithId)(json, primaryKey) });
222
+ });
223
+ },
224
+ deleteMany: function (resource, params) {
225
+ var ids = params.ids;
226
+ var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, primaryKeys);
227
+ var query = (0, urlBuilder_1.getQuery)(primaryKey, ids, resource);
228
+ var url = "".concat(apiUrl, "/").concat(resource, "?").concat(query);
229
+ return httpClient(url, {
230
+ method: 'DELETE',
231
+ headers: new Headers({
232
+ Prefer: 'return=representation',
233
+ 'Content-Type': 'application/json',
234
+ }),
235
+ }).then(function (_a) {
236
+ var json = _a.json;
237
+ return ({
238
+ data: json.map(function (data) { return (0, urlBuilder_1.encodeId)(data, primaryKey); }),
239
+ });
240
+ });
241
+ },
242
+ });
243
+ });
@@ -0,0 +1,18 @@
1
+ import { Identifier } from 'ra-core';
2
+ /**
3
+ * List of all possible operators in PostgRest
4
+ * (https://postgrest.org/en/stable/api.html#operators)
5
+ */
6
+ declare const postgrestOperators: readonly ["eq", "gt", "gte", "lt", "lte", "neq", "like", "ilike", "match", "imatch", "in", "is", "fts", "plfts", "phfts", "wfts", "cs", "cd", "ov", "sl", "sr", "nxr", "nxl", "adj", "not", "or", "and"];
7
+ export type PostgRestOperator = typeof postgrestOperators[number];
8
+ export declare const parseFilters: (filter: Record<string, any>, defaultListOp: PostgRestOperator) => {};
9
+ export type PrimaryKey = Array<string>;
10
+ export declare const getPrimaryKey: (resource: string, primaryKeys: Map<string, PrimaryKey>) => PrimaryKey;
11
+ export declare const decodeId: (id: Identifier, primaryKey: PrimaryKey) => string[] | number[];
12
+ export declare const encodeId: (data: any, primaryKey: PrimaryKey) => Identifier;
13
+ export declare const dataWithId: (data: any, primaryKey: PrimaryKey) => any;
14
+ export declare const isCompoundKey: (primaryKey: PrimaryKey) => Boolean;
15
+ export declare const getQuery: (primaryKey: PrimaryKey, ids: Identifier | Array<Identifier>, resource: string) => string;
16
+ export declare const getKeyData: (primaryKey: PrimaryKey, data: object) => object;
17
+ export declare const getOrderBy: (field: string, order: string, primaryKey: PrimaryKey) => string;
18
+ export {};
@@ -0,0 +1,195 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.getOrderBy = exports.getKeyData = exports.getQuery = exports.isCompoundKey = exports.dataWithId = exports.encodeId = exports.decodeId = exports.getPrimaryKey = exports.parseFilters = void 0;
15
+ /**
16
+ * List of all possible operators in PostgRest
17
+ * (https://postgrest.org/en/stable/api.html#operators)
18
+ */
19
+ var postgrestOperators = [
20
+ 'eq',
21
+ 'gt',
22
+ 'gte',
23
+ 'lt',
24
+ 'lte',
25
+ 'neq',
26
+ 'like',
27
+ 'ilike',
28
+ 'match',
29
+ 'imatch',
30
+ 'in',
31
+ 'is',
32
+ 'fts',
33
+ 'plfts',
34
+ 'phfts',
35
+ 'wfts',
36
+ 'cs',
37
+ 'cd',
38
+ 'ov',
39
+ 'sl',
40
+ 'sr',
41
+ 'nxr',
42
+ 'nxl',
43
+ 'adj',
44
+ 'not',
45
+ 'or',
46
+ 'and',
47
+ ];
48
+ var parseFilters = function (filter, defaultListOp) {
49
+ var result = {};
50
+ Object.keys(filter).forEach(function (key) {
51
+ // key: the name of the object key
52
+ var splitKey = key.split('@');
53
+ var operation = splitKey.length == 2
54
+ ? splitKey[1]
55
+ : defaultListOp;
56
+ var values;
57
+ if (['like', 'ilike'].includes(operation)) {
58
+ // we split the search term in words
59
+ values = filter[key].trim().split(/\s+/);
60
+ }
61
+ else {
62
+ values = [filter[key]];
63
+ }
64
+ values.forEach(function (value) {
65
+ // if operator is intentionally blank, rpc syntax
66
+ var op = operation.includes('like')
67
+ ? "".concat(operation, ".*").concat(value, "*")
68
+ : operation.length == 0
69
+ ? "".concat(value)
70
+ : "".concat(operation, ".").concat(value);
71
+ if (result[splitKey[0]] === undefined) {
72
+ // first operator for the key, we add it to the dict
73
+ result[splitKey[0]] = op;
74
+ }
75
+ else {
76
+ if (!Array.isArray(result[splitKey[0]])) {
77
+ // second operator, we transform to an array
78
+ result[splitKey[0]] = [result[splitKey[0]], op];
79
+ }
80
+ else {
81
+ // third and subsequent, we add to array
82
+ result[splitKey[0]].push(op);
83
+ }
84
+ }
85
+ });
86
+ });
87
+ return result;
88
+ };
89
+ exports.parseFilters = parseFilters;
90
+ var getPrimaryKey = function (resource, primaryKeys) {
91
+ return primaryKeys.get(resource) || ['id'];
92
+ };
93
+ exports.getPrimaryKey = getPrimaryKey;
94
+ var decodeId = function (id, primaryKey) {
95
+ if ((0, exports.isCompoundKey)(primaryKey)) {
96
+ return JSON.parse(id.toString());
97
+ }
98
+ else {
99
+ return [id.toString()];
100
+ }
101
+ };
102
+ exports.decodeId = decodeId;
103
+ var encodeId = function (data, primaryKey) {
104
+ if ((0, exports.isCompoundKey)(primaryKey)) {
105
+ return JSON.stringify(primaryKey.map(function (key) { return data[key]; }));
106
+ }
107
+ else {
108
+ return data[primaryKey[0]];
109
+ }
110
+ };
111
+ exports.encodeId = encodeId;
112
+ var dataWithId = function (data, primaryKey) {
113
+ if (JSON.stringify(primaryKey) === JSON.stringify(['id'])) {
114
+ return data;
115
+ }
116
+ return Object.assign(data, {
117
+ id: (0, exports.encodeId)(data, primaryKey),
118
+ });
119
+ };
120
+ exports.dataWithId = dataWithId;
121
+ var isCompoundKey = function (primaryKey) {
122
+ return primaryKey.length > 1;
123
+ };
124
+ exports.isCompoundKey = isCompoundKey;
125
+ var getQuery = function (primaryKey, ids, resource) {
126
+ var _a;
127
+ if (Array.isArray(ids) && ids.length > 1) {
128
+ // no standardized query with multiple ids possible for rpc endpoints which are api-exposed database functions
129
+ if (resource.startsWith('rpc/')) {
130
+ console.error("PostgREST's rpc endpoints are not intended to be handled as views. Therefore, no query generation for multiple key values implemented!");
131
+ return;
132
+ }
133
+ if ((0, exports.isCompoundKey)(primaryKey)) {
134
+ // TODO: Should be URL encoded
135
+ return "or=(".concat(ids.map(function (id) {
136
+ var primaryKeyParams = (0, exports.decodeId)(id, primaryKey);
137
+ return "and(".concat(primaryKey
138
+ .map(function (key, i) { return "".concat(key, ".eq.").concat(primaryKeyParams[i]); })
139
+ .join(','), ")");
140
+ }), ")");
141
+ }
142
+ else {
143
+ return new URLSearchParams((_a = {},
144
+ _a[primaryKey[0]] = "in.(".concat(ids.join(','), ")"),
145
+ _a)).toString();
146
+ }
147
+ }
148
+ else {
149
+ // if ids is one Identifier
150
+ var id = ids.toString();
151
+ var primaryKeyParams_1 = (0, exports.decodeId)(id, primaryKey);
152
+ if ((0, exports.isCompoundKey)(primaryKey)) {
153
+ if (resource.startsWith('rpc/'))
154
+ // TODO: Should be URL encoded
155
+ return "".concat(primaryKey
156
+ .map(function (key, i) { return "".concat(key, "=").concat(primaryKeyParams_1[i]); })
157
+ .join('&'));
158
+ // TODO: Should be URL encoded
159
+ else
160
+ return "and=(".concat(primaryKey
161
+ .map(function (key, i) {
162
+ return "".concat(key, ".eq.").concat(primaryKeyParams_1[i]);
163
+ })
164
+ .join(','), ")");
165
+ }
166
+ else {
167
+ return new URLSearchParams([
168
+ [primaryKey[0], "eq.".concat(id)],
169
+ ]).toString();
170
+ }
171
+ }
172
+ };
173
+ exports.getQuery = getQuery;
174
+ var getKeyData = function (primaryKey, data) {
175
+ var _a;
176
+ if ((0, exports.isCompoundKey)(primaryKey)) {
177
+ return primaryKey.reduce(function (keyData, key) {
178
+ var _a;
179
+ return (__assign(__assign({}, keyData), (_a = {}, _a[key] = data[key], _a)));
180
+ }, {});
181
+ }
182
+ else {
183
+ return _a = {}, _a[primaryKey[0]] = data[primaryKey[0]], _a;
184
+ }
185
+ };
186
+ exports.getKeyData = getKeyData;
187
+ var getOrderBy = function (field, order, primaryKey) {
188
+ if (field == 'id') {
189
+ return primaryKey.map(function (key) { return "".concat(key, ".").concat(order.toLowerCase()); }).join(',');
190
+ }
191
+ else {
192
+ return "".concat(field, ".").concat(order.toLowerCase());
193
+ }
194
+ };
195
+ exports.getOrderBy = getOrderBy;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raphiniert/ra-data-postgrest",
3
- "version": "1.2.0",
3
+ "version": "2.0.0-alpha.0",
4
4
  "description": "postgREST data provider for react-admin",
5
5
  "main": "lib/index.js",
6
6
  "module": "esm/index.js",
@@ -20,17 +20,25 @@
20
20
  "bugs": "https://github.com/raphiniert-com/ra-data-postgrest/issues",
21
21
  "license": "MIT",
22
22
  "scripts": {
23
- "build": "yarn run build-cjs && yarn run build-esm",
23
+ "test": "jest --watch",
24
+ "build": "npm run build-cjs && npm run build-esm",
24
25
  "build-cjs": "rimraf ./lib && tsc",
25
26
  "build-esm": "rimraf ./esm && tsc --outDir esm --module es2015",
26
27
  "watch": "tsc --outDir esm --module es2015 --watch",
27
- "prepare": "install-peers"
28
+ "prepare": "install-peers",
29
+ "prettier": "prettier --config ./.prettierrc.js --write --list-different \"src/**/*.{js,json,ts,tsx,css,md}\""
28
30
  },
29
31
  "devDependencies": {
32
+ "@types/jest": "^28.1.4",
30
33
  "cross-env": "^7.0.3",
34
+ "eslint-config-prettier": "^8.5.0",
35
+ "eslint-plugin-prettier": "^4.2.1",
31
36
  "install-peers-cli": "^2.2.0",
37
+ "jest": "^28.1.2",
38
+ "prettier": "~2.1.1",
32
39
  "rimraf": "^3.0.2",
33
- "typescript": "^4.6.4"
40
+ "ts-jest": "^28.0.5",
41
+ "typescript": "^4.9.3"
34
42
  },
35
43
  "peerDependencies": {
36
44
  "ra-core": "^4.1.0"