@raphiniert/ra-data-postgrest 2.1.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/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  Find all notable changes of this project in this file.
4
4
 
5
+ ## v2.2.0 - 2024-06-28
6
+ ### Improvements
7
+ - [#123](https://github.com/raphiniert-com/ra-data-postgrest/pull/125) Adding global sort order options @[kav](https://github.com/kav)
8
+
5
9
  ## v2.1.0 - 2024-02-27
6
10
  ### Improvements
7
11
  - updated dependencies
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
@@ -115,7 +115,7 @@ export default (function (config) { return ({
115
115
  var primaryKey = getPrimaryKey(resource, config.primaryKeys);
116
116
  var metaSchema = (_b = params.meta) === null || _b === void 0 ? void 0 : _b.schema;
117
117
  var query = params.target
118
- ? __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);
119
119
  if (select) {
120
120
  query.select = select;
121
121
  }
@@ -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
  }
package/lib/index.js CHANGED
@@ -122,7 +122,7 @@ exports.default = (function (config) { return ({
122
122
  var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
123
123
  var metaSchema = (_b = params.meta) === null || _b === void 0 ? void 0 : _b.schema;
124
124
  var query = params.target
125
- ? __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), filter) : __assign({ order: (0, urlBuilder_1.getOrderBy)(field, order, primaryKey), offset: String((page - 1) * perPage), limit: String(perPage) }, filter);
125
+ ? __assign((_a = {}, _a[params.target] = "eq.".concat(params.id), _a.order = (0, urlBuilder_1.getOrderBy)(field, order, primaryKey, config.sortOrder), _a.offset = String((page - 1) * perPage), _a.limit = String(perPage), _a), filter) : __assign({ order: (0, urlBuilder_1.getOrderBy)(field, order, primaryKey), offset: String((page - 1) * perPage), limit: String(perPage) }, filter);
126
126
  if (select) {
127
127
  query.select = select;
128
128
  }
@@ -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/lib/urlBuilder.js CHANGED
@@ -22,7 +22,7 @@ var __rest = (this && this.__rest) || function (s, e) {
22
22
  return t;
23
23
  };
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.getOrderBy = exports.getQuery = exports.dataWithoutVirtualId = exports.dataWithVirtualId = exports.removePrimaryKey = exports.encodeId = exports.decodeId = exports.getPrimaryKey = exports.parseFilters = void 0;
25
+ exports.getOrderBy = exports.PostgRestSortOrder = exports.getQuery = exports.dataWithoutVirtualId = exports.dataWithVirtualId = exports.removePrimaryKey = exports.encodeId = exports.decodeId = exports.getPrimaryKey = exports.parseFilters = void 0;
26
26
  /**
27
27
  * List of all possible operators in PostgRest
28
28
  * (https://postgrest.org/en/stable/api.html#operators)
@@ -269,12 +269,21 @@ var getQuery = function (primaryKey, ids, resource, meta) {
269
269
  return result;
270
270
  };
271
271
  exports.getQuery = getQuery;
272
- var getOrderBy = function (field, order, primaryKey) {
272
+ var PostgRestSortOrder;
273
+ (function (PostgRestSortOrder) {
274
+ PostgRestSortOrder["AscendingNullsLastDescendingNullsFirst"] = "asc,desc";
275
+ PostgRestSortOrder["AscendingNullsLastDescendingNullsLast"] = "asc,desc.nullslast";
276
+ PostgRestSortOrder["AscendingNullsFirstDescendingNullsFirst"] = "asc.nullsfirst,desc";
277
+ PostgRestSortOrder["AscendingNullsFirstDescendingNullsLast"] = "asc.nullsfirst,desc.nullslast";
278
+ })(PostgRestSortOrder || (exports.PostgRestSortOrder = PostgRestSortOrder = {}));
279
+ var getOrderBy = function (field, order, primaryKey, sortOrder) {
280
+ if (sortOrder === void 0) { sortOrder = PostgRestSortOrder.AscendingNullsLastDescendingNullsFirst; }
281
+ var postgRestOrder = sortOrder.split(',')[order === 'ASC' ? 0 : 1];
273
282
  if (field == 'id') {
274
- return primaryKey.map(function (key) { return "".concat(key, ".").concat(order.toLowerCase()); }).join(',');
283
+ return primaryKey.map(function (key) { return "".concat(key, ".").concat(postgRestOrder); }).join(',');
275
284
  }
276
285
  else {
277
- return "".concat(field, ".").concat(order.toLowerCase());
286
+ return "".concat(field, ".").concat(postgRestOrder);
278
287
  }
279
288
  };
280
289
  exports.getOrderBy = getOrderBy;