diff --git a/esm/index.d.ts b/esm/index.d.ts
deleted file mode 100644
index 68d0360..0000000
--- a/esm/index.d.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { DataProvider } from 'ra-core';
-import { PrimaryKey, PostgRestOperator } from './urlBuilder';
-/**
- * Maps react-admin queries to a postgrest REST API
- *
- * This REST dialect uses postgrest syntax
- *
- * @see https://postgrest.org/en/stable/api.html#embedded-filters
- *
- * @example
- *
- * getList => GET http://my.api.url/posts?order=title.asc&offset=0&limit=24&filterField=eq.value
- * getOne => GET http://my.api.url/posts?id=eq.123
- * getMany => GET http://my.api.url/posts?id=in.(123,456,789)
- * getManyReference => GET http://my.api.url/posts?author_id=eq.345
- * create => POST http://my.api.url/posts
- * update => PATCH http://my.api.url/posts?id=eq.123
- * updateMany => PATCH http://my.api.url/posts?id=in.(123,456,789)
- * delete => DELETE http://my.api.url/posts?id=eq.123
- * deleteMany => DELETE http://my.api.url/posts?id=in.(123,456,789)
- *
- * @example
- *
- * import * as React from 'react';
- * import { Admin, Resource, fetchUtils } from 'react-admin';
- * import postgrestRestProvider,
- * { IDataProviderConfig,
- * defaultPrimaryKeys,
- * defaultSchema } from '@raphiniert/ra-data-postgrest';
- *
- * import { PostList } from './posts';
- *
- * const config: IDataProviderConfig = {
- * apiUrl: 'http://path.to.my.api/',
- * httpClient: fetchUtils.fetchJson,
- * defaultListOp: 'eq',
- * primaryKeys: defaultPrimaryKeys,
- * schema: defaultSchema
- * }
- *
- * const App = () => (
- *
- *
- *
- * );
- *
- * export default App;
- */
-export type MetaOption = string | undefined;
-export declare const defaultPrimaryKeys: Map;
-export declare const defaultSchema: () => string;
-export interface IDataProviderConfig {
- apiUrl: string;
- httpClient: (string: any, Options: any) => Promise;
- defaultListOp: PostgRestOperator;
- primaryKeys: Map;
- schema: () => string;
-}
-declare const _default: (config: IDataProviderConfig) => DataProvider;
-export default _default;
diff --git a/esm/index.js b/esm/index.js
deleted file mode 100644
index 983390f..0000000
--- a/esm/index.js
+++ /dev/null
@@ -1,239 +0,0 @@
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-import { getPrimaryKey, parseFilters, getOrderBy, dataWithVirtualId, dataWithoutVirtualId, removePrimaryKey, getQuery, encodeId, } from './urlBuilder';
-import qs from 'qs';
-export var defaultPrimaryKeys = new Map();
-export var defaultSchema = function () { return ''; };
-var useCustomSchema = function (schema, metaSchema, method) {
- var _a;
- var funcHeaderSchema = schema;
- if (metaSchema !== undefined) {
- funcHeaderSchema = function () { return metaSchema; };
- }
- if (funcHeaderSchema().length > 0) {
- var schemaHeader = '';
- if (['GET', 'HEAD'].includes(method)) {
- schemaHeader = 'Accept-Profile';
- }
- else if (['POST', 'PATCH', 'PUT', 'DELETE'].includes(method)) {
- schemaHeader = 'Content-Profile';
- }
- else
- return {};
- return _a = {}, _a[schemaHeader] = funcHeaderSchema(), _a;
- }
- else
- return {};
-};
-export default (function (config) { return ({
- getList: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var primaryKey = getPrimaryKey(resource, config.primaryKeys);
- var _c = params.pagination, page = _c.page, perPage = _c.perPage;
- var _d = params.sort || {}, field = _d.field, order = _d.order;
- var _e = parseFilters(params, config.defaultListOp), filter = _e.filter, select = _e.select;
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- var query = __assign({ offset: String((page - 1) * perPage), limit: String(perPage) }, filter);
- if (field) {
- query.order = getOrderBy(field, order, primaryKey);
- }
- if (select) {
- query.select = select;
- }
- // add header that Content-Range is in returned header
- var options = {
- headers: new Headers(__assign(__assign({ Accept: 'application/json', Prefer: 'count=exact' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'GET'))),
- };
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs.stringify(query));
- return config.httpClient(url, options).then(function (_a) {
- var headers = _a.headers, json = _a.json;
- if (!headers.has('content-range')) {
- 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?");
- }
- return {
- data: json.map(function (obj) { return dataWithVirtualId(obj, primaryKey); }),
- total: parseInt(headers.get('content-range').split('/').pop(), 10),
- };
- });
- },
- getOne: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var id = params.id, meta = params.meta;
- var primaryKey = getPrimaryKey(resource, config.primaryKeys);
- var query = getQuery(primaryKey, id, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- headers: new Headers(__assign(__assign({ accept: 'application/vnd.pgrst.object+json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'GET'))),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: dataWithVirtualId(json, primaryKey),
- });
- });
- },
- getMany: function (resource, params) {
- var _a;
- if (params === void 0) { params = {}; }
- var ids = params.ids;
- var primaryKey = getPrimaryKey(resource, config.primaryKeys);
- var query = getQuery(primaryKey, ids, resource, params.meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- headers: new Headers(__assign({}, useCustomSchema(config.schema, metaSchema, 'GET'))),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: json.map(function (data) { return dataWithVirtualId(data, primaryKey); }),
- });
- });
- },
- getManyReference: function (resource, params) {
- var _a;
- var _b, _c;
- if (params === void 0) { params = {}; }
- var _d = params.pagination, page = _d.page, perPage = _d.perPage;
- var _e = params.sort, field = _e.field, order = _e.order;
- var _f = parseFilters(params, config.defaultListOp), filter = _f.filter, select = _f.select;
- var primaryKey = getPrimaryKey(resource, config.primaryKeys);
- var metaSchema = (_b = params.meta) === null || _b === void 0 ? void 0 : _b.schema;
- var query = params.target
- ? __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);
- if (select) {
- query.select = select;
- }
- // add header that Content-Range is in returned header
- var options = {
- headers: new Headers(__assign(__assign({ Accept: 'application/json', Prefer: 'count=exact' }, (((_c = params.meta) === null || _c === void 0 ? void 0 : _c.headers) || {})), useCustomSchema(config.schema, metaSchema, 'GET'))),
- };
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs.stringify(query));
- return config.httpClient(url, options).then(function (_a) {
- var headers = _a.headers, json = _a.json;
- if (!headers.has('content-range')) {
- 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?");
- }
- return {
- data: json.map(function (data) { return dataWithVirtualId(data, primaryKey); }),
- total: parseInt(headers.get('content-range').split('/').pop(), 10),
- };
- });
- },
- update: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var id = params.id, data = params.data, meta = params.meta;
- var primaryKey = getPrimaryKey(resource, config.primaryKeys);
- var query = getQuery(primaryKey, id, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- var body = JSON.stringify(__assign({}, dataWithoutVirtualId(removePrimaryKey(data, primaryKey), primaryKey)));
- return config
- .httpClient(url, {
- method: 'PATCH',
- headers: new Headers(__assign(__assign({ Accept: 'application/vnd.pgrst.object+json', Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'PATCH'))),
- body: body,
- })
- .then(function (_a) {
- var json = _a.json;
- return ({ data: dataWithVirtualId(json, primaryKey) });
- });
- },
- updateMany: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var ids = params.ids, meta = params.meta, data = params.data;
- var primaryKey = getPrimaryKey(resource, config.primaryKeys);
- var query = getQuery(primaryKey, ids, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs.stringify(query));
- var body = JSON.stringify(__assign({}, dataWithoutVirtualId(removePrimaryKey(data, primaryKey), primaryKey)));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- method: 'PATCH',
- headers: new Headers(__assign(__assign({ Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'PATCH'))),
- body: body,
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: json.map(function (data) { return encodeId(data, primaryKey); }),
- });
- });
- },
- create: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var meta = params.meta;
- var primaryKey = getPrimaryKey(resource, config.primaryKeys);
- var query = getQuery(primaryKey, undefined, resource, meta);
- var queryStr = qs.stringify(query);
- var url = "".concat(config.apiUrl, "/").concat(resource).concat(queryStr.length > 0 ? '?' : '').concat(queryStr);
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- method: 'POST',
- headers: new Headers(__assign(__assign({ Accept: 'application/vnd.pgrst.object+json', Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'POST'))),
- body: JSON.stringify(dataWithoutVirtualId(params.data, primaryKey)),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: __assign(__assign({}, json), { id: encodeId(json, primaryKey) }),
- });
- });
- },
- delete: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var id = params.id, meta = params.meta;
- var primaryKey = getPrimaryKey(resource, config.primaryKeys);
- var query = getQuery(primaryKey, id, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- method: 'DELETE',
- headers: new Headers(__assign(__assign({ Accept: 'application/vnd.pgrst.object+json', Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'DELETE'))),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({ data: dataWithVirtualId(json, primaryKey) });
- });
- },
- deleteMany: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var ids = params.ids, meta = params.meta;
- var primaryKey = getPrimaryKey(resource, config.primaryKeys);
- var query = getQuery(primaryKey, ids, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- method: 'DELETE',
- headers: new Headers(__assign(__assign({ Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'DELETE'))),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: json.map(function (data) { return encodeId(data, primaryKey); }),
- });
- });
- },
-}); });
diff --git a/esm/urlBuilder.d.ts b/esm/urlBuilder.d.ts
deleted file mode 100644
index 9566e94..0000000
--- a/esm/urlBuilder.d.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { Identifier } from 'ra-core';
-/**
- * List of all possible operators in PostgRest
- * (https://postgrest.org/en/stable/api.html#operators)
- */
-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"];
-type ParsedFiltersResult = {
- filter: any;
- select: any;
-};
-export type PostgRestOperator = (typeof postgrestOperators)[number];
-export declare const parseFilters: (params: any, defaultListOp: PostgRestOperator) => Partial;
-export type PrimaryKey = Array;
-export declare const getPrimaryKey: (resource: string, primaryKeys: Map) => PrimaryKey;
-export declare const decodeId: (id: Identifier, primaryKey: PrimaryKey) => string[] | number[];
-export declare const encodeId: (data: any, primaryKey: PrimaryKey) => Identifier;
-export declare const removePrimaryKey: (data: any, primaryKey: PrimaryKey) => any;
-export declare const dataWithVirtualId: (data: any, primaryKey: PrimaryKey) => any;
-export declare const dataWithoutVirtualId: (data: any, primaryKey: PrimaryKey) => any;
-export declare const getQuery: (primaryKey: PrimaryKey, ids: Identifier | Array | undefined, resource: string, meta?: any) => any;
-export declare const getOrderBy: (field: string, order: string, primaryKey: PrimaryKey) => string;
-export {};
diff --git a/esm/urlBuilder.js b/esm/urlBuilder.js
deleted file mode 100644
index e3e0775..0000000
--- a/esm/urlBuilder.js
+++ /dev/null
@@ -1,268 +0,0 @@
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-};
-/**
- * List of all possible operators in PostgRest
- * (https://postgrest.org/en/stable/api.html#operators)
- */
-var postgrestOperators = [
- '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',
-];
-var isObject = function (obj) {
- return typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
-};
-var resolveKeys = function (filter, keys) {
- var result = filter[keys[0]];
- for (var i = 1; i < keys.length; ++i) {
- result = result[keys[i]];
- }
- return result;
-};
-export var parseFilters = function (params, defaultListOp) {
- var filter = params.filter, _a = params.meta, meta = _a === void 0 ? {} : _a;
- var result = {};
- result.filter = {};
- Object.keys(filter).forEach(function (key) {
- // key: the name of the object key
- var keyArray = [key];
- var values;
- // in case of a nested object selection in a text field
- // RA returns object{ object } structure which is resolved here
- // see issue https://github.com/raphiniert-com/ra-data-postgrest/issues/58
- if (key.split('@')[0] !== '' && isObject(filter[key])) {
- var innerVal = filter[key];
- do {
- var inner = resolveKeys(filter, keyArray);
- var innerKey = Object.keys(inner)[0];
- keyArray.push(innerKey);
- innerVal = inner[innerKey];
- } while (isObject(innerVal));
- key = keyArray.join('.');
- values = [innerVal];
- }
- else {
- values = [filter[key]];
- }
- var splitKey = key.split('@');
- var operation = splitKey.length == 2
- ? splitKey[1]
- : defaultListOp;
- if (['like', 'ilike'].includes(operation)) {
- // we split the search term in words
- values = resolveKeys(filter, keyArray).trim().split(/\s+/);
- }
- // CASE: Logical operator
- else if (['or', 'and'].includes(operation)) {
- // we extract each value entries and make it dot separated string.
- var subFilter = parseFilters({ filter: resolveKeys(filter, keyArray) }, defaultListOp).filter;
- // something like { "age@lt": 18 } and { "age@gt": 21 }
- var filterExpressions_1 = [];
- Object.entries(subFilter).forEach(function (_a) {
- var op = _a[0], val = _a[1];
- if (Array.isArray(val))
- filterExpressions_1.push.apply(filterExpressions_1, val.map(function (v) { return [op, v].join('.'); }));
- else
- filterExpressions_1.push([op, val].join('.'));
- });
- // finally we flatten all as single string and enclose with bracket.
- values = ["(".concat(filterExpressions_1.join(','), ")")];
- }
- values.forEach(function (value) {
- var op = (function () {
- // if operator is intentionally blank, rpc syntax
- if (operation.length === 0)
- return "".concat(value);
- if (operation.includes('like'))
- return "".concat(operation, ".*").concat(value, "*");
- if (['and', 'or'].includes(operation))
- return "".concat(value);
- if (['cs', 'cd'].includes(operation))
- return "".concat(operation, ".{").concat(value, "}");
- return "".concat(operation, ".").concat(value);
- })();
- // If resulting filter doesn't contain the fieldname, then add it.
- if (result.filter[splitKey[0]] === undefined) {
- // first operator for the key,
- if (['and', 'or'].includes(operation)) {
- result.filter[operation] = op;
- }
- else {
- // we add it to the dict
- result.filter[splitKey[0]] = op;
- }
- }
- else {
- if (!Array.isArray(result[splitKey[0]])) {
- // second operator, we transform to an array
- result.filter[splitKey[0]] = [
- result.filter[splitKey[0]],
- op,
- ];
- }
- else {
- // third and subsequent, we add to array
- result.filter[splitKey[0]].push(op);
- }
- }
- });
- });
- if (meta === null || meta === void 0 ? void 0 : meta.columns) {
- result.select = Array.isArray(meta.columns)
- ? meta.columns.join(',')
- : meta.columns;
- }
- return result;
-};
-export var getPrimaryKey = function (resource, primaryKeys) {
- return primaryKeys.get(resource) || ['id'];
-};
-export var decodeId = function (id, primaryKey) {
- if (isCompoundKey(primaryKey)) {
- return JSON.parse(id.toString());
- }
- else {
- return [id.toString()];
- }
-};
-export var encodeId = function (data, primaryKey) {
- if (isCompoundKey(primaryKey)) {
- return JSON.stringify(primaryKey.map(function (key) { return data[key]; }));
- }
- else {
- return data[primaryKey[0]];
- }
-};
-export var removePrimaryKey = function (data, primaryKey) {
- var newData = __assign({}, data);
- primaryKey.forEach(function (key) { delete newData[key]; });
- return newData;
-};
-export var dataWithVirtualId = function (data, primaryKey) {
- if (primaryKey.length === 1 && primaryKey[0] === 'id') {
- return data;
- }
- return Object.assign(data, {
- id: encodeId(data, primaryKey),
- });
-};
-export var dataWithoutVirtualId = function (data, primaryKey) {
- if (primaryKey.length === 1 && primaryKey[0] === 'id') {
- return data;
- }
- var id = data.id, dataWithoutId = __rest(data, ["id"]);
- return dataWithoutId;
-};
-var isCompoundKey = function (primaryKey) {
- return primaryKey.length > 1;
-};
-export var getQuery = function (primaryKey, ids, resource, meta) {
- var _a, _b;
- if (meta === void 0) { meta = null; }
- var result = {};
- if (Array.isArray(ids) && ids.length > 1) {
- // no standardized query with multiple ids possible for rpc endpoints which are api-exposed database functions
- if (resource.startsWith('rpc/')) {
- console.error("PostgREST's rpc endpoints are not intended to be handled as views. Therefore, no query generation for multiple key values implemented!");
- return;
- }
- if (isCompoundKey(primaryKey)) {
- result = {
- or: "(".concat(ids.map(function (id) {
- var primaryKeyParams = decodeId(id, primaryKey);
- return "and(".concat(primaryKey
- .map(function (key, i) { return "".concat(key, ".eq.").concat(primaryKeyParams[i]); })
- .join(','), ")");
- }), ")"),
- };
- }
- else {
- result = (_a = {},
- _a[primaryKey[0]] = "in.(".concat(ids.join(','), ")"),
- _a);
- }
- }
- else if (ids) {
- // if ids is one Identifier
- var id = ids.toString();
- var primaryKeyParams_1 = decodeId(id, primaryKey);
- if (isCompoundKey(primaryKey)) {
- if (resource.startsWith('rpc/')) {
- result = {};
- primaryKey.map(function (key, i) {
- return (result[key] = "".concat(primaryKeyParams_1[i]));
- });
- }
- else {
- result = {
- and: "(".concat(primaryKey.map(function (key, i) {
- return "".concat(key, ".eq.").concat(primaryKeyParams_1[i]);
- }), ")"),
- };
- }
- }
- else {
- result = (_b = {},
- _b[primaryKey[0]] = "eq.".concat(id),
- _b);
- }
- }
- if (meta && meta.columns) {
- result.select = Array.isArray(meta.columns)
- ? meta.columns.join(',')
- : meta.columns;
- }
- return result;
-};
-export var getOrderBy = function (field, order, primaryKey) {
- if (field == 'id') {
- return primaryKey.map(function (key) { return "".concat(key, ".").concat(order.toLowerCase()); }).join(',');
- }
- else {
- return "".concat(field, ".").concat(order.toLowerCase());
- }
-};
diff --git a/lib/index.d.ts b/lib/index.d.ts
deleted file mode 100644
index 68d0360..0000000
--- a/lib/index.d.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { DataProvider } from 'ra-core';
-import { PrimaryKey, PostgRestOperator } from './urlBuilder';
-/**
- * Maps react-admin queries to a postgrest REST API
- *
- * This REST dialect uses postgrest syntax
- *
- * @see https://postgrest.org/en/stable/api.html#embedded-filters
- *
- * @example
- *
- * getList => GET http://my.api.url/posts?order=title.asc&offset=0&limit=24&filterField=eq.value
- * getOne => GET http://my.api.url/posts?id=eq.123
- * getMany => GET http://my.api.url/posts?id=in.(123,456,789)
- * getManyReference => GET http://my.api.url/posts?author_id=eq.345
- * create => POST http://my.api.url/posts
- * update => PATCH http://my.api.url/posts?id=eq.123
- * updateMany => PATCH http://my.api.url/posts?id=in.(123,456,789)
- * delete => DELETE http://my.api.url/posts?id=eq.123
- * deleteMany => DELETE http://my.api.url/posts?id=in.(123,456,789)
- *
- * @example
- *
- * import * as React from 'react';
- * import { Admin, Resource, fetchUtils } from 'react-admin';
- * import postgrestRestProvider,
- * { IDataProviderConfig,
- * defaultPrimaryKeys,
- * defaultSchema } from '@raphiniert/ra-data-postgrest';
- *
- * import { PostList } from './posts';
- *
- * const config: IDataProviderConfig = {
- * apiUrl: 'http://path.to.my.api/',
- * httpClient: fetchUtils.fetchJson,
- * defaultListOp: 'eq',
- * primaryKeys: defaultPrimaryKeys,
- * schema: defaultSchema
- * }
- *
- * const App = () => (
- *
- *
- *
- * );
- *
- * export default App;
- */
-export type MetaOption = string | undefined;
-export declare const defaultPrimaryKeys: Map;
-export declare const defaultSchema: () => string;
-export interface IDataProviderConfig {
- apiUrl: string;
- httpClient: (string: any, Options: any) => Promise;
- defaultListOp: PostgRestOperator;
- primaryKeys: Map;
- schema: () => string;
-}
-declare const _default: (config: IDataProviderConfig) => DataProvider;
-export default _default;
diff --git a/lib/index.js b/lib/index.js
deleted file mode 100644
index afa26d3..0000000
--- a/lib/index.js
+++ /dev/null
@@ -1,246 +0,0 @@
-"use strict";
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.defaultSchema = exports.defaultPrimaryKeys = void 0;
-var urlBuilder_1 = require("./urlBuilder");
-var qs_1 = __importDefault(require("qs"));
-exports.defaultPrimaryKeys = new Map();
-var defaultSchema = function () { return ''; };
-exports.defaultSchema = defaultSchema;
-var useCustomSchema = function (schema, metaSchema, method) {
- var _a;
- var funcHeaderSchema = schema;
- if (metaSchema !== undefined) {
- funcHeaderSchema = function () { return metaSchema; };
- }
- if (funcHeaderSchema().length > 0) {
- var schemaHeader = '';
- if (['GET', 'HEAD'].includes(method)) {
- schemaHeader = 'Accept-Profile';
- }
- else if (['POST', 'PATCH', 'PUT', 'DELETE'].includes(method)) {
- schemaHeader = 'Content-Profile';
- }
- else
- return {};
- return _a = {}, _a[schemaHeader] = funcHeaderSchema(), _a;
- }
- else
- return {};
-};
-exports.default = (function (config) { return ({
- getList: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
- var _c = params.pagination, page = _c.page, perPage = _c.perPage;
- var _d = params.sort || {}, field = _d.field, order = _d.order;
- var _e = (0, urlBuilder_1.parseFilters)(params, config.defaultListOp), filter = _e.filter, select = _e.select;
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- var query = __assign({ offset: String((page - 1) * perPage), limit: String(perPage) }, filter);
- if (field) {
- query.order = (0, urlBuilder_1.getOrderBy)(field, order, primaryKey);
- }
- if (select) {
- query.select = select;
- }
- // add header that Content-Range is in returned header
- var options = {
- headers: new Headers(__assign(__assign({ Accept: 'application/json', Prefer: 'count=exact' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'GET'))),
- };
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs_1.default.stringify(query));
- return config.httpClient(url, options).then(function (_a) {
- var headers = _a.headers, json = _a.json;
- if (!headers.has('content-range')) {
- 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?");
- }
- return {
- data: json.map(function (obj) { return (0, urlBuilder_1.dataWithVirtualId)(obj, primaryKey); }),
- total: parseInt(headers.get('content-range').split('/').pop(), 10),
- };
- });
- },
- getOne: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var id = params.id, meta = params.meta;
- var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
- var query = (0, urlBuilder_1.getQuery)(primaryKey, id, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs_1.default.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- headers: new Headers(__assign(__assign({ accept: 'application/vnd.pgrst.object+json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'GET'))),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: (0, urlBuilder_1.dataWithVirtualId)(json, primaryKey),
- });
- });
- },
- getMany: function (resource, params) {
- var _a;
- if (params === void 0) { params = {}; }
- var ids = params.ids;
- var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
- var query = (0, urlBuilder_1.getQuery)(primaryKey, ids, resource, params.meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs_1.default.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- headers: new Headers(__assign({}, useCustomSchema(config.schema, metaSchema, 'GET'))),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: json.map(function (data) { return (0, urlBuilder_1.dataWithVirtualId)(data, primaryKey); }),
- });
- });
- },
- getManyReference: function (resource, params) {
- var _a;
- var _b, _c;
- if (params === void 0) { params = {}; }
- var _d = params.pagination, page = _d.page, perPage = _d.perPage;
- var _e = params.sort, field = _e.field, order = _e.order;
- var _f = (0, urlBuilder_1.parseFilters)(params, config.defaultListOp), filter = _f.filter, select = _f.select;
- var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
- var metaSchema = (_b = params.meta) === null || _b === void 0 ? void 0 : _b.schema;
- var query = params.target
- ? __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);
- if (select) {
- query.select = select;
- }
- // add header that Content-Range is in returned header
- var options = {
- headers: new Headers(__assign(__assign({ Accept: 'application/json', Prefer: 'count=exact' }, (((_c = params.meta) === null || _c === void 0 ? void 0 : _c.headers) || {})), useCustomSchema(config.schema, metaSchema, 'GET'))),
- };
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs_1.default.stringify(query));
- return config.httpClient(url, options).then(function (_a) {
- var headers = _a.headers, json = _a.json;
- if (!headers.has('content-range')) {
- 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?");
- }
- return {
- data: json.map(function (data) { return (0, urlBuilder_1.dataWithVirtualId)(data, primaryKey); }),
- total: parseInt(headers.get('content-range').split('/').pop(), 10),
- };
- });
- },
- update: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var id = params.id, data = params.data, meta = params.meta;
- var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
- var query = (0, urlBuilder_1.getQuery)(primaryKey, id, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs_1.default.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- var body = JSON.stringify(__assign({}, (0, urlBuilder_1.dataWithoutVirtualId)((0, urlBuilder_1.removePrimaryKey)(data, primaryKey), primaryKey)));
- return config
- .httpClient(url, {
- method: 'PATCH',
- headers: new Headers(__assign(__assign({ Accept: 'application/vnd.pgrst.object+json', Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'PATCH'))),
- body: body,
- })
- .then(function (_a) {
- var json = _a.json;
- return ({ data: (0, urlBuilder_1.dataWithVirtualId)(json, primaryKey) });
- });
- },
- updateMany: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var ids = params.ids, meta = params.meta, data = params.data;
- var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
- var query = (0, urlBuilder_1.getQuery)(primaryKey, ids, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs_1.default.stringify(query));
- var body = JSON.stringify(__assign({}, (0, urlBuilder_1.dataWithoutVirtualId)((0, urlBuilder_1.removePrimaryKey)(data, primaryKey), primaryKey)));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- method: 'PATCH',
- headers: new Headers(__assign(__assign({ Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'PATCH'))),
- body: body,
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: json.map(function (data) { return (0, urlBuilder_1.encodeId)(data, primaryKey); }),
- });
- });
- },
- create: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var meta = params.meta;
- var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
- var query = (0, urlBuilder_1.getQuery)(primaryKey, undefined, resource, meta);
- var queryStr = qs_1.default.stringify(query);
- var url = "".concat(config.apiUrl, "/").concat(resource).concat(queryStr.length > 0 ? '?' : '').concat(queryStr);
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- method: 'POST',
- headers: new Headers(__assign(__assign({ Accept: 'application/vnd.pgrst.object+json', Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'POST'))),
- body: JSON.stringify((0, urlBuilder_1.dataWithoutVirtualId)(params.data, primaryKey)),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: __assign(__assign({}, json), { id: (0, urlBuilder_1.encodeId)(json, primaryKey) }),
- });
- });
- },
- delete: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var id = params.id, meta = params.meta;
- var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
- var query = (0, urlBuilder_1.getQuery)(primaryKey, id, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs_1.default.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- method: 'DELETE',
- headers: new Headers(__assign(__assign({ Accept: 'application/vnd.pgrst.object+json', Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'DELETE'))),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({ data: (0, urlBuilder_1.dataWithVirtualId)(json, primaryKey) });
- });
- },
- deleteMany: function (resource, params) {
- var _a, _b;
- if (params === void 0) { params = {}; }
- var ids = params.ids, meta = params.meta;
- var primaryKey = (0, urlBuilder_1.getPrimaryKey)(resource, config.primaryKeys);
- var query = (0, urlBuilder_1.getQuery)(primaryKey, ids, resource, meta);
- var url = "".concat(config.apiUrl, "/").concat(resource, "?").concat(qs_1.default.stringify(query));
- var metaSchema = (_a = params.meta) === null || _a === void 0 ? void 0 : _a.schema;
- return config
- .httpClient(url, {
- method: 'DELETE',
- headers: new Headers(__assign(__assign({ Prefer: 'return=representation', 'Content-Type': 'application/json' }, (((_b = params.meta) === null || _b === void 0 ? void 0 : _b.headers) || {})), useCustomSchema(config.schema, metaSchema, 'DELETE'))),
- })
- .then(function (_a) {
- var json = _a.json;
- return ({
- data: json.map(function (data) { return (0, urlBuilder_1.encodeId)(data, primaryKey); }),
- });
- });
- },
-}); });
diff --git a/lib/urlBuilder.d.ts b/lib/urlBuilder.d.ts
deleted file mode 100644
index 9566e94..0000000
--- a/lib/urlBuilder.d.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { Identifier } from 'ra-core';
-/**
- * List of all possible operators in PostgRest
- * (https://postgrest.org/en/stable/api.html#operators)
- */
-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"];
-type ParsedFiltersResult = {
- filter: any;
- select: any;
-};
-export type PostgRestOperator = (typeof postgrestOperators)[number];
-export declare const parseFilters: (params: any, defaultListOp: PostgRestOperator) => Partial;
-export type PrimaryKey = Array;
-export declare const getPrimaryKey: (resource: string, primaryKeys: Map) => PrimaryKey;
-export declare const decodeId: (id: Identifier, primaryKey: PrimaryKey) => string[] | number[];
-export declare const encodeId: (data: any, primaryKey: PrimaryKey) => Identifier;
-export declare const removePrimaryKey: (data: any, primaryKey: PrimaryKey) => any;
-export declare const dataWithVirtualId: (data: any, primaryKey: PrimaryKey) => any;
-export declare const dataWithoutVirtualId: (data: any, primaryKey: PrimaryKey) => any;
-export declare const getQuery: (primaryKey: PrimaryKey, ids: Identifier | Array | undefined, resource: string, meta?: any) => any;
-export declare const getOrderBy: (field: string, order: string, primaryKey: PrimaryKey) => string;
-export {};
diff --git a/lib/urlBuilder.js b/lib/urlBuilder.js
deleted file mode 100644
index 46ffcae..0000000
--- a/lib/urlBuilder.js
+++ /dev/null
@@ -1,280 +0,0 @@
-"use strict";
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.getOrderBy = exports.getQuery = exports.dataWithoutVirtualId = exports.dataWithVirtualId = exports.removePrimaryKey = exports.encodeId = exports.decodeId = exports.getPrimaryKey = exports.parseFilters = void 0;
-/**
- * List of all possible operators in PostgRest
- * (https://postgrest.org/en/stable/api.html#operators)
- */
-var postgrestOperators = [
- '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',
-];
-var isObject = function (obj) {
- return typeof obj === 'object' && !Array.isArray(obj) && obj !== null;
-};
-var resolveKeys = function (filter, keys) {
- var result = filter[keys[0]];
- for (var i = 1; i < keys.length; ++i) {
- result = result[keys[i]];
- }
- return result;
-};
-var parseFilters = function (params, defaultListOp) {
- var filter = params.filter, _a = params.meta, meta = _a === void 0 ? {} : _a;
- var result = {};
- result.filter = {};
- Object.keys(filter).forEach(function (key) {
- // key: the name of the object key
- var keyArray = [key];
- var values;
- // in case of a nested object selection in a text field
- // RA returns object{ object } structure which is resolved here
- // see issue https://github.com/raphiniert-com/ra-data-postgrest/issues/58
- if (key.split('@')[0] !== '' && isObject(filter[key])) {
- var innerVal = filter[key];
- do {
- var inner = resolveKeys(filter, keyArray);
- var innerKey = Object.keys(inner)[0];
- keyArray.push(innerKey);
- innerVal = inner[innerKey];
- } while (isObject(innerVal));
- key = keyArray.join('.');
- values = [innerVal];
- }
- else {
- values = [filter[key]];
- }
- var splitKey = key.split('@');
- var operation = splitKey.length == 2
- ? splitKey[1]
- : defaultListOp;
- if (['like', 'ilike'].includes(operation)) {
- // we split the search term in words
- values = resolveKeys(filter, keyArray).trim().split(/\s+/);
- }
- // CASE: Logical operator
- else if (['or', 'and'].includes(operation)) {
- // we extract each value entries and make it dot separated string.
- var subFilter = (0, exports.parseFilters)({ filter: resolveKeys(filter, keyArray) }, defaultListOp).filter;
- // something like { "age@lt": 18 } and { "age@gt": 21 }
- var filterExpressions_1 = [];
- Object.entries(subFilter).forEach(function (_a) {
- var op = _a[0], val = _a[1];
- if (Array.isArray(val))
- filterExpressions_1.push.apply(filterExpressions_1, val.map(function (v) { return [op, v].join('.'); }));
- else
- filterExpressions_1.push([op, val].join('.'));
- });
- // finally we flatten all as single string and enclose with bracket.
- values = ["(".concat(filterExpressions_1.join(','), ")")];
- }
- values.forEach(function (value) {
- var op = (function () {
- // if operator is intentionally blank, rpc syntax
- if (operation.length === 0)
- return "".concat(value);
- if (operation.includes('like'))
- return "".concat(operation, ".*").concat(value, "*");
- if (['and', 'or'].includes(operation))
- return "".concat(value);
- if (['cs', 'cd'].includes(operation))
- return "".concat(operation, ".{").concat(value, "}");
- return "".concat(operation, ".").concat(value);
- })();
- // If resulting filter doesn't contain the fieldname, then add it.
- if (result.filter[splitKey[0]] === undefined) {
- // first operator for the key,
- if (['and', 'or'].includes(operation)) {
- result.filter[operation] = op;
- }
- else {
- // we add it to the dict
- result.filter[splitKey[0]] = op;
- }
- }
- else {
- if (!Array.isArray(result[splitKey[0]])) {
- // second operator, we transform to an array
- result.filter[splitKey[0]] = [
- result.filter[splitKey[0]],
- op,
- ];
- }
- else {
- // third and subsequent, we add to array
- result.filter[splitKey[0]].push(op);
- }
- }
- });
- });
- if (meta === null || meta === void 0 ? void 0 : meta.columns) {
- result.select = Array.isArray(meta.columns)
- ? meta.columns.join(',')
- : meta.columns;
- }
- return result;
-};
-exports.parseFilters = parseFilters;
-var getPrimaryKey = function (resource, primaryKeys) {
- return primaryKeys.get(resource) || ['id'];
-};
-exports.getPrimaryKey = getPrimaryKey;
-var decodeId = function (id, primaryKey) {
- if (isCompoundKey(primaryKey)) {
- return JSON.parse(id.toString());
- }
- else {
- return [id.toString()];
- }
-};
-exports.decodeId = decodeId;
-var encodeId = function (data, primaryKey) {
- if (isCompoundKey(primaryKey)) {
- return JSON.stringify(primaryKey.map(function (key) { return data[key]; }));
- }
- else {
- return data[primaryKey[0]];
- }
-};
-exports.encodeId = encodeId;
-var removePrimaryKey = function (data, primaryKey) {
- var newData = __assign({}, data);
- primaryKey.forEach(function (key) { delete newData[key]; });
- return newData;
-};
-exports.removePrimaryKey = removePrimaryKey;
-var dataWithVirtualId = function (data, primaryKey) {
- if (primaryKey.length === 1 && primaryKey[0] === 'id') {
- return data;
- }
- return Object.assign(data, {
- id: (0, exports.encodeId)(data, primaryKey),
- });
-};
-exports.dataWithVirtualId = dataWithVirtualId;
-var dataWithoutVirtualId = function (data, primaryKey) {
- if (primaryKey.length === 1 && primaryKey[0] === 'id') {
- return data;
- }
- var id = data.id, dataWithoutId = __rest(data, ["id"]);
- return dataWithoutId;
-};
-exports.dataWithoutVirtualId = dataWithoutVirtualId;
-var isCompoundKey = function (primaryKey) {
- return primaryKey.length > 1;
-};
-var getQuery = function (primaryKey, ids, resource, meta) {
- var _a, _b;
- if (meta === void 0) { meta = null; }
- var result = {};
- if (Array.isArray(ids) && ids.length > 1) {
- // no standardized query with multiple ids possible for rpc endpoints which are api-exposed database functions
- if (resource.startsWith('rpc/')) {
- console.error("PostgREST's rpc endpoints are not intended to be handled as views. Therefore, no query generation for multiple key values implemented!");
- return;
- }
- if (isCompoundKey(primaryKey)) {
- result = {
- or: "(".concat(ids.map(function (id) {
- var primaryKeyParams = (0, exports.decodeId)(id, primaryKey);
- return "and(".concat(primaryKey
- .map(function (key, i) { return "".concat(key, ".eq.").concat(primaryKeyParams[i]); })
- .join(','), ")");
- }), ")"),
- };
- }
- else {
- result = (_a = {},
- _a[primaryKey[0]] = "in.(".concat(ids.join(','), ")"),
- _a);
- }
- }
- else if (ids) {
- // if ids is one Identifier
- var id = ids.toString();
- var primaryKeyParams_1 = (0, exports.decodeId)(id, primaryKey);
- if (isCompoundKey(primaryKey)) {
- if (resource.startsWith('rpc/')) {
- result = {};
- primaryKey.map(function (key, i) {
- return (result[key] = "".concat(primaryKeyParams_1[i]));
- });
- }
- else {
- result = {
- and: "(".concat(primaryKey.map(function (key, i) {
- return "".concat(key, ".eq.").concat(primaryKeyParams_1[i]);
- }), ")"),
- };
- }
- }
- else {
- result = (_b = {},
- _b[primaryKey[0]] = "eq.".concat(id),
- _b);
- }
- }
- if (meta && meta.columns) {
- result.select = Array.isArray(meta.columns)
- ? meta.columns.join(',')
- : meta.columns;
- }
- return result;
-};
-exports.getQuery = getQuery;
-var getOrderBy = function (field, order, primaryKey) {
- if (field == 'id') {
- return primaryKey.map(function (key) { return "".concat(key, ".").concat(order.toLowerCase()); }).join(',');
- }
- else {
- return "".concat(field, ".").concat(order.toLowerCase());
- }
-};
-exports.getOrderBy = getOrderBy;