@xata.io/client 0.0.0-beta.f46df88 → 0.0.0-beta.f65b504

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/api/client.d.ts +1 -1
  3. package/dist/api/client.js +32 -17
  4. package/dist/api/components.d.ts +7 -6
  5. package/dist/api/components.js +7 -6
  6. package/dist/api/fetcher.d.ts +15 -0
  7. package/dist/api/fetcher.js +19 -13
  8. package/dist/client.d.ts +39 -0
  9. package/dist/client.js +124 -0
  10. package/dist/index.d.ts +3 -0
  11. package/dist/index.js +3 -0
  12. package/dist/namespace.d.ts +7 -0
  13. package/dist/namespace.js +6 -0
  14. package/dist/schema/filters.d.ts +93 -19
  15. package/dist/schema/filters.js +0 -23
  16. package/dist/schema/filters.spec.d.ts +1 -0
  17. package/dist/schema/filters.spec.js +177 -0
  18. package/dist/schema/index.d.ts +16 -2
  19. package/dist/schema/index.js +26 -6
  20. package/dist/schema/operators.d.ts +26 -24
  21. package/dist/schema/operators.js +13 -11
  22. package/dist/schema/query.d.ts +8 -8
  23. package/dist/schema/record.d.ts +5 -5
  24. package/dist/schema/repository.d.ts +82 -48
  25. package/dist/schema/repository.js +162 -166
  26. package/dist/schema/selection.d.ts +5 -4
  27. package/dist/schema/selection.spec.js +154 -59
  28. package/dist/schema/sorting.d.ts +17 -0
  29. package/dist/schema/sorting.js +28 -0
  30. package/dist/schema/sorting.spec.d.ts +1 -0
  31. package/dist/schema/sorting.spec.js +11 -0
  32. package/dist/search/index.d.ts +20 -0
  33. package/dist/search/index.js +30 -0
  34. package/dist/util/branches.d.ts +5 -0
  35. package/dist/util/branches.js +7 -0
  36. package/dist/util/config.d.ts +11 -0
  37. package/dist/util/config.js +121 -0
  38. package/dist/util/environment.d.ts +5 -0
  39. package/dist/util/environment.js +68 -0
  40. package/dist/util/fetch.d.ts +2 -0
  41. package/dist/util/fetch.js +13 -0
  42. package/dist/util/lang.d.ts +1 -1
  43. package/dist/util/lang.js +1 -1
  44. package/dist/util/types.d.ts +12 -0
  45. package/package.json +5 -2
@@ -1,40 +1,62 @@
1
- import { FetchImpl } from '../api/fetcher';
1
+ import { SchemaNamespaceResult } from '.';
2
+ import { FetcherExtraProps } from '../api/fetcher';
3
+ import { Dictionary } from '../util/types';
2
4
  import { Page } from './pagination';
3
5
  import { Query } from './query';
4
6
  import { BaseData, EditableData, Identifiable, XataRecord } from './record';
5
7
  import { SelectedPick } from './selection';
6
- export declare type Links = Record<string, Array<string[]>>;
8
+ declare type TableLink = string[];
9
+ export declare type LinkDictionary = Dictionary<TableLink[]>;
7
10
  /**
8
11
  * Common interface for performing operations on a table.
9
12
  */
10
- export declare abstract class Repository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record, SelectedPick<Record, ['*']>> {
11
- abstract create(object: EditableData<Data> & Partial<Identifiable>): Promise<SelectedPick<Record, ['*']>>;
13
+ export declare abstract class Repository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record, Readonly<SelectedPick<Record, ['*']>>> {
14
+ abstract create(object: EditableData<Data> & Partial<Identifiable>): Promise<Readonly<SelectedPick<Record, ['*']>>>;
12
15
  /**
13
16
  * Creates a single record in the table with a unique id.
14
17
  * @param id The unique id.
15
18
  * @param object Object containing the column names with their values to be stored in the table.
16
19
  * @returns The full persisted record.
17
20
  */
18
- abstract create(id: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
21
+ abstract create(id: string, object: EditableData<Data>): Promise<Readonly<SelectedPick<Record, ['*']>>>;
19
22
  /**
20
23
  * Creates multiple records in the table.
21
24
  * @param objects Array of objects with the column names and the values to be stored in the table.
22
25
  * @returns Array of the persisted records.
23
26
  */
24
- abstract createMany(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
27
+ abstract create(objects: Array<EditableData<Data> & Partial<Identifiable>>): Promise<Readonly<SelectedPick<Record, ['*']>>[]>;
25
28
  /**
26
29
  * Queries a single record from the table given its unique id.
27
30
  * @param id The unique id.
28
31
  * @returns The persisted record for the given id or null if the record could not be found.
29
32
  */
30
- abstract read(id: string): Promise<SelectedPick<Record, ['*']> | null>;
33
+ abstract read(id: string): Promise<Readonly<SelectedPick<Record, ['*']> | null>>;
34
+ /**
35
+ * Partially update a single record.
36
+ * @param object An object with its id and the columns to be updated.
37
+ * @returns The full persisted record.
38
+ */
39
+ abstract update(object: Partial<EditableData<Data>> & Identifiable): Promise<Readonly<SelectedPick<Record, ['*']>>>;
31
40
  /**
32
41
  * Partially update a single record given its unique id.
33
42
  * @param id The unique id.
34
- * @param object The column names and their values that have to be updatd.
43
+ * @param object The column names and their values that have to be updated.
35
44
  * @returns The full persisted record.
36
45
  */
37
- abstract update(id: string, object: Partial<EditableData<Data>>): Promise<SelectedPick<Record, ['*']>>;
46
+ abstract update(id: string, object: Partial<EditableData<Data>>): Promise<Readonly<SelectedPick<Record, ['*']>>>;
47
+ /**
48
+ * Partially updates multiple records.
49
+ * @param objects An array of objects with their ids and columns to be updated.
50
+ * @returns Array of the persisted records.
51
+ */
52
+ abstract update(objects: Array<Partial<EditableData<Data>> & Identifiable>): Promise<Readonly<SelectedPick<Record, ['*']>>[]>;
53
+ /**
54
+ * Creates or updates a single record. If a record exists with the given id,
55
+ * it will be update, otherwise a new record will be created.
56
+ * @param object Object containing the column names with their values to be persisted in the table.
57
+ * @returns The full persisted record.
58
+ */
59
+ abstract createOrUpdate(object: EditableData<Data> & Identifiable): Promise<Readonly<SelectedPick<Record, ['*']>>>;
38
60
  /**
39
61
  * Creates or updates a single record. If a record exists with the given id,
40
62
  * it will be update, otherwise a new record will be created.
@@ -42,59 +64,71 @@ export declare abstract class Repository<Data extends BaseData, Record extends X
42
64
  * @param object The column names and the values to be persisted.
43
65
  * @returns The full persisted record.
44
66
  */
45
- abstract createOrUpdate(id: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
67
+ abstract createOrUpdate(id: string, object: EditableData<Data>): Promise<Readonly<SelectedPick<Record, ['*']>>>;
68
+ /**
69
+ * Creates or updates a single record. If a record exists with the given id,
70
+ * it will be update, otherwise a new record will be created.
71
+ * @param objects Array of objects with the column names and the values to be stored in the table.
72
+ * @returns Array of the persisted records.
73
+ */
74
+ abstract createOrUpdate(objects: Array<EditableData<Data> & Identifiable>): Promise<Readonly<SelectedPick<Record, ['*']>>[]>;
46
75
  /**
47
76
  * Deletes a record given its unique id.
48
77
  * @param id The unique id.
49
78
  * @throws If the record could not be found or there was an error while performing the deletion.
50
79
  */
51
- abstract delete(id: string): void;
80
+ abstract delete(id: string): Promise<void>;
81
+ /**
82
+ * Deletes a record given its unique id.
83
+ * @param id An object with a unique id.
84
+ * @throws If the record could not be found or there was an error while performing the deletion.
85
+ */
86
+ abstract delete(id: Identifiable): Promise<void>;
87
+ /**
88
+ * Deletes a record given a list of unique ids.
89
+ * @param ids The array of unique ids.
90
+ * @throws If the record could not be found or there was an error while performing the deletion.
91
+ */
92
+ abstract delete(ids: string[]): Promise<void>;
93
+ /**
94
+ * Deletes a record given a list of unique ids.
95
+ * @param ids An array of objects with unique ids.
96
+ * @throws If the record could not be found or there was an error while performing the deletion.
97
+ */
98
+ abstract delete(ids: Identifiable[]): Promise<void>;
99
+ /**
100
+ * Search for records in the table.
101
+ * @param query The query to search for.
102
+ * @param options The options to search with (like: fuzziness)
103
+ * @returns The found records.
104
+ */
105
+ abstract search(query: string, options?: {
106
+ fuzziness?: number;
107
+ }): Promise<SelectedPick<Record, ['*']>[]>;
52
108
  abstract query<Result extends XataRecord>(query: Query<Record, Result>): Promise<Page<Record, Result>>;
53
109
  }
54
110
  export declare class RestRepository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record, SelectedPick<Record, ['*']>> {
55
111
  #private;
56
- constructor(client: BaseClient<any>, table: string);
112
+ constructor(options: {
113
+ table: string;
114
+ links?: LinkDictionary;
115
+ getFetchProps: () => Promise<FetcherExtraProps>;
116
+ schemaNamespace: SchemaNamespaceResult<any>;
117
+ });
57
118
  create(object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
58
119
  create(recordId: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
59
- createMany(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
120
+ create(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
60
121
  read(recordId: string): Promise<SelectedPick<Record, ['*']> | null>;
122
+ update(object: Partial<EditableData<Data>> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
61
123
  update(recordId: string, object: Partial<EditableData<Data>>): Promise<SelectedPick<Record, ['*']>>;
124
+ update(objects: Array<Partial<EditableData<Data>> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
125
+ createOrUpdate(object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
62
126
  createOrUpdate(recordId: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
63
- delete(recordId: string): Promise<void>;
127
+ createOrUpdate(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
128
+ delete(recordId: string | Identifiable | Array<string | Identifiable>): Promise<void>;
129
+ search(query: string, options?: {
130
+ fuzziness?: number;
131
+ }): Promise<SelectedPick<Record, ['*']>[]>;
64
132
  query<Result extends XataRecord>(query: Query<Record, Result>): Promise<Page<Record, Result>>;
65
133
  }
66
- interface RepositoryFactory {
67
- createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data & XataRecord>;
68
- }
69
- export declare class RestRespositoryFactory implements RepositoryFactory {
70
- createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data & XataRecord>;
71
- }
72
- declare type BranchStrategyValue = string | undefined | null;
73
- declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
74
- declare type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder;
75
- declare type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>;
76
- export declare type XataClientOptions = {
77
- /**
78
- * Fetch implementation. This option is only required if the runtime does not include a fetch implementation
79
- * available in the global scope. If you are running your code on Deno or Cloudflare workers for example,
80
- * you won't need to provide a specific fetch implementation. But for most versions of Node.js you'll need
81
- * to provide one. Such as cross-fetch, node-fetch or isomorphic-fetch.
82
- */
83
- fetch?: FetchImpl;
84
- databaseURL?: string;
85
- branch: BranchStrategyOption;
86
- /**
87
- * API key to be used. You can create one in your account settings at https://app.xata.io/settings.
88
- */
89
- apiKey: string;
90
- repositoryFactory?: RepositoryFactory;
91
- };
92
- export declare class BaseClient<D extends Record<string, Repository<any>> = Record<string, Repository<any>>> {
93
- #private;
94
- options: XataClientOptions;
95
- db: D;
96
- constructor(options: XataClientOptions, links?: Links);
97
- initObject<T>(table: string, object: object): T;
98
- getBranch(): Promise<string>;
99
- }
100
134
  export {};
@@ -19,22 +19,15 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
19
19
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
20
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
21
  };
22
- var __asyncValues = (this && this.__asyncValues) || function (o) {
23
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
24
- var m = o[Symbol.asyncIterator], i;
25
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
26
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
27
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
- };
29
- var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _BaseClient_links, _BaseClient_branch;
22
+ var _RestRepository_instances, _RestRepository_table, _RestRepository_links, _RestRepository_getFetchProps, _RestRepository_schemaNamespace, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _RestRepository_bulkInsertTableRecords, _RestRepository_updateRecordWithID, _RestRepository_upsertRecordWithID, _RestRepository_deleteRecord, _RestRepository_initObject;
30
23
  Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
24
+ exports.RestRepository = exports.Repository = void 0;
32
25
  const api_1 = require("../api");
33
26
  const lang_1 = require("../util/lang");
34
- const filters_1 = require("./filters");
35
27
  const pagination_1 = require("./pagination");
36
28
  const query_1 = require("./query");
37
29
  const record_1 = require("./record");
30
+ const sorting_1 = require("./sorting");
38
31
  /**
39
32
  * Common interface for performing operations on a table.
40
33
  */
@@ -42,89 +35,131 @@ class Repository extends query_1.Query {
42
35
  }
43
36
  exports.Repository = Repository;
44
37
  class RestRepository extends query_1.Query {
45
- constructor(client, table) {
38
+ constructor(options) {
46
39
  var _a;
47
- super(null, table, {});
40
+ super(null, options.table, {});
48
41
  _RestRepository_instances.add(this);
49
- _RestRepository_client.set(this, void 0);
50
- _RestRepository_fetch.set(this, void 0);
51
42
  _RestRepository_table.set(this, void 0);
52
- __classPrivateFieldSet(this, _RestRepository_client, client, "f");
53
- __classPrivateFieldSet(this, _RestRepository_table, table, "f");
54
- // TODO: Remove when integrating with API client
55
- const globalFetch = typeof fetch !== 'undefined' ? fetch : undefined;
56
- const fetchImpl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch) !== null && _a !== void 0 ? _a : globalFetch;
57
- if (!fetchImpl) {
58
- /** @todo add a link after docs exist */
59
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
60
- }
61
- __classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f");
43
+ _RestRepository_links.set(this, void 0);
44
+ _RestRepository_getFetchProps.set(this, void 0);
45
+ _RestRepository_schemaNamespace.set(this, void 0);
46
+ __classPrivateFieldSet(this, _RestRepository_table, options.table, "f");
47
+ __classPrivateFieldSet(this, _RestRepository_links, (_a = options.links) !== null && _a !== void 0 ? _a : {}, "f");
48
+ __classPrivateFieldSet(this, _RestRepository_getFetchProps, options.getFetchProps, "f");
49
+ __classPrivateFieldSet(this, _RestRepository_schemaNamespace, options.schemaNamespace, "f");
62
50
  }
63
51
  create(a, b) {
64
52
  return __awaiter(this, void 0, void 0, function* () {
53
+ // Create many records
54
+ if (Array.isArray(a)) {
55
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_bulkInsertTableRecords).call(this, a);
56
+ }
57
+ // Create one record with id as param
65
58
  if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
66
59
  if (a === '')
67
60
  throw new Error("The id can't be empty");
68
61
  return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a, b);
69
62
  }
70
- else if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
63
+ // Create one record with id as property
64
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
71
65
  if (a.id === '')
72
66
  throw new Error("The id can't be empty");
73
67
  return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
74
68
  }
75
- else if ((0, lang_1.isObject)(a)) {
69
+ // Create one record without id
70
+ if ((0, lang_1.isObject)(a)) {
76
71
  return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithoutId).call(this, a);
77
72
  }
78
- else {
79
- throw new Error('Invalid arguments for create method');
80
- }
73
+ throw new Error('Invalid arguments for create method');
81
74
  });
82
75
  }
83
- createMany(objects) {
76
+ // TODO: Add column support: https://github.com/xataio/openapi/issues/139
77
+ read(recordId) {
84
78
  return __awaiter(this, void 0, void 0, function* () {
85
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
86
- const records = objects.map((object) => transformObjectLinks(object));
87
- const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
88
- const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
89
- if (finalObjects.length !== objects.length) {
90
- throw new Error('The server failed to save some records');
79
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
80
+ try {
81
+ const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
82
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), response);
83
+ }
84
+ catch (e) {
85
+ if ((0, lang_1.isObject)(e) && e.status === 404) {
86
+ return null;
87
+ }
88
+ throw e;
91
89
  }
92
- return finalObjects;
93
90
  });
94
91
  }
95
- // TODO: Add column support: https://github.com/xataio/openapi/issues/139
96
- read(recordId) {
92
+ update(a, b) {
97
93
  return __awaiter(this, void 0, void 0, function* () {
98
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
99
- const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
100
- return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
94
+ // Update many records
95
+ if (Array.isArray(a)) {
96
+ if (a.length > 100) {
97
+ // TODO: Implement bulk update when API has support for it
98
+ console.warn('Bulk update operation is not optimized in the Xata API yet, this request might be slow');
99
+ }
100
+ return Promise.all(a.map((object) => this.update(object)));
101
+ }
102
+ // Update one record with id as param
103
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
104
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_updateRecordWithID).call(this, a, b);
105
+ }
106
+ // Update one record with id as property
107
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
108
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_updateRecordWithID).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
109
+ }
110
+ throw new Error('Invalid arguments for update method');
101
111
  });
102
112
  }
103
- update(recordId, object) {
113
+ createOrUpdate(a, b) {
104
114
  return __awaiter(this, void 0, void 0, function* () {
105
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
106
- const record = transformObjectLinks(object);
107
- const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
108
- const item = yield this.read(response.id);
109
- if (!item)
110
- throw new Error('The server failed to save the record');
111
- return item;
115
+ // Create or update many records
116
+ if (Array.isArray(a)) {
117
+ if (a.length > 100) {
118
+ // TODO: Implement bulk update when API has support for it
119
+ console.warn('Bulk update operation is not optimized in the Xata API yet, this request might be slow');
120
+ }
121
+ return Promise.all(a.map((object) => this.createOrUpdate(object)));
122
+ }
123
+ // Create or update one record with id as param
124
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
125
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_upsertRecordWithID).call(this, a, b);
126
+ }
127
+ // Create or update one record with id as property
128
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
129
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_upsertRecordWithID).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
130
+ }
131
+ throw new Error('Invalid arguments for createOrUpdate method');
112
132
  });
113
133
  }
114
- createOrUpdate(recordId, object) {
134
+ delete(recordId) {
115
135
  return __awaiter(this, void 0, void 0, function* () {
116
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
117
- const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
118
- const item = yield this.read(response.id);
119
- if (!item)
120
- throw new Error('The server failed to save the record');
121
- return item;
136
+ // Delete many records
137
+ if (Array.isArray(recordId)) {
138
+ if (recordId.length > 100) {
139
+ // TODO: Implement bulk delete when API has support for it
140
+ console.warn('Bulk delete operation is not optimized in the Xata API yet, this request might be slow');
141
+ }
142
+ yield Promise.all(recordId.map((id) => this.delete(id)));
143
+ return;
144
+ }
145
+ // Delete one record with id as param
146
+ if ((0, lang_1.isString)(recordId)) {
147
+ yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_deleteRecord).call(this, recordId);
148
+ return;
149
+ }
150
+ // Delete one record with id as property
151
+ if ((0, lang_1.isObject)(recordId) && (0, lang_1.isString)(recordId.id)) {
152
+ yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_deleteRecord).call(this, recordId.id);
153
+ return;
154
+ }
155
+ throw new Error('Invalid arguments for delete method');
122
156
  });
123
157
  }
124
- delete(recordId) {
158
+ search(query, options = {}) {
125
159
  return __awaiter(this, void 0, void 0, function* () {
126
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
127
- yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
160
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
161
+ const { records } = yield (0, api_1.searchBranch)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}' }, body: { tables: [__classPrivateFieldGet(this, _RestRepository_table, "f")], query, fuzziness: options.fuzziness } }, fetchProps));
162
+ return records.map((item) => __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), item));
128
163
  });
129
164
  }
130
165
  query(query) {
@@ -133,38 +168,21 @@ class RestRepository extends query_1.Query {
133
168
  const data = query.getQueryOptions();
134
169
  const body = {
135
170
  filter: Object.values((_a = data.filter) !== null && _a !== void 0 ? _a : {}).some(Boolean) ? data.filter : undefined,
136
- sort: (0, filters_1.buildSortFilter)(data.sort),
171
+ sort: data.sort ? (0, sorting_1.buildSortFilter)(data.sort) : undefined,
137
172
  page: data.page,
138
173
  columns: data.columns
139
174
  };
140
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
175
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
141
176
  const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body }, fetchProps));
142
- const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record));
177
+ const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), record));
143
178
  return new pagination_1.Page(query, meta, records);
144
179
  });
145
180
  }
146
181
  }
147
182
  exports.RestRepository = RestRepository;
148
- _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
183
+ _RestRepository_table = new WeakMap(), _RestRepository_links = new WeakMap(), _RestRepository_getFetchProps = new WeakMap(), _RestRepository_schemaNamespace = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_insertRecordWithoutId = function _RestRepository_insertRecordWithoutId(object) {
149
184
  return __awaiter(this, void 0, void 0, function* () {
150
- const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
151
- return {
152
- fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
153
- apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
154
- apiUrl: '',
155
- // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
156
- workspacesApiUrl: (path, params) => {
157
- var _a, _b;
158
- const baseUrl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.databaseURL) !== null && _a !== void 0 ? _a : '';
159
- const hasBranch = (_b = params.dbBranchName) !== null && _b !== void 0 ? _b : params.branch;
160
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branch}` : '');
161
- return baseUrl + newPath;
162
- }
163
- };
164
- });
165
- }, _RestRepository_insertRecordWithoutId = function _RestRepository_insertRecordWithoutId(object) {
166
- return __awaiter(this, void 0, void 0, function* () {
167
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
185
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
168
186
  const record = transformObjectLinks(object);
169
187
  const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
170
188
  workspace: '{workspaceId}',
@@ -179,7 +197,7 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
179
197
  });
180
198
  }, _RestRepository_insertRecordWithId = function _RestRepository_insertRecordWithId(recordId, object) {
181
199
  return __awaiter(this, void 0, void 0, function* () {
182
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
200
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
183
201
  const record = transformObjectLinks(object);
184
202
  const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
185
203
  workspace: '{workspaceId}',
@@ -193,96 +211,74 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
193
211
  }
194
212
  return finalObject;
195
213
  });
196
- };
197
- class RestRespositoryFactory {
198
- createRepository(client, table) {
199
- return new RestRepository(client, table);
200
- }
201
- }
202
- exports.RestRespositoryFactory = RestRespositoryFactory;
203
- class BaseClient {
204
- constructor(options, links = {}) {
205
- _BaseClient_links.set(this, void 0);
206
- _BaseClient_branch.set(this, void 0);
207
- if (!options.databaseURL || !options.apiKey || !options.branch) {
208
- throw new Error('Options databaseURL, apiKey and branch are required');
209
- }
210
- this.options = options;
211
- __classPrivateFieldSet(this, _BaseClient_links, links, "f");
212
- const factory = options.repositoryFactory || new RestRespositoryFactory();
213
- this.db = new Proxy({}, {
214
- get: (_target, prop) => {
215
- if (typeof prop !== 'string')
216
- throw new Error('Invalid table name');
217
- return factory.createRepository(this, prop);
218
- }
219
- });
220
- }
221
- initObject(table, object) {
222
- const result = {};
223
- Object.assign(result, object);
224
- const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
225
- for (const link of tableLinks) {
226
- const [field, linkTable] = link;
227
- const value = result[field];
228
- if (value && (0, lang_1.isObject)(value)) {
229
- result[field] = this.initObject(linkTable, value);
230
- }
214
+ }, _RestRepository_bulkInsertTableRecords = function _RestRepository_bulkInsertTableRecords(objects) {
215
+ return __awaiter(this, void 0, void 0, function* () {
216
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
217
+ const records = objects.map((object) => transformObjectLinks(object));
218
+ const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
219
+ const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
220
+ if (finalObjects.length !== objects.length) {
221
+ throw new Error('The server failed to save some records');
231
222
  }
232
- const db = this.db;
233
- result.read = function () {
234
- return db[table].read(result['id']);
235
- };
236
- result.update = function (data) {
237
- return db[table].update(result['id'], data);
238
- };
239
- result.delete = function () {
240
- return db[table].delete(result['id']);
241
- };
242
- for (const prop of ['read', 'update', 'delete']) {
243
- Object.defineProperty(result, prop, { enumerable: false });
223
+ return finalObjects;
224
+ });
225
+ }, _RestRepository_updateRecordWithID = function _RestRepository_updateRecordWithID(recordId, object) {
226
+ return __awaiter(this, void 0, void 0, function* () {
227
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
228
+ const record = transformObjectLinks(object);
229
+ const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
230
+ const item = yield this.read(response.id);
231
+ if (!item)
232
+ throw new Error('The server failed to save the record');
233
+ return item;
234
+ });
235
+ }, _RestRepository_upsertRecordWithID = function _RestRepository_upsertRecordWithID(recordId, object) {
236
+ return __awaiter(this, void 0, void 0, function* () {
237
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
238
+ const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
239
+ const item = yield this.read(response.id);
240
+ if (!item)
241
+ throw new Error('The server failed to save the record');
242
+ return item;
243
+ });
244
+ }, _RestRepository_deleteRecord = function _RestRepository_deleteRecord(recordId) {
245
+ return __awaiter(this, void 0, void 0, function* () {
246
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
247
+ yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
248
+ });
249
+ }, _RestRepository_initObject = function _RestRepository_initObject(table, object) {
250
+ const result = {};
251
+ Object.assign(result, object);
252
+ const tableLinks = __classPrivateFieldGet(this, _RestRepository_links, "f")[table] || [];
253
+ for (const link of tableLinks) {
254
+ const [field, linkTable] = link;
255
+ const value = result[field];
256
+ if (value && (0, lang_1.isObject)(value)) {
257
+ result[field] = __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, linkTable, value);
244
258
  }
245
- Object.freeze(result);
246
- return result;
247
259
  }
248
- getBranch() {
249
- var e_1, _a;
250
- return __awaiter(this, void 0, void 0, function* () {
251
- if (__classPrivateFieldGet(this, _BaseClient_branch, "f"))
252
- return __classPrivateFieldGet(this, _BaseClient_branch, "f");
253
- const { branch: param } = this.options;
254
- const strategies = Array.isArray(param) ? [...param] : [param];
255
- const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
256
- return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy;
257
- });
258
- try {
259
- for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
260
- const strategy = strategies_1_1.value;
261
- const branch = yield evaluateBranch(strategy);
262
- if (branch) {
263
- __classPrivateFieldSet(this, _BaseClient_branch, branch, "f");
264
- return branch;
265
- }
266
- }
267
- }
268
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
269
- finally {
270
- try {
271
- if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
272
- }
273
- finally { if (e_1) throw e_1.error; }
274
- }
275
- throw new Error('Unable to resolve branch value');
276
- });
260
+ const db = __classPrivateFieldGet(this, _RestRepository_schemaNamespace, "f");
261
+ result.read = function () {
262
+ return db[table].read(result['id']);
263
+ };
264
+ result.update = function (data) {
265
+ return db[table].update(result['id'], data);
266
+ };
267
+ result.delete = function () {
268
+ return db[table].delete(result['id']);
269
+ };
270
+ for (const prop of ['read', 'update', 'delete']) {
271
+ Object.defineProperty(result, prop, { enumerable: false });
277
272
  }
278
- }
279
- exports.BaseClient = BaseClient;
280
- _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
281
- const isBranchStrategyBuilder = (strategy) => {
282
- return typeof strategy === 'function';
273
+ Object.freeze(result);
274
+ return result;
283
275
  };
284
276
  const transformObjectLinks = (object) => {
285
277
  return Object.entries(object).reduce((acc, [key, value]) => {
278
+ // Ignore internal properties
279
+ if (key === 'xata')
280
+ return acc;
281
+ // Transform links to identifier
286
282
  return Object.assign(Object.assign({}, acc), { [key]: (0, record_1.isIdentifiable)(value) ? value.id : value });
287
283
  }, {});
288
284
  };
@@ -4,7 +4,7 @@ export declare type SelectableColumn<O, RecursivePath extends any[] = []> = '*'
4
4
  export declare type SelectedPick<O extends XataRecord, Key extends SelectableColumn<O>[]> = XataRecord & UnionToIntersection<Values<{
5
5
  [K in Key[number]]: NestedValueAtColumn<O, K> & XataRecord;
6
6
  }>>;
7
- export declare type ValueAtColumn<O extends XataRecord, P extends SelectableColumn<O>> = P extends '*' ? Values<O> : P extends 'id' ? string : P extends keyof O ? O[P] : P extends `${infer K}.${infer V}` ? K extends keyof O ? Values<O[K] extends XataRecord ? (V extends SelectableColumn<O[K]> ? {
7
+ export declare type ValueAtColumn<O, P extends SelectableColumn<O>> = P extends '*' ? Values<O> : P extends 'id' ? string : P extends keyof O ? O[P] : P extends `${infer K}.${infer V}` ? K extends keyof O ? Values<O[K] extends XataRecord ? (V extends SelectableColumn<O[K]> ? {
8
8
  V: ValueAtColumn<O[K], V>;
9
9
  } : never) : O[K]> : never : never;
10
10
  declare type MAX_RECURSION = 5;
@@ -15,10 +15,11 @@ declare type NestedColumns<O, RecursivePath extends any[]> = RecursivePath['leng
15
15
  }>, never>;
16
16
  declare type DataProps<O> = Exclude<StringKeys<O>, StringKeys<XataRecord>>;
17
17
  declare type NestedValueAtColumn<O, Key extends SelectableColumn<O>> = Key extends `${infer N}.${infer M}` ? N extends DataProps<O> ? {
18
- [K in N]: M extends SelectableColumn<NonNullable<O[K]>> ? NestedValueAtColumn<NonNullable<O[K]>, M> & XataRecord : unknown;
18
+ [K in N]: M extends SelectableColumn<NonNullable<O[K]>> ? NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], NestedValueAtColumn<NonNullable<O[K]>, M> & XataRecord> : ForwardNullable<O[K], NestedValueAtColumn<NonNullable<O[K]>, M>> : unknown;
19
19
  } : unknown : Key extends DataProps<O> ? {
20
- [K in Key]: NonNullable<O[K]> extends XataRecord ? SelectedPick<NonNullable<O[K]>, ['*']> : O[K];
20
+ [K in Key]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], SelectedPick<NonNullable<O[K]>, ['*']>> : O[K];
21
21
  } : Key extends '*' ? {
22
- [K in keyof NonNullable<O>]: NonNullable<NonNullable<O>[K]> extends XataRecord ? NonNullable<O>[K] extends XataRecord ? Link<NonNullable<O>[K]> : Link<NonNullable<NonNullable<O>[K]>> | null : NonNullable<O>[K];
22
+ [K in StringKeys<O>]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], Link<NonNullable<O[K]>>> : O[K];
23
23
  } : unknown;
24
+ declare type ForwardNullable<T, R> = T extends NonNullable<T> ? R : R | null;
24
25
  export {};