@xata.io/client 0.0.0-beta.b394112 → 0.0.0-beta.b8f7b5b

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 (53) hide show
  1. package/.eslintrc.cjs +13 -0
  2. package/CHANGELOG.md +57 -0
  3. package/dist/api/client.d.ts +1 -1
  4. package/dist/api/client.js +32 -17
  5. package/dist/api/components.d.ts +7 -6
  6. package/dist/api/components.js +7 -6
  7. package/dist/api/fetcher.d.ts +15 -0
  8. package/dist/api/fetcher.js +23 -22
  9. package/dist/api/providers.js +3 -2
  10. package/dist/api/responses.d.ts +6 -0
  11. package/dist/client.d.ts +39 -0
  12. package/dist/client.js +124 -0
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.js +3 -0
  15. package/dist/namespace.d.ts +7 -0
  16. package/dist/namespace.js +6 -0
  17. package/dist/schema/filters.d.ts +93 -17
  18. package/dist/schema/filters.js +0 -22
  19. package/dist/schema/filters.spec.d.ts +1 -0
  20. package/dist/schema/filters.spec.js +177 -0
  21. package/dist/schema/index.d.ts +17 -2
  22. package/dist/schema/index.js +29 -6
  23. package/dist/schema/operators.d.ts +26 -24
  24. package/dist/schema/operators.js +13 -11
  25. package/dist/schema/pagination.d.ts +13 -13
  26. package/dist/schema/pagination.js +0 -1
  27. package/dist/schema/query.d.ts +39 -50
  28. package/dist/schema/query.js +25 -37
  29. package/dist/schema/record.d.ts +25 -3
  30. package/dist/schema/record.js +11 -0
  31. package/dist/schema/repository.d.ts +94 -64
  32. package/dist/schema/repository.js +205 -204
  33. package/dist/schema/selection.d.ts +24 -11
  34. package/dist/schema/selection.spec.d.ts +1 -0
  35. package/dist/schema/selection.spec.js +204 -0
  36. package/dist/schema/sorting.d.ts +17 -0
  37. package/dist/schema/sorting.js +28 -0
  38. package/dist/schema/sorting.spec.d.ts +1 -0
  39. package/dist/schema/sorting.spec.js +11 -0
  40. package/dist/search/index.d.ts +20 -0
  41. package/dist/search/index.js +30 -0
  42. package/dist/util/branches.d.ts +5 -0
  43. package/dist/util/branches.js +7 -0
  44. package/dist/util/config.d.ts +11 -0
  45. package/dist/util/config.js +121 -0
  46. package/dist/util/environment.d.ts +5 -0
  47. package/dist/util/environment.js +68 -0
  48. package/dist/util/fetch.d.ts +2 -0
  49. package/dist/util/fetch.js +13 -0
  50. package/dist/util/lang.d.ts +3 -0
  51. package/dist/util/lang.js +13 -1
  52. package/dist/util/types.d.ts +23 -1
  53. package/package.json +5 -2
@@ -19,265 +19,266 @@ 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, _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
- const filters_1 = require("./filters");
26
+ const lang_1 = require("../util/lang");
34
27
  const pagination_1 = require("./pagination");
35
28
  const query_1 = require("./query");
29
+ const record_1 = require("./record");
30
+ const sorting_1 = require("./sorting");
36
31
  /**
37
32
  * Common interface for performing operations on a table.
38
33
  */
39
34
  class Repository extends query_1.Query {
40
35
  }
41
36
  exports.Repository = Repository;
42
- class RestRepository extends Repository {
43
- constructor(client, table) {
37
+ class RestRepository extends query_1.Query {
38
+ constructor(options) {
44
39
  var _a;
45
- super(null, table, {});
40
+ super(null, options.table, {});
46
41
  _RestRepository_instances.add(this);
47
- _RestRepository_client.set(this, void 0);
48
- _RestRepository_fetch.set(this, void 0);
49
42
  _RestRepository_table.set(this, void 0);
50
- __classPrivateFieldSet(this, _RestRepository_client, client, "f");
51
- __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");
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");
60
50
  }
61
- create(object) {
51
+ create(a, b) {
62
52
  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');
53
+ // Create many records
54
+ if (Array.isArray(a)) {
55
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_bulkInsertTableRecords).call(this, a);
73
56
  }
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');
57
+ // Create one record with id as param
58
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
59
+ if (a === '')
60
+ throw new Error("The id can't be empty");
61
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a, b);
62
+ }
63
+ // Create one record with id as property
64
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
65
+ if (a.id === '')
66
+ throw new Error("The id can't be empty");
67
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
68
+ }
69
+ // Create one record without id
70
+ if ((0, lang_1.isObject)(a)) {
71
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithoutId).call(this, a);
85
72
  }
86
- return finalObjects;
73
+ throw new Error('Invalid arguments for create method');
87
74
  });
88
75
  }
76
+ // TODO: Add column support: https://github.com/xataio/openapi/issues/139
89
77
  read(recordId) {
90
78
  return __awaiter(this, void 0, void 0, function* () {
91
- 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);
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;
89
+ }
94
90
  });
95
91
  }
96
- update(recordId, object) {
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.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;
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');
104
111
  });
105
112
  }
106
- insert(recordId, object) {
113
+ createOrUpdate(a, b) {
107
114
  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');
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 }));
119
130
  }
120
- return finalObject;
131
+ throw new Error('Invalid arguments for createOrUpdate method');
121
132
  });
122
133
  }
123
- updateOrInsert(recordId, object) {
134
+ delete(recordId) {
124
135
  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;
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');
131
156
  });
132
157
  }
133
- delete(recordId) {
158
+ search(query, options = {}) {
134
159
  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));
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));
137
163
  });
138
164
  }
139
- query(query, options = {}) {
140
- var _a, _b, _c;
165
+ query(query) {
166
+ var _a;
141
167
  return __awaiter(this, void 0, void 0, function* () {
142
168
  const data = query.getQueryOptions();
143
169
  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
170
+ filter: Object.values((_a = data.filter) !== null && _a !== void 0 ? _a : {}).some(Boolean) ? data.filter : undefined,
171
+ sort: data.sort ? (0, sorting_1.buildSortFilter)(data.sort) : undefined,
172
+ page: data.page,
173
+ columns: data.columns
148
174
  };
149
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
175
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
150
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));
151
- 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
177
+ const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), record));
153
178
  return new pagination_1.Page(query, meta, records);
154
179
  });
155
180
  }
156
181
  }
157
182
  exports.RestRepository = RestRepository;
158
- _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) {
159
184
  return __awaiter(this, void 0, void 0, function* () {
160
- const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
161
- return {
162
- fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
163
- apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
164
- apiUrl: '',
165
- // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
166
- workspacesApiUrl: (path, params) => {
167
- var _a, _b;
168
- const baseUrl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.databaseURL) !== null && _a !== void 0 ? _a : '';
169
- const hasBranch = (_b = params.dbBranchName) !== null && _b !== void 0 ? _b : params.branch;
170
- const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branch}` : '');
171
- return baseUrl + newPath;
172
- }
173
- };
185
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
186
+ const record = transformObjectLinks(object);
187
+ const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
188
+ workspace: '{workspaceId}',
189
+ dbBranchName: '{dbBranch}',
190
+ tableName: __classPrivateFieldGet(this, _RestRepository_table, "f")
191
+ }, body: record }, fetchProps));
192
+ const finalObject = yield this.read(response.id);
193
+ if (!finalObject) {
194
+ throw new Error('The server failed to save the record');
195
+ }
196
+ return finalObject;
174
197
  });
175
- };
176
- class RestRespositoryFactory {
177
- createRepository(client, table) {
178
- return new RestRepository(client, table);
179
- }
180
- }
181
- exports.RestRespositoryFactory = RestRespositoryFactory;
182
- class BaseClient {
183
- constructor(options, links = {}) {
184
- _BaseClient_links.set(this, void 0);
185
- _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');
198
+ }, _RestRepository_insertRecordWithId = function _RestRepository_insertRecordWithId(recordId, object) {
199
+ return __awaiter(this, void 0, void 0, function* () {
200
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_getFetchProps, "f").call(this);
201
+ const record = transformObjectLinks(object);
202
+ const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
203
+ workspace: '{workspaceId}',
204
+ dbBranchName: '{dbBranch}',
205
+ tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
206
+ recordId
207
+ }, body: record, queryParams: { createOnly: true } }, fetchProps));
208
+ const finalObject = yield this.read(response.id);
209
+ if (!finalObject) {
210
+ throw new Error('The server failed to save the record');
188
211
  }
189
- this.options = options;
190
- __classPrivateFieldSet(this, _BaseClient_links, links, "f");
191
- const factory = options.repositoryFactory || new RestRespositoryFactory();
192
- this.db = new Proxy({}, {
193
- get: (_target, prop) => {
194
- if (typeof prop !== 'string')
195
- throw new Error('Invalid table name');
196
- return factory.createRepository(this, prop);
197
- }
198
- });
199
- }
200
- initObject(table, object) {
201
- const o = {};
202
- Object.assign(o, object);
203
- const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
204
- for (const link of tableLinks) {
205
- 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
- }
220
- }
212
+ return finalObject;
213
+ });
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');
221
222
  }
222
- const db = this.db;
223
- o.read = function () {
224
- return db[table].read(o['id']);
225
- };
226
- o.update = function (data) {
227
- return db[table].update(o['id'], data);
228
- };
229
- o.delete = function () {
230
- return db[table].delete(o['id']);
231
- };
232
- for (const prop of ['read', 'update', 'delete']) {
233
- Object.defineProperty(o, 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);
234
258
  }
235
- // TODO: links and rev links
236
- Object.freeze(o);
237
- return o;
238
259
  }
239
- getBranch() {
240
- var e_1, _a;
241
- return __awaiter(this, void 0, void 0, function* () {
242
- if (__classPrivateFieldGet(this, _BaseClient_branch, "f"))
243
- return __classPrivateFieldGet(this, _BaseClient_branch, "f");
244
- const { branch: param } = this.options;
245
- const strategies = Array.isArray(param) ? [...param] : [param];
246
- const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
247
- return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy;
248
- });
249
- try {
250
- for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
251
- const strategy = strategies_1_1.value;
252
- const branch = yield evaluateBranch(strategy);
253
- if (branch) {
254
- __classPrivateFieldSet(this, _BaseClient_branch, branch, "f");
255
- return branch;
256
- }
257
- }
258
- }
259
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
260
- finally {
261
- try {
262
- if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
263
- }
264
- finally { if (e_1) throw e_1.error; }
265
- }
266
- throw new Error('Unable to resolve branch value');
267
- });
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 });
268
272
  }
269
- }
270
- exports.BaseClient = BaseClient;
271
- _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
272
- const isBranchStrategyBuilder = (strategy) => {
273
- return typeof strategy === 'function';
273
+ Object.freeze(result);
274
+ return result;
274
275
  };
275
- // TODO: We can find a better implementation for links
276
276
  const transformObjectLinks = (object) => {
277
277
  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 });
278
+ // Ignore internal properties
279
+ if (key === 'xata')
280
+ return acc;
281
+ // Transform links to identifier
282
+ return Object.assign(Object.assign({}, acc), { [key]: (0, record_1.isIdentifiable)(value) ? value.id : value });
282
283
  }, {});
283
284
  };
@@ -1,12 +1,25 @@
1
- import { StringKeys, UnionToIntersection, Values } from '../util/types';
2
- import { Query } from './query';
3
- import { BaseData, Identifiable, XataRecord } from './record';
4
- declare type Queries<T> = {
5
- [key in keyof T as T[key] extends Query<any, any> ? key : never]: T[key];
6
- };
7
- export declare type Selectable<T extends BaseData> = T & Partial<Identifiable>;
8
- export declare type SelectableColumn<O> = '*' | (O extends Array<unknown> ? never : O extends Record<string, any> ? '*' | Values<{
9
- [K in StringKeys<O>]: O[K] extends Record<string, any> ? `${K}.${SelectableColumn<O[K]>}` : K;
10
- }> : '');
11
- export declare type Select<T, K extends SelectableColumn<T>> = UnionToIntersection<K extends keyof T ? Pick<T, K> : T> & Queries<T> & XataRecord;
1
+ import { If, IsArray, IsObject, StringKeys, UnionToIntersection, Values } from '../util/types';
2
+ import { Link, XataRecord } from './record';
3
+ export declare type SelectableColumn<O, RecursivePath extends any[] = []> = '*' | 'id' | DataProps<O> | NestedColumns<O, RecursivePath>;
4
+ export declare type SelectedPick<O extends XataRecord, Key extends SelectableColumn<O>[]> = XataRecord & UnionToIntersection<Values<{
5
+ [K in Key[number]]: NestedValueAtColumn<O, K> & XataRecord;
6
+ }>>;
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
+ V: ValueAtColumn<O[K], V>;
9
+ } : never) : O[K]> : never : never;
10
+ declare type MAX_RECURSION = 5;
11
+ declare type NestedColumns<O, RecursivePath extends any[]> = RecursivePath['length'] extends MAX_RECURSION ? never : If<IsObject<O>, Values<{
12
+ [K in DataProps<O>]: If<IsArray<NonNullable<O[K]>>, K, // If the property is an array, we stop recursion. We don't support object arrays yet
13
+ If<IsObject<NonNullable<O[K]>>, NonNullable<O[K]> extends XataRecord ? SelectableColumn<NonNullable<O[K]>, [...RecursivePath, O[K]]> extends string ? K | `${K}.${SelectableColumn<NonNullable<O[K]>, [...RecursivePath, O[K]]>}` : never : `${K}.${StringKeys<NonNullable<O[K]>> | '*'}`, // This allows usage of objects that are not links
14
+ K>>;
15
+ }>, never>;
16
+ declare type DataProps<O> = Exclude<StringKeys<O>, StringKeys<XataRecord>>;
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]>> ? NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], NestedValueAtColumn<NonNullable<O[K]>, M> & XataRecord> : ForwardNullable<O[K], NestedValueAtColumn<NonNullable<O[K]>, M>> : unknown;
19
+ } : unknown : Key extends DataProps<O> ? {
20
+ [K in Key]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], SelectedPick<NonNullable<O[K]>, ['*']>> : O[K];
21
+ } : Key extends '*' ? {
22
+ [K in StringKeys<O>]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], Link<NonNullable<O[K]>>> : O[K];
23
+ } : unknown;
24
+ declare type ForwardNullable<T, R> = T extends NonNullable<T> ? R : R | null;
12
25
  export {};
@@ -0,0 +1 @@
1
+ export {};