@raphiniert/ra-data-postgrest 1.2.1 → 2.0.0-alpha.1

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