{"id":13479151,"url":"https://github.com/raphiniert-com/ra-data-postgrest","last_synced_at":"2025-05-16T02:08:56.983Z","repository":{"id":40995310,"uuid":"234365451","full_name":"raphiniert-com/ra-data-postgrest","owner":"raphiniert-com","description":"react admin client for postgREST","archived":false,"fork":false,"pushed_at":"2025-04-29T11:30:26.000Z","size":542,"stargazers_count":120,"open_issues_count":3,"forks_count":35,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-04-29T11:38:52.476Z","etag":null,"topics":["api","postgresql","postgrest","react","react-admin","rest"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/raphiniert-com.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-01-16T16:44:06.000Z","updated_at":"2025-04-29T11:27:28.000Z","dependencies_parsed_at":"2023-02-16T18:32:04.232Z","dependency_job_id":"bcdfb579-82b0-4f64-899b-9f6674572642","html_url":"https://github.com/raphiniert-com/ra-data-postgrest","commit_stats":{"total_commits":175,"total_committers":16,"mean_commits":10.9375,"dds":0.7428571428571429,"last_synced_commit":"ff935baf0b2dc9c126b5e47a621cfe270779061e"},"previous_names":[],"tags_count":27,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/raphiniert-com%2Fra-data-postgrest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/raphiniert-com%2Fra-data-postgrest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/raphiniert-com%2Fra-data-postgrest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/raphiniert-com%2Fra-data-postgrest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/raphiniert-com","download_url":"https://codeload.github.com/raphiniert-com/ra-data-postgrest/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254453655,"owners_count":22073617,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","postgresql","postgrest","react","react-admin","rest"],"created_at":"2024-07-31T16:02:10.437Z","updated_at":"2025-05-16T02:08:56.970Z","avatar_url":"https://github.com/raphiniert-com.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# PostgREST Data Provider For React-Admin\n[![npm](https://img.shields.io/npm/v/@raphiniert/ra-data-postgrest.svg)](https://www.npmjs.com/package/@raphiniert/ra-data-postgrest)\n[![npm downloads](https://img.shields.io/npm/dm/@raphiniert/ra-data-postgrest.svg)](https://www.npmjs.com/package/@raphiniert/ra-data-postgrest)\n[![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)\n[![License: MIT](https://img.shields.io/gitlab/license/24181795)](https://github.com/raphiniert-com/ra-data-postgrest/blob/master/LICENSE)\n\n\nPostgREST Data Provider for [react-admin](https://github.com/marmelab/react-admin), the frontend framework for building admin applications on top of REST/GraphQL services.\n\n## Installation\n\n```sh\nnpm install --save @raphiniert/ra-data-postgrest\n```\n\n## Citation\nIf you use the PostgREST Data Provider in your research or project, please consider citing the corresponding [paper](https://www.sciencedirect.com/science/article/pii/S2665963824000873). Feel free to include the following BibTeX entry in your publications:\n\n```bibtex\n@article{SCHEIBLE2024100699,\n    title = {PostgREST Data Provider for React-Admin: Bootstrap the creation of user interfaces on top of PostgreSQL databases},\n    journal = {Software Impacts},\n    volume = {21},\n    pages = {100699},\n    year = {2024},\n    issn = {2665-9638},\n    doi = {https://doi.org/10.1016/j.simpa.2024.100699},\n    author = {Raphael Scheible}\n}\n```\n\n\n## REST Dialect\n\nThis 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).\n\n| Method             | API calls                                                                            |\n| ------------------ | ------------------------------------------------------------------------------------ |\n| `getList`          | `GET http://my.api.url/posts?order=title.asc\u0026offset=0\u0026limit=24\u0026filterField=eq.value` |\n| `getOne`           | `GET http://my.api.url/posts?id=eq.123`                                              |\n| `getMany`          | `GET http://my.api.url/posts?id=in.(123,456,789)`                                    |\n| `getManyReference` | `GET http://my.api.url/posts?author_id=eq.345`                                       |\n| `create`           | `POST http://my.api.url/posts`                                                       |\n| `update`           | `PATCH http://my.api.url/posts?id=eq.123`                                            |\n| `updateMany`       | `PATCH http://my.api.url/posts?id=in.(123,456,789)`                                  |\n| `delete`           | `DELETE http://my.api.url/posts?id=eq.123`                                           |\n| `deleteMany`       | `DELETE http://my.api.url/posts?id=in.(123,456,789)`                                 |\n\n**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.\n\n```\nContent-Range: posts 0-24/319\n```\n\nIf 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.\n\n```\nAccess-Control-Expose-Headers: Content-Range\n```\n\n## Usage\n\n```jsx\n// in src/App.js\nimport * as React from 'react';\nimport { Admin, Resource, fetchUtils } from 'react-admin';\nimport postgrestRestProvider,\n     { IDataProviderConfig,\n       defaultPrimaryKeys,\n       defaultSchema } from '@raphiniert/ra-data-postgrest';\n\nimport { PostList } from './posts';\n\nconst config: IDataProviderConfig = {\n    apiUrl: 'http://path.to.my.api/',\n    httpClient: fetchUtils.fetchJson,\n    defaultListOp: 'eq',\n    primaryKeys: defaultPrimaryKeys,\n    schema: defaultSchema\n}\n\nconst App = () =\u003e (\n    \u003cAdmin dataProvider={postgrestRestProvider(config)}\u003e\n        \u003cResource name=\"posts\" list={PostList} /\u003e\n    \u003c/Admin\u003e\n);\n\nexport default App;\n```\n\n### Adding Custom Headers\n\nThe 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.\n\nThat means that if you need to add custom headers to your requests, you just need to _wrap_ the `fetchJson()` call inside your own function:\n\n```jsx\nimport { fetchUtils, Admin, Resource } from 'react-admin';\nimport postgrestRestProvider from '@raphiniert/ra-data-postgrest';\n\nconst httpClient = (url, options = {}) =\u003e {\n    if (!options.headers) {\n        options.headers = new Headers({ Accept: 'application/json' });\n    }\n    // add your own headers here\n    options.headers.set('X-Custom-Header', 'foobar');\n    return fetchUtils.fetchJson(url, options);\n};\n\nconst config: IDataProviderConfig = {\n    ...\n    httpClient: httpClient,\n    ...\n}\n\nconst dataProvider = postgrestRestProvider(config);\n\nrender(\n    \u003cAdmin dataProvider={dataProvider} title=\"Example Admin\"\u003e\n        ...\n    \u003c/Admin\u003e,\n    document.getElementById('root')\n);\n```\n\nNow all the requests to the REST API will contain the `X-Custom-Header: foobar` header.\n\n**Tip**: The most common usage of custom headers is for authentication. `fetchJson` has built-on support for the `Authorization` token header:\n\n```js\nconst httpClient = (url, options = {}) =\u003e {\n    options.user = {\n        authenticated: true,\n        token: 'SRTRDFVESGNJYTUKTYTHRG',\n    };\n    return fetchUtils.fetchJson(url, options);\n};\n```\n\nNow all the requests to the REST API will contain the `Authorization: SRTRDFVESGNJYTUKTYTHRG` header.\n\n### Special Filter Feature\n\nAs postgRest allows several comparators, e.g. `ilike`, `like`, `eq`...\nThe dataProvider is designed to enable you to specify the comparator in your react filter component:\n\n```jsx\n\u003cFilter {...props}\u003e\n    \u003cTextInput label=\"Search\" source=\"post_title@ilike\" alwaysOn /\u003e\n    \u003cTextInput label=\"Search\" source=\"post_author\" alwaysOn /\u003e\n    // some more filters\n\u003c/Filter\u003e\n```\n\nOne 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.\n\n#### RPC Functions\n\nGiven 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:\n\n```jsx\n\u003cFilter {...props}\u003e\n    \u003cTextInput label=\"Search\" source=\"post_author@\" alwaysOn /\u003e\n    // some more filters\n\u003c/Filter\u003e\n```\n\n### Compound primary keys\n\nIf 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:\n\n```jsx\nconst config: IDataProviderConfig = {\n    ...\n    primaryKeys: new Map([\n        ['some_table', ['custom_id']],\n        ['another_table', ['first_column', 'second_column']],\n    ]),\n    ...\n}\n\nconst dataProvider = postgrestRestProvider(config);\n```\n\n### Custom schema\nPostgREST 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 `() =\u003e (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:\n```jsx\nconst config: IDataProviderConfig = {\n    ...\n    schema: () =\u003e localStorage.getItem(\"schema\") || \"api\",\n    ...\n}\n\nconst dataProvider = postgrestRestProvider(config);\n```\n\n### Passing extra headers via meta\nPostgrest 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).\n\nWithin the data provider one can add any kind of header to the request while calling react-admin hooks, e.g.:\n\n```jsx\nconst [create, { isLoading, error }] = useCreate(\n    'rpc/my-function',\n    {\n        data: { ... },\n        meta: { headers: { Prefer: 'params=single-object' } },\n    }\n);\n```\n\n### Null sort order\n\nPostgrest 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:\n\n```jsx\nimport { PostgRestSortOrder, IDataProviderConfig } from '@raphiniert/ra-data-postgrest';\n\nconst config: IDataProviderConfig = {\n    ...\n    sortOrder: PostgRestSortOrder.AscendingNullsLastDescendingNullsLast\n    ...\n}\n\nconst dataProvider = postgrestRestProvider(config);\n```\n\nThis parameter impacts the `getList` and `getManyReference` calls.\n\nIt 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.\n\nYou can also override this parameter on a per-query basis by passing `nullsfirst: true` or `nullslast: true` in the `meta` object of the query:\n\n```jsx\nconst { data, total, isLoading, error } = useGetList(\n    'posts',\n    {\n        pagination: { page: 1, perPage: 10 },\n        sort: { field: 'published_at', order: 'DESC' },\n        meta: { nullslast: true }\n    }\n);\n```\n\n### Vertical filtering\nPostgrest 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:\n\n```jsx\nconst { data, total, isLoading, error } = useGetList(\n    'posts',\n    {\n        pagination: { page: 1, perPage: 10 },\n        sort: { field: 'published_at', order: 'DESC' }\n        meta: { columns: ['id', 'title'] }\n    }\n);\n```\n\nFurther, one should be able to leverage this feature to rename columns:\n```jsx\ncolumns: ['id', 'somealias:title']\n```\n, to cast columns:\n```jsx\ncolumns: ['id::text', 'title']\n```\nand even get bits from a json or jsonb column\"\n```jsx\ncolumns: ['id', 'json_data-\u003e\u003eblood_type', 'json_data-\u003ephones']\n```\n\n**Note**: not working for `create` and `updateMany`.\n\n### Embeds and prefetch\n\n`ra-data-postgrest` supports React Admin [embed](https://marmelab.com/react-admin/DataProviders.html#embedding-relationships) and [prefetch](https://marmelab.com/react-admin/DataProviders.html#prefetching-relationships) features.\n\nFor instance, here's how to prefetch posts authors (many-to-one relationship):\n\n```jsx\nimport { Datagrid, List, ReferenceField, TextField } from 'react-admin';\n\nconst PostList = () =\u003e (\n    \u003cList queryOptions={{ meta: { prefetch: ['authors'] } }}\u003e\n        \u003cDatagrid\u003e\n            \u003cTextField source=\"title\" /\u003e\n            \u003cReferenceField source=\"author_id\" reference=\"authors\" /\u003e\n        \u003c/Datagrid\u003e\n    \u003c/List\u003e\n)\n```\n\nHere's how to embed posts authors instead:\n\n```jsx\nimport { Datagrid, List, ReferenceField, TextField } from 'react-admin';\n\nconst PostList = () =\u003e (\n    \u003cList queryOptions={{ meta: { embed: ['authors'] } }}\u003e\n        \u003cDatagrid\u003e\n            \u003cTextField source=\"title\" /\u003e\n            \u003cTextField source=\"authors.name\" /\u003e\n        \u003c/Datagrid\u003e\n    \u003c/List\u003e\n)\n```\n\nThis will result in a single query to the database and populate React Admin cache for the `authors` resource.\n\nThis works for one-to-many relationships too. For instance, here's how to prefetch all books from an author:\n\n```jsx\nimport { Show, SimpleShowLayout, ReferenceManyField, Datagrid, TextField, DateField } from 'react-admin';\n\nconst AuthorShow = () =\u003e (\n    \u003cShow queryOptions={{ meta: { prefetch: ['books'] } }}\u003e\n        \u003cSimpleShowLayout\u003e\n            \u003cTextField source=\"first_name\" /\u003e\n            \u003cTextField source=\"last_name\" /\u003e\n            \u003cReferenceManyField reference=\"books\" target=\"author_id\" label=\"Books\"\u003e\n              \u003cDatagrid\u003e\n                \u003cTextField source=\"title\" /\u003e\n                \u003cDateField source=\"published_at\" /\u003e\n              \u003c/Datagrid\u003e\n            \u003c/ReferenceManyField\u003e\n        \u003c/SimpleShowLayout\u003e\n    \u003c/Show\u003e\n);\n```\n\nHere's how to embed the books instead:\n\n```jsx\nimport { Show, SimpleShowLayout, ArrayField, Datagrid, TextField, DateField } from 'react-admin';\n\nconst AuthorShow = () =\u003e (\n    \u003cShow queryOptions={{ meta: { prefetch: ['books'] } }}\u003e\n        \u003cSimpleShowLayout\u003e\n            \u003cTextField source=\"first_name\" /\u003e\n            \u003cTextField source=\"last_name\" /\u003e\n            \u003cArrayField source=\"books\"\u003e\n              \u003cDatagrid\u003e\n                \u003cTextField source=\"title\" /\u003e\n                \u003cDateField source=\"published_at\" /\u003e\n              \u003c/Datagrid\u003e\n            \u003c/ArrayField\u003e\n        \u003c/SimpleShowLayout\u003e\n    \u003c/Show\u003e\n);\n```\n\nThis will result in a single query to the database and populate React Admin cache for the `books` resource.\n\n## Developers notes\n\nThe current development of this library was done with node v20.18.0 (npm v10.8.2). In this version the unit tests and the development environment should work.\n\n## License\n\nThis data provider is licensed under the MIT License and sponsored by [raphiniert.com](https://raphiniert.com).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fraphiniert-com%2Fra-data-postgrest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fraphiniert-com%2Fra-data-postgrest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fraphiniert-com%2Fra-data-postgrest/lists"}