@raphiniert/ra-data-postgrest 2.0.0 → 2.2.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/README.md CHANGED
@@ -1,232 +1,247 @@
1
- # PostgREST Data Provider For React-Admin
2
- [![npm](https://img.shields.io/npm/v/@raphiniert/ra-data-postgrest.svg)](https://www.npmjs.com/package/@raphiniert/ra-data-postgrest)
3
- [![npm downloads](https://img.shields.io/npm/dm/@raphiniert/ra-data-postgrest.svg)](https://www.npmjs.com/package/@raphiniert/ra-data-postgrest)
4
- [![Coverage Status](https://coveralls.io/repos/github/raphiniert-com/ra-data-postgrest/badge.svg?branch=master)](https://coveralls.io/github/raphiniert-com/ra-data-postgrest?branch=master)
5
- [![License: MIT](https://img.shields.io/gitlab/license/24181795)](https://github.com/raphiniert-com/ra-data-postgrest/blob/master/LICENSE)
6
-
7
-
8
- PostgREST Data Provider for [react-admin](https://github.com/marmelab/react-admin), the frontend framework for building admin applications on top of REST/GraphQL services.
9
-
10
- ## Installation
11
-
12
- ```sh
13
- npm install --save @raphiniert/ra-data-postgrest
14
- ```
15
-
16
- **NOTE**: When using RA 3.x.x, use the data-provider 1.x.x. For RA >= 4.1.x use the data-provider starting from 1.2.x.
17
-
18
- ## REST Dialect
19
-
20
- This Data Provider fits REST APIs using simple GET parameters for filters and sorting. This is the dialect used for instance in [PostgREST](http://postgrest.org).
21
-
22
- | Method | API calls |
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
- **Note**: The PostgREST data provider expects the API to include a `Content-Range` header in the response to `getList` calls. The value must be the total number of resources in the collection. This allows react-admin to know how many pages of resources there are in total, and build the pagination controls.
35
-
36
- ```
37
- Content-Range: posts 0-24/319
38
- ```
39
-
40
- If your API is on another domain as the JS code, you'll need to whitelist this header with an `Access-Control-Expose-Headers` [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) header.
41
-
42
- ```
43
- Access-Control-Expose-Headers: Content-Range
44
- ```
45
-
46
- ## Usage
47
-
48
- ```jsx
49
- // in src/App.js
50
- import * as React from 'react';
51
- import { Admin, Resource, fetchUtils } from 'react-admin';
52
- import postgrestRestProvider,
53
- { IDataProviderConfig,
54
- defaultPrimaryKeys,
55
- defaultSchema } from '@raphiniert/ra-data-postgrest';
56
-
57
- import { PostList } from './posts';
58
-
59
- const config: IDataProviderConfig = {
60
- apiUrl: 'http://path.to.my.api/',
61
- httpClient: fetchUtils.fetchJson,
62
- defaultListOp: 'eq',
63
- primaryKeys: defaultPrimaryKeys,
64
- schema: defaultSchema
65
- }
66
-
67
- const App = () => (
68
- <Admin dataProvider={postgrestRestProvider(config)}>
69
- <Resource name="posts" list={PostList} />
70
- </Admin>
71
- );
72
-
73
- export default App;
74
- ```
75
-
76
- ### Adding Custom Headers
77
-
78
- The provider function accepts an HTTP client function as second argument. By default, they use react-admin's `fetchUtils.fetchJson()` as HTTP client. It's similar to HTML5 `fetch()`, except it handles JSON decoding and HTTP error codes automatically.
79
-
80
- That means that if you need to add custom headers to your requests, you just need to _wrap_ the `fetchJson()` call inside your own function:
81
-
82
- ```jsx
83
- import { fetchUtils, Admin, Resource } from 'react-admin';
84
- import postgrestRestProvider from '@raphiniert/ra-data-postgrest';
85
-
86
- const httpClient = (url, options = {}) => {
87
- if (!options.headers) {
88
- options.headers = new Headers({ Accept: 'application/json' });
89
- }
90
- // add your own headers here
91
- options.headers.set('X-Custom-Header', 'foobar');
92
- return fetchUtils.fetchJson(url, options);
93
- };
94
-
95
- const config: IDataProviderConfig = {
96
- ...
97
- httpClient: httpClient,
98
- ...
99
- }
100
-
101
- const dataProvider = postgrestRestProvider(config);
102
-
103
- render(
104
- <Admin dataProvider={dataProvider} title="Example Admin">
105
- ...
106
- </Admin>,
107
- document.getElementById('root')
108
- );
109
- ```
110
-
111
- Now all the requests to the REST API will contain the `X-Custom-Header: foobar` header.
112
-
113
- **Tip**: The most common usage of custom headers is for authentication. `fetchJson` has built-on support for the `Authorization` token header:
114
-
115
- ```js
116
- const httpClient = (url, options = {}) => {
117
- options.user = {
118
- authenticated: true,
119
- token: 'SRTRDFVESGNJYTUKTYTHRG',
120
- };
121
- return fetchUtils.fetchJson(url, options);
122
- };
123
- ```
124
-
125
- Now all the requests to the REST API will contain the `Authorization: SRTRDFVESGNJYTUKTYTHRG` header.
126
-
127
- ### Special Filter Feature
128
-
129
- As postgRest allows several comparators, e.g. `ilike`, `like`, `eq`...
130
- The dataProvider is designed to enable you to specify the comparator in your react filter component:
131
-
132
- ```jsx
133
- <Filter {...props}>
134
- <TextInput label="Search" source="post_title@ilike" alwaysOn />
135
- <TextInput label="Search" source="post_author" alwaysOn />
136
- // some more filters
137
- </Filter>
138
- ```
139
-
140
- 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.
141
-
142
- #### RPC Functions
143
-
144
- Given a RPC call as `GET /rpc/add_them?post_author=Herbert HTTP/1.1`, the dataProvider allows you to filter such endpoints. As they are no view, but a SQL procedure, several postgREST features do not apply. I.e. no comparators such as `ilike`, `like`, `eq` are applicable. Only the raw value without comparator needs to be send to the API. In order to realize this behavior, just add an "empty" comparator to the field, i.e. end `source` with an `@` as in the example:
145
-
146
- ```jsx
147
- <Filter {...props}>
148
- <TextInput label="Search" source="post_author@" alwaysOn />
149
- // some more filters
150
- </Filter>
151
- ```
152
-
153
- ### Compound primary keys
154
-
155
- 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:
156
-
157
- ```jsx
158
- const config: IDataProviderConfig = {
159
- ...
160
- primaryKeys: new Map([
161
- ['some_table', ['custom_id']],
162
- ['another_table', ['first_column', 'second_column']],
163
- ]),
164
- ...
165
- }
166
-
167
- const dataProvider = postgrestRestProvider(config);
168
- ```
169
-
170
- ### Custom schema
171
- PostgREST allows to [select and switch the database schema](https://postgrest.org/en/stable/api.html#switching-schemas) by setting a custom header. Thus, one way to use this function would be adding the custom header as a string while using react-admin hooks within `meta.schema` (compare to next section) or to set it up as function of `() => (string)` while using the data provider just component based. The latter can be done as follows and gives the opportunity to use some central storage (e.g. localStorage) which can be changed at multiple points of the application:
172
- ```jsx
173
- const config: IDataProviderConfig = {
174
- ...
175
- schema: localStorage.getItem("schema") || "api",
176
- ...
177
- }
178
-
179
- const dataProvider = postgrestRestProvider(config);
180
- ```
181
-
182
- ### Passing extra headers via meta
183
- Postgrest supports calling functions with a single JSON parameter by sending the header Prefer: params=single-object with your request according to its [docs](https://postgrest.org/en/stable/api.html#calling-functions-with-a-single-json-parameter).
184
-
185
- Within the data provider one can add any kind of header to the request while calling react-admin hooks, e.g.:
186
-
187
- ```jsx
188
- const [create, { isLoading, error }] = useCreate(
189
- 'rpc/my-function',
190
- {
191
- data: { ... },
192
- meta: { headers: { Prefer: 'params=single-object' } },
193
- }
194
- );
195
- ```
196
-
197
- ### Vertical filtering
198
- Postgrest supports a feature of [Vertical Filtering (Columns)](https://postgrest.org/en/stable/api.html#vertical-filtering-columns). Within the react-admin hooks this feature can be used as in the following example:
199
-
200
- ```jsx
201
- const { data, total, isLoading, error } = useGetList(
202
- 'posts',
203
- {
204
- pagination: { page: 1, perPage: 10 },
205
- sort: { field: 'published_at', order: 'DESC' }
206
- meta: { columns: ['id', 'title'] }
207
- }
208
- );
209
- ```
210
-
211
- Further, one should be able to leverage this feature to rename columns:
212
- ```jsx
213
- columns: ['id', 'somealias:title']
214
- ```
215
- , to cast columns:
216
- ```jsx
217
- columns: ['id::text', 'title']
218
- ```
219
- and even get bits from a json or jsonb column"
220
- ```jsx
221
- columns: ['id', 'json_data->>blood_type', 'json_data->phones']
222
- ```
223
-
224
- **Note**: not working for `create` and `updateMany`.
225
-
226
- ## Developers notes
227
-
228
- The current development of this library was done with node v19.10 and npm 8.19.3. In this version the unit tests and the development environment should work.
229
-
230
- ## License
231
-
232
- This data provider is licensed under the MIT License and sponsored by [raphiniert.com](https://raphiniert.com).
1
+ # PostgREST Data Provider For React-Admin
2
+ [![npm](https://img.shields.io/npm/v/@raphiniert/ra-data-postgrest.svg)](https://www.npmjs.com/package/@raphiniert/ra-data-postgrest)
3
+ [![npm downloads](https://img.shields.io/npm/dm/@raphiniert/ra-data-postgrest.svg)](https://www.npmjs.com/package/@raphiniert/ra-data-postgrest)
4
+ [![Coverage Status](https://coveralls.io/repos/github/raphiniert-com/ra-data-postgrest/badge.svg?branch=master)](https://coveralls.io/github/raphiniert-com/ra-data-postgrest?branch=master)
5
+ [![License: MIT](https://img.shields.io/gitlab/license/24181795)](https://github.com/raphiniert-com/ra-data-postgrest/blob/master/LICENSE)
6
+
7
+
8
+ PostgREST Data Provider for [react-admin](https://github.com/marmelab/react-admin), the frontend framework for building admin applications on top of REST/GraphQL services.
9
+
10
+ ## Installation
11
+
12
+ ```sh
13
+ npm install --save @raphiniert/ra-data-postgrest
14
+ ```
15
+
16
+ **NOTE**: When using RA 3.x.x, use the data-provider 1.x.x. For RA >= 4.1.x use the data-provider starting from 1.2.x.
17
+
18
+ ## REST Dialect
19
+
20
+ This Data Provider fits REST APIs using simple GET parameters for filters and sorting. This is the dialect used for instance in [PostgREST](http://postgrest.org).
21
+
22
+ | Method | API calls |
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
+ **Note**: The PostgREST data provider expects the API to include a `Content-Range` header in the response to `getList` calls. The value must be the total number of resources in the collection. This allows react-admin to know how many pages of resources there are in total, and build the pagination controls.
35
+
36
+ ```
37
+ Content-Range: posts 0-24/319
38
+ ```
39
+
40
+ If your API is on another domain as the JS code, you'll need to whitelist this header with an `Access-Control-Expose-Headers` [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) header.
41
+
42
+ ```
43
+ Access-Control-Expose-Headers: Content-Range
44
+ ```
45
+
46
+ ## Usage
47
+
48
+ ```jsx
49
+ // in src/App.js
50
+ import * as React from 'react';
51
+ import { Admin, Resource, fetchUtils } from 'react-admin';
52
+ import postgrestRestProvider,
53
+ { IDataProviderConfig,
54
+ defaultPrimaryKeys,
55
+ defaultSchema } from '@raphiniert/ra-data-postgrest';
56
+
57
+ import { PostList } from './posts';
58
+
59
+ const config: IDataProviderConfig = {
60
+ apiUrl: 'http://path.to.my.api/',
61
+ httpClient: fetchUtils.fetchJson,
62
+ defaultListOp: 'eq',
63
+ primaryKeys: defaultPrimaryKeys,
64
+ schema: defaultSchema
65
+ }
66
+
67
+ const App = () => (
68
+ <Admin dataProvider={postgrestRestProvider(config)}>
69
+ <Resource name="posts" list={PostList} />
70
+ </Admin>
71
+ );
72
+
73
+ export default App;
74
+ ```
75
+
76
+ ### Adding Custom Headers
77
+
78
+ The provider function accepts an HTTP client function as second argument. By default, they use react-admin's `fetchUtils.fetchJson()` as HTTP client. It's similar to HTML5 `fetch()`, except it handles JSON decoding and HTTP error codes automatically.
79
+
80
+ That means that if you need to add custom headers to your requests, you just need to _wrap_ the `fetchJson()` call inside your own function:
81
+
82
+ ```jsx
83
+ import { fetchUtils, Admin, Resource } from 'react-admin';
84
+ import postgrestRestProvider from '@raphiniert/ra-data-postgrest';
85
+
86
+ const httpClient = (url, options = {}) => {
87
+ if (!options.headers) {
88
+ options.headers = new Headers({ Accept: 'application/json' });
89
+ }
90
+ // add your own headers here
91
+ options.headers.set('X-Custom-Header', 'foobar');
92
+ return fetchUtils.fetchJson(url, options);
93
+ };
94
+
95
+ const config: IDataProviderConfig = {
96
+ ...
97
+ httpClient: httpClient,
98
+ ...
99
+ }
100
+
101
+ const dataProvider = postgrestRestProvider(config);
102
+
103
+ render(
104
+ <Admin dataProvider={dataProvider} title="Example Admin">
105
+ ...
106
+ </Admin>,
107
+ document.getElementById('root')
108
+ );
109
+ ```
110
+
111
+ Now all the requests to the REST API will contain the `X-Custom-Header: foobar` header.
112
+
113
+ **Tip**: The most common usage of custom headers is for authentication. `fetchJson` has built-on support for the `Authorization` token header:
114
+
115
+ ```js
116
+ const httpClient = (url, options = {}) => {
117
+ options.user = {
118
+ authenticated: true,
119
+ token: 'SRTRDFVESGNJYTUKTYTHRG',
120
+ };
121
+ return fetchUtils.fetchJson(url, options);
122
+ };
123
+ ```
124
+
125
+ Now all the requests to the REST API will contain the `Authorization: SRTRDFVESGNJYTUKTYTHRG` header.
126
+
127
+ ### Special Filter Feature
128
+
129
+ As postgRest allows several comparators, e.g. `ilike`, `like`, `eq`...
130
+ The dataProvider is designed to enable you to specify the comparator in your react filter component:
131
+
132
+ ```jsx
133
+ <Filter {...props}>
134
+ <TextInput label="Search" source="post_title@ilike" alwaysOn />
135
+ <TextInput label="Search" source="post_author" alwaysOn />
136
+ // some more filters
137
+ </Filter>
138
+ ```
139
+
140
+ 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.
141
+
142
+ #### RPC Functions
143
+
144
+ Given a RPC call as `GET /rpc/add_them?post_author=Herbert HTTP/1.1`, the dataProvider allows you to filter such endpoints. As they are no view, but a SQL procedure, several postgREST features do not apply. I.e. no comparators such as `ilike`, `like`, `eq` are applicable. Only the raw value without comparator needs to be send to the API. In order to realize this behavior, just add an "empty" comparator to the field, i.e. end `source` with an `@` as in the example:
145
+
146
+ ```jsx
147
+ <Filter {...props}>
148
+ <TextInput label="Search" source="post_author@" alwaysOn />
149
+ // some more filters
150
+ </Filter>
151
+ ```
152
+
153
+ ### Compound primary keys
154
+
155
+ 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:
156
+
157
+ ```jsx
158
+ const config: IDataProviderConfig = {
159
+ ...
160
+ primaryKeys: new Map([
161
+ ['some_table', ['custom_id']],
162
+ ['another_table', ['first_column', 'second_column']],
163
+ ]),
164
+ ...
165
+ }
166
+
167
+ const dataProvider = postgrestRestProvider(config);
168
+ ```
169
+
170
+ ### Custom schema
171
+ PostgREST allows to [select and switch the database schema](https://postgrest.org/en/stable/api.html#switching-schemas) by setting a custom header. Thus, one way to use this function would be adding the custom header as a string while using react-admin hooks within `meta.schema` (compare to next section) or to set it up as function of `() => (string)` while using the data provider just component based. The latter can be done as follows and gives the opportunity to use some central storage (e.g. localStorage) which can be changed at multiple points of the application:
172
+ ```jsx
173
+ const config: IDataProviderConfig = {
174
+ ...
175
+ schema: () => localStorage.getItem("schema") || "api",
176
+ ...
177
+ }
178
+
179
+ const dataProvider = postgrestRestProvider(config);
180
+ ```
181
+
182
+ ### Passing extra headers via meta
183
+ Postgrest supports calling functions with a single JSON parameter by sending the header Prefer: params=single-object with your request according to its [docs](https://postgrest.org/en/stable/api.html#calling-functions-with-a-single-json-parameter).
184
+
185
+ Within the data provider one can add any kind of header to the request while calling react-admin hooks, e.g.:
186
+
187
+ ```jsx
188
+ const [create, { isLoading, error }] = useCreate(
189
+ 'rpc/my-function',
190
+ {
191
+ data: { ... },
192
+ meta: { headers: { Prefer: 'params=single-object' } },
193
+ }
194
+ );
195
+ ```
196
+
197
+ ### Null sort order
198
+ Postgrest supports specifying the position of nulls in [sort ordering](https://postgrest.org/en/v12/references/api/tables_views.html#ordering). This can be configured via an optional data provider parameter:
199
+
200
+ ```jsx
201
+ const config: IDataProviderConfig = {
202
+ ...
203
+ sortOrder: PostgRestSortOrder.AscendingNullsLastDescendingNullsLast
204
+ ...
205
+ }
206
+
207
+ const dataProvider = postgrestRestProvider(config);
208
+ ```
209
+
210
+ It is important to note that null positioning in sort will impact index utilization so in some cases you'll want to add corresponding index on the database side.
211
+
212
+ ### Vertical filtering
213
+ Postgrest supports a feature of [Vertical Filtering (Columns)](https://postgrest.org/en/stable/api.html#vertical-filtering-columns). Within the react-admin hooks this feature can be used as in the following example:
214
+
215
+ ```jsx
216
+ const { data, total, isLoading, error } = useGetList(
217
+ 'posts',
218
+ {
219
+ pagination: { page: 1, perPage: 10 },
220
+ sort: { field: 'published_at', order: 'DESC' }
221
+ meta: { columns: ['id', 'title'] }
222
+ }
223
+ );
224
+ ```
225
+
226
+ Further, one should be able to leverage this feature to rename columns:
227
+ ```jsx
228
+ columns: ['id', 'somealias:title']
229
+ ```
230
+ , to cast columns:
231
+ ```jsx
232
+ columns: ['id::text', 'title']
233
+ ```
234
+ and even get bits from a json or jsonb column"
235
+ ```jsx
236
+ columns: ['id', 'json_data->>blood_type', 'json_data->phones']
237
+ ```
238
+
239
+ **Note**: not working for `create` and `updateMany`.
240
+
241
+ ## Developers notes
242
+
243
+ The current development of this library was done with node v19.10 and npm 8.19.3. In this version the unit tests and the development environment should work.
244
+
245
+ ## License
246
+
247
+ This data provider is licensed under the MIT License and sponsored by [raphiniert.com](https://raphiniert.com).
package/esm/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DataProvider } from 'ra-core';
2
- import { PrimaryKey, PostgRestOperator } from './urlBuilder';
2
+ import { PrimaryKey, PostgRestOperator, PostgRestSortOrder } from './urlBuilder';
3
3
  /**
4
4
  * Maps react-admin queries to a postgrest REST API
5
5
  *
@@ -53,6 +53,7 @@ export interface IDataProviderConfig {
53
53
  apiUrl: string;
54
54
  httpClient: (string: any, Options: any) => Promise<any>;
55
55
  defaultListOp: PostgRestOperator;
56
+ sortOrder?: PostgRestSortOrder;
56
57
  primaryKeys: Map<string, PrimaryKey>;
57
58
  schema: () => string;
58
59
  }
package/esm/index.js CHANGED
@@ -11,6 +11,7 @@ var __assign = (this && this.__assign) || function () {
11
11
  };
12
12
  import { getPrimaryKey, parseFilters, getOrderBy, dataWithVirtualId, dataWithoutVirtualId, removePrimaryKey, getQuery, encodeId, } from './urlBuilder';
13
13
  import qs from 'qs';
14
+ import isEqual from 'lodash/isEqual';
14
15
  export var defaultPrimaryKeys = new Map();
15
16
  export var defaultSchema = function () { return ''; };
16
17
  var useCustomSchema = function (schema, metaSchema, method) {
@@ -58,7 +59,7 @@ export default (function (config) { return ({
58
59
  return config.httpClient(url, options).then(function (_a) {
59
60
  var headers = _a.headers, json = _a.json;
60
61
  if (!headers.has('content-range')) {
61
- 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?");
62
+ 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?");
62
63
  }
63
64
  return {
64
65
  data: json.map(function (obj) { return dataWithVirtualId(obj, primaryKey); }),
@@ -114,7 +115,7 @@ export default (function (config) { return ({
114
115
  var primaryKey = getPrimaryKey(resource, config.primaryKeys);
115
116
  var metaSchema = (_b = params.meta) === null || _b === void 0 ? void 0 : _b.schema;
116
117
  var query = params.target
117
- ? __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);
118
+ ? __assign((_a = {}, _a[params.target] = "eq.".concat(params.id), _a.order = getOrderBy(field, order, primaryKey, config.sortOrder), _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);
118
119
  if (select) {
119
120
  query.select = select;
120
121
  }
@@ -126,7 +127,7 @@ export default (function (config) { return ({
126
127
  return config.httpClient(url, options).then(function (_a) {
127
128
  var headers = _a.headers, json = _a.json;
128
129
  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
+ 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
  }
131
132
  return {
132
133
  data: json.map(function (data) { return dataWithVirtualId(data, primaryKey); }),
@@ -137,12 +138,13 @@ export default (function (config) { return ({
137
138
  update: function (resource, params) {
138
139
  var _a, _b;
139
140
  if (params === void 0) { params = {}; }
140
- var id = params.id, data = params.data, meta = params.meta;
141
+ var id = params.id, data = params.data, meta = params.meta, previousData = params.previousData;
141
142
  var primaryKey = getPrimaryKey(resource, config.primaryKeys);
142
143
  var query = getQuery(primaryKey, id, resource, meta);
143
144
  var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs.stringify(query));
145
+ var changedData = getChanges(data, previousData);
144
146
  var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
145
- var body = JSON.stringify(__assign({}, dataWithoutVirtualId(removePrimaryKey(data, primaryKey), primaryKey)));
147
+ var body = JSON.stringify(__assign({}, dataWithoutVirtualId(removePrimaryKey(changedData, primaryKey), primaryKey)));
146
148
  return config
147
149
  .httpClient(url, {
148
150
  method: 'PATCH',
@@ -241,3 +243,12 @@ export default (function (config) { return ({
241
243
  });
242
244
  },
243
245
  }); });
246
+ var getChanges = function (data, previousData) {
247
+ var changes = Object.keys(data).reduce(function (changes, key) {
248
+ if (!isEqual(data[key], previousData[key])) {
249
+ changes[key] = data[key];
250
+ }
251
+ return changes;
252
+ }, {});
253
+ return changes;
254
+ };
@@ -18,5 +18,11 @@ export declare const removePrimaryKey: (data: any, primaryKey: PrimaryKey) => an
18
18
  export declare const dataWithVirtualId: (data: any, primaryKey: PrimaryKey) => any;
19
19
  export declare const dataWithoutVirtualId: (data: any, primaryKey: PrimaryKey) => any;
20
20
  export declare const getQuery: (primaryKey: PrimaryKey, ids: Identifier | Array<Identifier> | undefined, resource: string, meta?: any) => any;
21
- export declare const getOrderBy: (field: string, order: string, primaryKey: PrimaryKey) => string;
21
+ export declare enum PostgRestSortOrder {
22
+ AscendingNullsLastDescendingNullsFirst = "asc,desc",
23
+ AscendingNullsLastDescendingNullsLast = "asc,desc.nullslast",
24
+ AscendingNullsFirstDescendingNullsFirst = "asc.nullsfirst,desc",
25
+ AscendingNullsFirstDescendingNullsLast = "asc.nullsfirst,desc.nullslast"
26
+ }
27
+ export declare const getOrderBy: (field: string, order: string, primaryKey: PrimaryKey, sortOrder?: PostgRestSortOrder) => string;
22
28
  export {};
package/esm/urlBuilder.js CHANGED
@@ -258,11 +258,20 @@ export var getQuery = function (primaryKey, ids, resource, meta) {
258
258
  }
259
259
  return result;
260
260
  };
261
- export var getOrderBy = function (field, order, primaryKey) {
261
+ export var PostgRestSortOrder;
262
+ (function (PostgRestSortOrder) {
263
+ PostgRestSortOrder["AscendingNullsLastDescendingNullsFirst"] = "asc,desc";
264
+ PostgRestSortOrder["AscendingNullsLastDescendingNullsLast"] = "asc,desc.nullslast";
265
+ PostgRestSortOrder["AscendingNullsFirstDescendingNullsFirst"] = "asc.nullsfirst,desc";
266
+ PostgRestSortOrder["AscendingNullsFirstDescendingNullsLast"] = "asc.nullsfirst,desc.nullslast";
267
+ })(PostgRestSortOrder || (PostgRestSortOrder = {}));
268
+ export var getOrderBy = function (field, order, primaryKey, sortOrder) {
269
+ if (sortOrder === void 0) { sortOrder = PostgRestSortOrder.AscendingNullsLastDescendingNullsFirst; }
270
+ var postgRestOrder = sortOrder.split(',')[order === 'ASC' ? 0 : 1];
262
271
  if (field == 'id') {
263
- return primaryKey.map(function (key) { return "".concat(key, ".").concat(order.toLowerCase()); }).join(',');
272
+ return primaryKey.map(function (key) { return "".concat(key, ".").concat(postgRestOrder); }).join(',');
264
273
  }
265
274
  else {
266
- return "".concat(field, ".").concat(order.toLowerCase());
275
+ return "".concat(field, ".").concat(postgRestOrder);
267
276
  }
268
277
  };
package/lib/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { DataProvider } from 'ra-core';
2
- import { PrimaryKey, PostgRestOperator } from './urlBuilder';
2
+ import { PrimaryKey, PostgRestOperator, PostgRestSortOrder } from './urlBuilder';
3
3
  /**
4
4
  * Maps react-admin queries to a postgrest REST API
5
5
  *
@@ -53,6 +53,7 @@ export interface IDataProviderConfig {
53
53
  apiUrl: string;
54
54
  httpClient: (string: any, Options: any) => Promise<any>;
55
55
  defaultListOp: PostgRestOperator;
56
+ sortOrder?: PostgRestSortOrder;
56
57
  primaryKeys: Map<string, PrimaryKey>;
57
58
  schema: () => string;
58
59
  }