@xata.io/client 0.0.0-beta.09892c4 → 0.0.0-beta.09bfef8

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 (41) hide show
  1. package/.eslintrc.cjs +13 -0
  2. package/CHANGELOG.md +27 -0
  3. package/dist/api/client.d.ts +1 -1
  4. package/dist/api/client.js +11 -9
  5. package/dist/api/fetcher.d.ts +15 -0
  6. package/dist/api/fetcher.js +23 -22
  7. package/dist/api/providers.js +3 -2
  8. package/dist/api/responses.d.ts +6 -0
  9. package/dist/schema/config.d.ts +4 -0
  10. package/dist/schema/config.js +83 -0
  11. package/dist/schema/filters.d.ts +93 -17
  12. package/dist/schema/filters.js +0 -22
  13. package/dist/schema/filters.spec.d.ts +1 -0
  14. package/dist/schema/filters.spec.js +175 -0
  15. package/dist/schema/index.d.ts +1 -0
  16. package/dist/schema/index.js +4 -1
  17. package/dist/schema/operators.d.ts +17 -27
  18. package/dist/schema/operators.js +1 -14
  19. package/dist/schema/pagination.d.ts +13 -13
  20. package/dist/schema/pagination.js +0 -1
  21. package/dist/schema/query.d.ts +39 -50
  22. package/dist/schema/query.js +25 -37
  23. package/dist/schema/record.d.ts +25 -3
  24. package/dist/schema/record.js +11 -0
  25. package/dist/schema/repository.d.ts +79 -35
  26. package/dist/schema/repository.js +208 -114
  27. package/dist/schema/selection.d.ts +24 -11
  28. package/dist/schema/selection.spec.d.ts +1 -0
  29. package/dist/schema/selection.spec.js +203 -0
  30. package/dist/schema/sorting.d.ts +17 -0
  31. package/dist/schema/sorting.js +28 -0
  32. package/dist/schema/sorting.spec.d.ts +1 -0
  33. package/dist/schema/sorting.spec.js +9 -0
  34. package/dist/util/environment.d.ts +5 -0
  35. package/dist/util/environment.js +68 -0
  36. package/dist/util/fetch.d.ts +2 -0
  37. package/dist/util/fetch.js +13 -0
  38. package/dist/util/lang.d.ts +3 -0
  39. package/dist/util/lang.js +13 -1
  40. package/dist/util/types.d.ts +22 -1
  41. package/package.json +2 -2
@@ -1,77 +1,121 @@
1
1
  import { FetchImpl } from '../api/fetcher';
2
2
  import { Page } from './pagination';
3
- import { Query, QueryOptions } from './query';
4
- import { BaseData, XataRecord } from './record';
5
- import { Select, SelectableColumn } from './selection';
3
+ import { Query } from './query';
4
+ import { BaseData, EditableData, Identifiable, XataRecord } from './record';
5
+ import { SelectedPick } from './selection';
6
6
  export declare type Links = Record<string, Array<string[]>>;
7
7
  /**
8
8
  * Common interface for performing operations on a table.
9
9
  */
10
- export declare abstract class Repository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record> {
11
- abstract create(object: Data): Promise<Record>;
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, ['*']>>;
12
+ /**
13
+ * Creates a single record in the table with a unique id.
14
+ * @param id The unique id.
15
+ * @param object Object containing the column names with their values to be stored in the table.
16
+ * @returns The full persisted record.
17
+ */
18
+ abstract create(id: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
12
19
  /**
13
20
  * Creates multiple records in the table.
14
21
  * @param objects Array of objects with the column names and the values to be stored in the table.
15
22
  * @returns Array of the persisted records.
16
23
  */
17
- abstract createMany(objects: Data[]): Promise<Record[]>;
24
+ abstract create(objects: Array<EditableData<Data> & Partial<Identifiable>>): Promise<SelectedPick<Record, ['*']>[]>;
18
25
  /**
19
26
  * Queries a single record from the table given its unique id.
20
27
  * @param id The unique id.
21
28
  * @returns The persisted record for the given id or null if the record could not be found.
22
29
  */
23
- abstract read(id: string): Promise<Record | null>;
30
+ abstract read(id: string): Promise<SelectedPick<Record, ['*']> | null>;
24
31
  /**
25
- * Insert a single record with a unique id.
26
- * @param id The unique id.
27
- * @param object Object containing the column names with their values to be stored in the table.
32
+ * Partially update a single record.
33
+ * @param object An object with its id and the columns to be updated.
28
34
  * @returns The full persisted record.
29
35
  */
30
- abstract insert(id: string, object: Data): Promise<Record>;
36
+ abstract update(object: Partial<EditableData<Data>> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
31
37
  /**
32
38
  * Partially update a single record given its unique id.
33
39
  * @param id The unique id.
34
- * @param object The column names and their values that have to be updatd.
40
+ * @param object The column names and their values that have to be updated.
35
41
  * @returns The full persisted record.
36
42
  */
37
- abstract update(id: string, object: Partial<Data>): Promise<Record>;
43
+ abstract update(id: string, object: Partial<EditableData<Data>>): Promise<SelectedPick<Record, ['*']>>;
38
44
  /**
39
- * Updates or inserts a single record. If a record exists with the given id,
45
+ * Partially updates multiple records.
46
+ * @param objects An array of objects with their ids and columns to be updated.
47
+ * @returns Array of the persisted records.
48
+ */
49
+ abstract update(objects: Array<Partial<EditableData<Data>> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
50
+ /**
51
+ * Creates or updates a single record. If a record exists with the given id,
52
+ * it will be update, otherwise a new record will be created.
53
+ * @param object Object containing the column names with their values to be persisted in the table.
54
+ * @returns The full persisted record.
55
+ */
56
+ abstract createOrUpdate(object: EditableData<Data> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
57
+ /**
58
+ * Creates or updates a single record. If a record exists with the given id,
40
59
  * it will be update, otherwise a new record will be created.
41
60
  * @param id A unique id.
42
61
  * @param object The column names and the values to be persisted.
43
62
  * @returns The full persisted record.
44
63
  */
45
- abstract updateOrInsert(id: string, object: Data): Promise<Record>;
64
+ abstract createOrUpdate(id: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
65
+ /**
66
+ * Creates or updates a single record. If a record exists with the given id,
67
+ * it will be update, otherwise a new record will be created.
68
+ * @param objects Array of objects with the column names and the values to be stored in the table.
69
+ * @returns Array of the persisted records.
70
+ */
71
+ abstract createOrUpdate(objects: Array<EditableData<Data> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
46
72
  /**
47
73
  * Deletes a record given its unique id.
48
74
  * @param id The unique id.
49
75
  * @throws If the record could not be found or there was an error while performing the deletion.
50
76
  */
51
- abstract delete(id: string): void;
52
- abstract query<Result extends XataRecord, Options extends QueryOptions<Record>>(query: Query<Record, Result>, options: Options): Promise<Page<Record, typeof options extends {
53
- columns: SelectableColumn<Data>[];
54
- } ? Select<Data, typeof options['columns'][number]> : Result>>;
77
+ abstract delete(id: string): Promise<void>;
78
+ /**
79
+ * Deletes a record given its unique id.
80
+ * @param id An object with a unique id.
81
+ * @throws If the record could not be found or there was an error while performing the deletion.
82
+ */
83
+ abstract delete(id: Identifiable): Promise<void>;
84
+ /**
85
+ * Deletes a record given a list of unique ids.
86
+ * @param ids The array of unique ids.
87
+ * @throws If the record could not be found or there was an error while performing the deletion.
88
+ */
89
+ abstract delete(ids: string[]): Promise<void>;
90
+ /**
91
+ * Deletes a record given a list of unique ids.
92
+ * @param ids An array of objects with unique ids.
93
+ * @throws If the record could not be found or there was an error while performing the deletion.
94
+ */
95
+ abstract delete(ids: Identifiable[]): Promise<void>;
96
+ abstract query<Result extends XataRecord>(query: Query<Record, Result>): Promise<Page<Record, Result>>;
55
97
  }
56
- export declare class RestRepository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Repository<Data, Record> {
98
+ export declare class RestRepository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record, SelectedPick<Record, ['*']>> {
57
99
  #private;
58
100
  constructor(client: BaseClient<any>, table: string);
59
- create(object: Data): Promise<Record>;
60
- createMany(objects: Data[]): Promise<Record[]>;
61
- read(recordId: string): Promise<Record | null>;
62
- update(recordId: string, object: Partial<Data>): Promise<Record>;
63
- insert(recordId: string, object: Data): Promise<Record>;
64
- updateOrInsert(recordId: string, object: Data): Promise<Record>;
65
- delete(recordId: string): Promise<void>;
66
- query<Result extends XataRecord, Options extends QueryOptions<Record>>(query: Query<Record, Result>, options?: Options): Promise<Page<Record, typeof options extends {
67
- columns: SelectableColumn<Data>[];
68
- } ? Select<Data, typeof options['columns'][number]> : Result>>;
101
+ create(object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
102
+ create(recordId: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
103
+ create(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
104
+ read(recordId: string): Promise<SelectedPick<Record, ['*']> | null>;
105
+ update(object: Partial<EditableData<Data>> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
106
+ update(recordId: string, object: Partial<EditableData<Data>>): Promise<SelectedPick<Record, ['*']>>;
107
+ update(objects: Array<Partial<EditableData<Data>> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
108
+ createOrUpdate(object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
109
+ createOrUpdate(recordId: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
110
+ createOrUpdate(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
111
+ delete(recordId: string | Identifiable | Array<string | Identifiable>): Promise<void>;
112
+ query<Result extends XataRecord>(query: Query<Record, Result>): Promise<Page<Record, Result>>;
69
113
  }
70
114
  interface RepositoryFactory {
71
- createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data>;
115
+ createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data & XataRecord>;
72
116
  }
73
117
  export declare class RestRespositoryFactory implements RepositoryFactory {
74
- createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data>;
118
+ createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data & XataRecord>;
75
119
  }
76
120
  declare type BranchStrategyValue = string | undefined | null;
77
121
  declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
@@ -86,18 +130,18 @@ export declare type XataClientOptions = {
86
130
  */
87
131
  fetch?: FetchImpl;
88
132
  databaseURL?: string;
89
- branch: BranchStrategyOption;
133
+ branch?: BranchStrategyOption;
90
134
  /**
91
135
  * API key to be used. You can create one in your account settings at https://app.xata.io/settings.
92
136
  */
93
- apiKey: string;
137
+ apiKey?: string;
94
138
  repositoryFactory?: RepositoryFactory;
95
139
  };
96
140
  export declare class BaseClient<D extends Record<string, Repository<any>> = Record<string, Repository<any>>> {
97
141
  #private;
98
142
  options: XataClientOptions;
99
143
  db: D;
100
- constructor(options: XataClientOptions, links?: Links);
144
+ constructor(options?: XataClientOptions, links?: Links);
101
145
  initObject<T>(table: string, object: object): T;
102
146
  getBranch(): Promise<string>;
103
147
  }
@@ -26,22 +26,25 @@ var __asyncValues = (this && this.__asyncValues) || function (o) {
26
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
27
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
28
  };
29
- var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _BaseClient_links, _BaseClient_branch;
29
+ var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _RestRepository_bulkInsertTableRecords, _RestRepository_updateRecordWithID, _RestRepository_upsertRecordWithID, _RestRepository_deleteRecord, _BaseClient_links, _BaseClient_branch;
30
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
31
  exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
32
32
  const api_1 = require("../api");
33
- const filters_1 = require("./filters");
33
+ const fetch_1 = require("../util/fetch");
34
+ const lang_1 = require("../util/lang");
35
+ const config_1 = require("./config");
34
36
  const pagination_1 = require("./pagination");
35
37
  const query_1 = require("./query");
38
+ const record_1 = require("./record");
39
+ const sorting_1 = require("./sorting");
36
40
  /**
37
41
  * Common interface for performing operations on a table.
38
42
  */
39
43
  class Repository extends query_1.Query {
40
44
  }
41
45
  exports.Repository = Repository;
42
- class RestRepository extends Repository {
46
+ class RestRepository extends query_1.Query {
43
47
  constructor(client, table) {
44
- var _a;
45
48
  super(null, table, {});
46
49
  _RestRepository_instances.add(this);
47
50
  _RestRepository_client.set(this, void 0);
@@ -49,118 +52,144 @@ class RestRepository extends Repository {
49
52
  _RestRepository_table.set(this, void 0);
50
53
  __classPrivateFieldSet(this, _RestRepository_client, client, "f");
51
54
  __classPrivateFieldSet(this, _RestRepository_table, table, "f");
52
- // TODO: Remove when integrating with API client
53
- const globalFetch = typeof fetch !== 'undefined' ? fetch : undefined;
54
- const fetchImpl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch) !== null && _a !== void 0 ? _a : globalFetch;
55
- if (!fetchImpl) {
56
- /** @todo add a link after docs exist */
57
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
58
- }
59
- __classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f");
55
+ __classPrivateFieldSet(this, _RestRepository_fetch, (0, fetch_1.getFetchImplementation)(__classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch), "f");
60
56
  }
61
- create(object) {
57
+ create(a, b) {
62
58
  return __awaiter(this, void 0, void 0, function* () {
63
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
64
- const record = transformObjectLinks(object);
65
- const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
66
- workspace: '{workspaceId}',
67
- dbBranchName: '{dbBranch}',
68
- tableName: __classPrivateFieldGet(this, _RestRepository_table, "f")
69
- }, body: record }, fetchProps));
70
- const finalObject = yield this.read(response.id);
71
- if (!finalObject) {
72
- throw new Error('The server failed to save the record');
59
+ // Create many records
60
+ if (Array.isArray(a)) {
61
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_bulkInsertTableRecords).call(this, a);
73
62
  }
74
- return finalObject;
75
- });
76
- }
77
- createMany(objects) {
78
- return __awaiter(this, void 0, void 0, function* () {
79
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
80
- const records = objects.map((object) => transformObjectLinks(object));
81
- const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
82
- const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
83
- if (finalObjects.length !== objects.length) {
84
- throw new Error('The server failed to save some records');
63
+ // Create one record with id as param
64
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
65
+ if (a === '')
66
+ throw new Error("The id can't be empty");
67
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a, b);
85
68
  }
86
- return finalObjects;
69
+ // Create one record with id as property
70
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
71
+ if (a.id === '')
72
+ throw new Error("The id can't be empty");
73
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
74
+ }
75
+ // Create one record without id
76
+ if ((0, lang_1.isObject)(a)) {
77
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithoutId).call(this, a);
78
+ }
79
+ throw new Error('Invalid arguments for create method');
87
80
  });
88
81
  }
82
+ // TODO: Add column support: https://github.com/xataio/openapi/issues/139
89
83
  read(recordId) {
90
84
  return __awaiter(this, void 0, void 0, function* () {
91
85
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
92
- const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
93
- return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
94
- });
95
- }
96
- update(recordId, object) {
97
- 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.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
100
- const item = yield this.read(response.id);
101
- if (!item)
102
- throw new Error('The server failed to save the record');
103
- return item;
86
+ try {
87
+ const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
88
+ return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
89
+ }
90
+ catch (e) {
91
+ if ((0, lang_1.isObject)(e) && e.status === 404) {
92
+ return null;
93
+ }
94
+ throw e;
95
+ }
104
96
  });
105
97
  }
106
- insert(recordId, object) {
98
+ update(a, b) {
107
99
  return __awaiter(this, void 0, void 0, function* () {
108
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
109
- const record = transformObjectLinks(object);
110
- const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
111
- workspace: '{workspaceId}',
112
- dbBranchName: '{dbBranch}',
113
- tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
114
- recordId
115
- }, body: record }, fetchProps));
116
- const finalObject = yield this.read(response.id);
117
- if (!finalObject) {
118
- throw new Error('The server failed to save the record');
100
+ // Update many records
101
+ if (Array.isArray(a)) {
102
+ if (a.length > 100) {
103
+ // TODO: Implement bulk update when API has support for it
104
+ console.warn('Bulk update operation is not optimized in the Xata API yet, this request might be slow');
105
+ }
106
+ return Promise.all(a.map((object) => this.update(object)));
107
+ }
108
+ // Update one record with id as param
109
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
110
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_updateRecordWithID).call(this, a, b);
111
+ }
112
+ // Update one record with id as property
113
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
114
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_updateRecordWithID).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
119
115
  }
120
- return finalObject;
116
+ throw new Error('Invalid arguments for update method');
121
117
  });
122
118
  }
123
- updateOrInsert(recordId, object) {
119
+ createOrUpdate(a, b) {
124
120
  return __awaiter(this, void 0, void 0, function* () {
125
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
126
- const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
127
- const item = yield this.read(response.id);
128
- if (!item)
129
- throw new Error('The server failed to save the record');
130
- return item;
121
+ // Create or update many records
122
+ if (Array.isArray(a)) {
123
+ if (a.length > 100) {
124
+ // TODO: Implement bulk update when API has support for it
125
+ console.warn('Bulk update operation is not optimized in the Xata API yet, this request might be slow');
126
+ }
127
+ return Promise.all(a.map((object) => this.createOrUpdate(object)));
128
+ }
129
+ // Create or update one record with id as param
130
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
131
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_upsertRecordWithID).call(this, a, b);
132
+ }
133
+ // Create or update one record with id as property
134
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
135
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_upsertRecordWithID).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
136
+ }
137
+ throw new Error('Invalid arguments for createOrUpdate method');
131
138
  });
132
139
  }
133
140
  delete(recordId) {
134
141
  return __awaiter(this, void 0, void 0, function* () {
135
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
136
- yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
142
+ // Delete many records
143
+ if (Array.isArray(recordId)) {
144
+ if (recordId.length > 100) {
145
+ // TODO: Implement bulk delete when API has support for it
146
+ console.warn('Bulk delete operation is not optimized in the Xata API yet, this request might be slow');
147
+ }
148
+ yield Promise.all(recordId.map((id) => this.delete(id)));
149
+ return;
150
+ }
151
+ // Delete one record with id as param
152
+ if ((0, lang_1.isString)(recordId)) {
153
+ yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_deleteRecord).call(this, recordId);
154
+ return;
155
+ }
156
+ // Delete one record with id as property
157
+ if ((0, lang_1.isObject)(recordId) && (0, lang_1.isString)(recordId.id)) {
158
+ yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_deleteRecord).call(this, recordId.id);
159
+ return;
160
+ }
161
+ throw new Error('Invalid arguments for delete method');
137
162
  });
138
163
  }
139
- query(query, options = {}) {
140
- var _a, _b, _c;
164
+ query(query) {
165
+ var _a;
141
166
  return __awaiter(this, void 0, void 0, function* () {
142
167
  const data = query.getQueryOptions();
143
168
  const body = {
144
- filter: Object.values(data.filter).some(Boolean) ? data.filter : undefined,
145
- sort: (_a = (0, filters_1.buildSortFilter)(options === null || options === void 0 ? void 0 : options.sort)) !== null && _a !== void 0 ? _a : data.sort,
146
- page: (_b = options === null || options === void 0 ? void 0 : options.page) !== null && _b !== void 0 ? _b : data.page,
147
- columns: (_c = options === null || options === void 0 ? void 0 : options.columns) !== null && _c !== void 0 ? _c : data.columns
169
+ filter: Object.values((_a = data.filter) !== null && _a !== void 0 ? _a : {}).some(Boolean) ? data.filter : undefined,
170
+ sort: data.sort ? (0, sorting_1.buildSortFilter)(data.sort) : undefined,
171
+ page: data.page,
172
+ columns: data.columns
148
173
  };
149
174
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
150
175
  const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body }, fetchProps));
151
176
  const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record));
152
- // TODO: We should properly type this any
153
177
  return new pagination_1.Page(query, meta, records);
154
178
  });
155
179
  }
156
180
  }
157
181
  exports.RestRepository = RestRepository;
158
182
  _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
183
+ var _a;
159
184
  return __awaiter(this, void 0, void 0, function* () {
160
185
  const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
186
+ const apiKey = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey) !== null && _a !== void 0 ? _a : (0, config_1.getAPIKey)();
187
+ if (!apiKey) {
188
+ throw new Error('Could not resolve a valid apiKey');
189
+ }
161
190
  return {
162
191
  fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
163
- apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
192
+ apiKey,
164
193
  apiUrl: '',
165
194
  // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
166
195
  workspacesApiUrl: (path, params) => {
@@ -172,6 +201,72 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
172
201
  }
173
202
  };
174
203
  });
204
+ }, _RestRepository_insertRecordWithoutId = function _RestRepository_insertRecordWithoutId(object) {
205
+ return __awaiter(this, void 0, void 0, function* () {
206
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
207
+ const record = transformObjectLinks(object);
208
+ const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
209
+ workspace: '{workspaceId}',
210
+ dbBranchName: '{dbBranch}',
211
+ tableName: __classPrivateFieldGet(this, _RestRepository_table, "f")
212
+ }, body: record }, fetchProps));
213
+ const finalObject = yield this.read(response.id);
214
+ if (!finalObject) {
215
+ throw new Error('The server failed to save the record');
216
+ }
217
+ return finalObject;
218
+ });
219
+ }, _RestRepository_insertRecordWithId = function _RestRepository_insertRecordWithId(recordId, object) {
220
+ return __awaiter(this, void 0, void 0, function* () {
221
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
222
+ const record = transformObjectLinks(object);
223
+ const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
224
+ workspace: '{workspaceId}',
225
+ dbBranchName: '{dbBranch}',
226
+ tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
227
+ recordId
228
+ }, body: record, queryParams: { createOnly: true } }, fetchProps));
229
+ const finalObject = yield this.read(response.id);
230
+ if (!finalObject) {
231
+ throw new Error('The server failed to save the record');
232
+ }
233
+ return finalObject;
234
+ });
235
+ }, _RestRepository_bulkInsertTableRecords = function _RestRepository_bulkInsertTableRecords(objects) {
236
+ return __awaiter(this, void 0, void 0, function* () {
237
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
238
+ const records = objects.map((object) => transformObjectLinks(object));
239
+ const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
240
+ const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
241
+ if (finalObjects.length !== objects.length) {
242
+ throw new Error('The server failed to save some records');
243
+ }
244
+ return finalObjects;
245
+ });
246
+ }, _RestRepository_updateRecordWithID = function _RestRepository_updateRecordWithID(recordId, object) {
247
+ return __awaiter(this, void 0, void 0, function* () {
248
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
249
+ const record = transformObjectLinks(object);
250
+ const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
251
+ const item = yield this.read(response.id);
252
+ if (!item)
253
+ throw new Error('The server failed to save the record');
254
+ return item;
255
+ });
256
+ }, _RestRepository_upsertRecordWithID = function _RestRepository_upsertRecordWithID(recordId, object) {
257
+ return __awaiter(this, void 0, void 0, function* () {
258
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
259
+ const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
260
+ const item = yield this.read(response.id);
261
+ if (!item)
262
+ throw new Error('The server failed to save the record');
263
+ return item;
264
+ });
265
+ }, _RestRepository_deleteRecord = function _RestRepository_deleteRecord(recordId) {
266
+ return __awaiter(this, void 0, void 0, function* () {
267
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
268
+ yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
269
+ });
175
270
  };
176
271
  class RestRespositoryFactory {
177
272
  createRepository(client, table) {
@@ -179,16 +274,31 @@ class RestRespositoryFactory {
179
274
  }
180
275
  }
181
276
  exports.RestRespositoryFactory = RestRespositoryFactory;
277
+ function resolveXataClientOptions(options) {
278
+ const databaseURL = (options === null || options === void 0 ? void 0 : options.databaseURL) || (0, config_1.getDatabaseUrl)() || '';
279
+ const apiKey = (options === null || options === void 0 ? void 0 : options.apiKey) || (0, config_1.getAPIKey)() || '';
280
+ const branch = (options === null || options === void 0 ? void 0 : options.branch) ||
281
+ (() => (0, config_1.getBranch)({
282
+ apiKey,
283
+ apiUrl: databaseURL,
284
+ fetchImpl: (0, fetch_1.getFetchImplementation)(options === null || options === void 0 ? void 0 : options.fetch)
285
+ }));
286
+ if (!databaseURL || !apiKey) {
287
+ throw new Error('Options databaseURL and apiKey are required');
288
+ }
289
+ return Object.assign(Object.assign({}, options), { databaseURL,
290
+ apiKey,
291
+ branch });
292
+ }
182
293
  class BaseClient {
183
- constructor(options, links = {}) {
294
+ constructor(options = {}, links = {}) {
184
295
  _BaseClient_links.set(this, void 0);
185
296
  _BaseClient_branch.set(this, void 0);
186
- if (!options.databaseURL || !options.apiKey || !options.branch) {
187
- throw new Error('Options databaseURL, apiKey and branch are required');
188
- }
189
- this.options = options;
297
+ this.options = resolveXataClientOptions(options);
298
+ // Make this property not enumerable so it doesn't show up in console.dir, etc.
299
+ Object.defineProperty(this.options, 'apiKey', { enumerable: false });
190
300
  __classPrivateFieldSet(this, _BaseClient_links, links, "f");
191
- const factory = options.repositoryFactory || new RestRespositoryFactory();
301
+ const factory = this.options.repositoryFactory || new RestRespositoryFactory();
192
302
  this.db = new Proxy({}, {
193
303
  get: (_target, prop) => {
194
304
  if (typeof prop !== 'string')
@@ -198,43 +308,31 @@ class BaseClient {
198
308
  });
199
309
  }
200
310
  initObject(table, object) {
201
- const o = {};
202
- Object.assign(o, object);
311
+ const result = {};
312
+ Object.assign(result, object);
203
313
  const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
204
314
  for (const link of tableLinks) {
205
315
  const [field, linkTable] = link;
206
- const value = o[field];
207
- if (value && typeof value === 'object') {
208
- const { id } = value;
209
- if (Object.keys(value).find((col) => col === 'id')) {
210
- o[field] = this.initObject(linkTable, value);
211
- }
212
- else if (id) {
213
- o[field] = {
214
- id,
215
- get: () => {
216
- this.db[linkTable].read(id);
217
- }
218
- };
219
- }
316
+ const value = result[field];
317
+ if (value && (0, lang_1.isObject)(value)) {
318
+ result[field] = this.initObject(linkTable, value);
220
319
  }
221
320
  }
222
321
  const db = this.db;
223
- o.read = function () {
224
- return db[table].read(o['id']);
322
+ result.read = function () {
323
+ return db[table].read(result['id']);
225
324
  };
226
- o.update = function (data) {
227
- return db[table].update(o['id'], data);
325
+ result.update = function (data) {
326
+ return db[table].update(result['id'], data);
228
327
  };
229
- o.delete = function () {
230
- return db[table].delete(o['id']);
328
+ result.delete = function () {
329
+ return db[table].delete(result['id']);
231
330
  };
232
331
  for (const prop of ['read', 'update', 'delete']) {
233
- Object.defineProperty(o, prop, { enumerable: false });
332
+ Object.defineProperty(result, prop, { enumerable: false });
234
333
  }
235
- // TODO: links and rev links
236
- Object.freeze(o);
237
- return o;
334
+ Object.freeze(result);
335
+ return result;
238
336
  }
239
337
  getBranch() {
240
338
  var e_1, _a;
@@ -272,12 +370,8 @@ _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
272
370
  const isBranchStrategyBuilder = (strategy) => {
273
371
  return typeof strategy === 'function';
274
372
  };
275
- // TODO: We can find a better implementation for links
276
373
  const transformObjectLinks = (object) => {
277
374
  return Object.entries(object).reduce((acc, [key, value]) => {
278
- if (value && typeof value === 'object' && typeof value.id === 'string') {
279
- return Object.assign(Object.assign({}, acc), { [key]: value.id });
280
- }
281
- return Object.assign(Object.assign({}, acc), { [key]: value });
375
+ return Object.assign(Object.assign({}, acc), { [key]: (0, record_1.isIdentifiable)(value) ? value.id : value });
282
376
  }, {});
283
377
  };