@xata.io/client 0.0.0-beta.4e4e7fc → 0.0.0-beta.53c906e

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 (48) hide show
  1. package/.eslintrc.cjs +13 -0
  2. package/CHANGELOG.md +71 -0
  3. package/dist/api/client.d.ts +4 -2
  4. package/dist/api/client.js +40 -18
  5. package/dist/api/components.d.ts +58 -37
  6. package/dist/api/components.js +48 -38
  7. package/dist/api/fetcher.d.ts +15 -0
  8. package/dist/api/fetcher.js +23 -22
  9. package/dist/api/parameters.d.ts +1 -0
  10. package/dist/api/providers.js +3 -2
  11. package/dist/api/responses.d.ts +6 -0
  12. package/dist/api/schemas.d.ts +1 -1
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.js +1 -0
  15. package/dist/schema/filters.d.ts +93 -17
  16. package/dist/schema/filters.js +0 -22
  17. package/dist/schema/filters.spec.d.ts +1 -0
  18. package/dist/schema/filters.spec.js +175 -0
  19. package/dist/schema/index.d.ts +5 -3
  20. package/dist/schema/index.js +8 -4
  21. package/dist/schema/operators.d.ts +74 -21
  22. package/dist/schema/operators.js +59 -6
  23. package/dist/schema/pagination.d.ts +56 -14
  24. package/dist/schema/pagination.js +37 -2
  25. package/dist/schema/query.d.ts +110 -37
  26. package/dist/schema/query.js +87 -35
  27. package/dist/schema/record.d.ts +60 -4
  28. package/dist/schema/record.js +11 -0
  29. package/dist/schema/repository.d.ts +140 -25
  30. package/dist/schema/repository.js +232 -100
  31. package/dist/schema/selection.d.ts +24 -13
  32. package/dist/schema/selection.spec.d.ts +1 -0
  33. package/dist/schema/selection.spec.js +203 -0
  34. package/dist/schema/sorting.d.ts +17 -0
  35. package/dist/schema/sorting.js +28 -0
  36. package/dist/schema/sorting.spec.d.ts +1 -0
  37. package/dist/schema/sorting.spec.js +9 -0
  38. package/dist/util/config.d.ts +11 -0
  39. package/dist/util/config.js +121 -0
  40. package/dist/util/environment.d.ts +5 -0
  41. package/dist/util/environment.js +68 -0
  42. package/dist/util/fetch.d.ts +2 -0
  43. package/dist/util/fetch.js +13 -0
  44. package/dist/util/lang.d.ts +3 -0
  45. package/dist/util/lang.js +13 -1
  46. package/dist/util/types.d.ts +22 -1
  47. package/package.json +5 -2
  48. package/tsconfig.json +21 -0
@@ -26,17 +26,24 @@ 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("../util/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");
40
+ /**
41
+ * Common interface for performing operations on a table.
42
+ */
36
43
  class Repository extends query_1.Query {
37
44
  }
38
45
  exports.Repository = Repository;
39
- class RestRepository extends Repository {
46
+ class RestRepository extends query_1.Query {
40
47
  constructor(client, table) {
41
48
  super(null, table, {});
42
49
  _RestRepository_instances.add(this);
@@ -45,107 +52,151 @@ class RestRepository extends Repository {
45
52
  _RestRepository_table.set(this, void 0);
46
53
  __classPrivateFieldSet(this, _RestRepository_client, client, "f");
47
54
  __classPrivateFieldSet(this, _RestRepository_table, table, "f");
48
- // TODO: Remove when integrating with API client
49
- const fetchImpl = typeof fetch !== 'undefined' ? fetch : __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch;
50
- if (!fetchImpl) {
51
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
52
- }
53
- __classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f");
55
+ __classPrivateFieldSet(this, _RestRepository_fetch, (0, fetch_1.getFetchImplementation)(__classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch), "f");
54
56
  }
55
- create(object) {
57
+ create(a, b) {
56
58
  return __awaiter(this, void 0, void 0, function* () {
57
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
58
- const record = transformObjectLinks(object);
59
- const response = object.id
60
- ? yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
61
- workspace: '{workspaceId}',
62
- dbBranchName: '{dbBranch}',
63
- tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
64
- recordId: object.id
65
- }, body: record }, fetchProps))
66
- : yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
67
- workspace: '{workspaceId}',
68
- dbBranchName: '{dbBranch}',
69
- tableName: __classPrivateFieldGet(this, _RestRepository_table, "f")
70
- }, body: record }, fetchProps));
71
- const finalObject = yield this.read(response.id);
72
- if (!finalObject) {
73
- 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);
62
+ }
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);
68
+ }
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
74
  }
75
- return finalObject;
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');
76
80
  });
77
81
  }
78
- createMany(objects) {
82
+ // TODO: Add column support: https://github.com/xataio/openapi/issues/139
83
+ read(recordId) {
79
84
  return __awaiter(this, void 0, void 0, function* () {
80
85
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
81
- const records = objects.map((object) => transformObjectLinks(object));
82
- const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
83
- // TODO: Use filer.$any() to get all the records
84
- const finalObjects = yield Promise.all(response.recordIDs.map((id) => this.read(id)));
85
- if (finalObjects.some((object) => !object)) {
86
- throw new Error('The server failed to save the record');
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;
87
95
  }
88
- return finalObjects;
89
96
  });
90
97
  }
91
- read(recordId) {
98
+ update(a, b) {
92
99
  return __awaiter(this, void 0, void 0, function* () {
93
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
94
- const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
95
- return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
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 }));
115
+ }
116
+ throw new Error('Invalid arguments for update method');
96
117
  });
97
118
  }
98
- update(recordId, object) {
119
+ createOrUpdate(a, b) {
99
120
  return __awaiter(this, void 0, void 0, function* () {
100
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
101
- const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
102
- const item = yield this.read(response.id);
103
- if (!item)
104
- throw new Error('The server failed to save the record');
105
- 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');
106
138
  });
107
139
  }
108
- upsert(recordId, object) {
140
+ delete(recordId) {
109
141
  return __awaiter(this, void 0, void 0, function* () {
110
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
111
- const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
112
- const item = yield this.read(response.id);
113
- if (!item)
114
- throw new Error('The server failed to save the record');
115
- return item;
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');
116
162
  });
117
163
  }
118
- delete(recordId) {
164
+ search(query, options = {}) {
119
165
  return __awaiter(this, void 0, void 0, function* () {
120
166
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
121
- yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
167
+ 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));
168
+ return records.map((item) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), item));
122
169
  });
123
170
  }
124
- query(query, options) {
125
- var _a, _b, _c;
171
+ query(query) {
172
+ var _a;
126
173
  return __awaiter(this, void 0, void 0, function* () {
127
174
  const data = query.getQueryOptions();
128
175
  const body = {
129
- filter: Object.values(data.filter).some(Boolean) ? data.filter : undefined,
130
- sort: (_a = (0, filters_1.buildSortFilter)(options === null || options === void 0 ? void 0 : options.sort)) !== null && _a !== void 0 ? _a : data.sort,
131
- page: (_b = options === null || options === void 0 ? void 0 : options.page) !== null && _b !== void 0 ? _b : data.page,
132
- columns: (_c = options === null || options === void 0 ? void 0 : options.columns) !== null && _c !== void 0 ? _c : data.columns
176
+ filter: Object.values((_a = data.filter) !== null && _a !== void 0 ? _a : {}).some(Boolean) ? data.filter : undefined,
177
+ sort: data.sort ? (0, sorting_1.buildSortFilter)(data.sort) : undefined,
178
+ page: data.page,
179
+ columns: data.columns
133
180
  };
134
181
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
135
182
  const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body }, fetchProps));
136
183
  const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record));
137
- // TODO: We should properly type this any
138
184
  return new pagination_1.Page(query, meta, records);
139
185
  });
140
186
  }
141
187
  }
142
188
  exports.RestRepository = RestRepository;
143
189
  _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
190
+ var _a;
144
191
  return __awaiter(this, void 0, void 0, function* () {
145
192
  const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
193
+ const apiKey = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey) !== null && _a !== void 0 ? _a : (0, config_1.getAPIKey)();
194
+ if (!apiKey) {
195
+ throw new Error('Could not resolve a valid apiKey');
196
+ }
146
197
  return {
147
198
  fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
148
- apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
199
+ apiKey,
149
200
  apiUrl: '',
150
201
  // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
151
202
  workspacesApiUrl: (path, params) => {
@@ -157,6 +208,72 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
157
208
  }
158
209
  };
159
210
  });
211
+ }, _RestRepository_insertRecordWithoutId = function _RestRepository_insertRecordWithoutId(object) {
212
+ return __awaiter(this, void 0, void 0, function* () {
213
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
214
+ const record = transformObjectLinks(object);
215
+ const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
216
+ workspace: '{workspaceId}',
217
+ dbBranchName: '{dbBranch}',
218
+ tableName: __classPrivateFieldGet(this, _RestRepository_table, "f")
219
+ }, body: record }, fetchProps));
220
+ const finalObject = yield this.read(response.id);
221
+ if (!finalObject) {
222
+ throw new Error('The server failed to save the record');
223
+ }
224
+ return finalObject;
225
+ });
226
+ }, _RestRepository_insertRecordWithId = function _RestRepository_insertRecordWithId(recordId, object) {
227
+ return __awaiter(this, void 0, void 0, function* () {
228
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
229
+ const record = transformObjectLinks(object);
230
+ const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
231
+ workspace: '{workspaceId}',
232
+ dbBranchName: '{dbBranch}',
233
+ tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
234
+ recordId
235
+ }, body: record, queryParams: { createOnly: true } }, fetchProps));
236
+ const finalObject = yield this.read(response.id);
237
+ if (!finalObject) {
238
+ throw new Error('The server failed to save the record');
239
+ }
240
+ return finalObject;
241
+ });
242
+ }, _RestRepository_bulkInsertTableRecords = function _RestRepository_bulkInsertTableRecords(objects) {
243
+ return __awaiter(this, void 0, void 0, function* () {
244
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
245
+ const records = objects.map((object) => transformObjectLinks(object));
246
+ const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
247
+ const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
248
+ if (finalObjects.length !== objects.length) {
249
+ throw new Error('The server failed to save some records');
250
+ }
251
+ return finalObjects;
252
+ });
253
+ }, _RestRepository_updateRecordWithID = function _RestRepository_updateRecordWithID(recordId, object) {
254
+ return __awaiter(this, void 0, void 0, function* () {
255
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
256
+ const record = transformObjectLinks(object);
257
+ const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
258
+ const item = yield this.read(response.id);
259
+ if (!item)
260
+ throw new Error('The server failed to save the record');
261
+ return item;
262
+ });
263
+ }, _RestRepository_upsertRecordWithID = function _RestRepository_upsertRecordWithID(recordId, object) {
264
+ return __awaiter(this, void 0, void 0, function* () {
265
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
266
+ const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
267
+ const item = yield this.read(response.id);
268
+ if (!item)
269
+ throw new Error('The server failed to save the record');
270
+ return item;
271
+ });
272
+ }, _RestRepository_deleteRecord = function _RestRepository_deleteRecord(recordId) {
273
+ return __awaiter(this, void 0, void 0, function* () {
274
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
275
+ yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
276
+ });
160
277
  };
161
278
  class RestRespositoryFactory {
162
279
  createRepository(client, table) {
@@ -164,54 +281,69 @@ class RestRespositoryFactory {
164
281
  }
165
282
  }
166
283
  exports.RestRespositoryFactory = RestRespositoryFactory;
284
+ function resolveXataClientOptions(options) {
285
+ const databaseURL = (options === null || options === void 0 ? void 0 : options.databaseURL) || (0, config_1.getDatabaseURL)() || '';
286
+ const apiKey = (options === null || options === void 0 ? void 0 : options.apiKey) || (0, config_1.getAPIKey)() || '';
287
+ const branch = (options === null || options === void 0 ? void 0 : options.branch) || (() => (0, config_1.getCurrentBranchName)({ apiKey, databaseURL, fetchImpl: options === null || options === void 0 ? void 0 : options.fetch }));
288
+ if (!databaseURL || !apiKey) {
289
+ throw new Error('Options databaseURL and apiKey are required');
290
+ }
291
+ return Object.assign(Object.assign({}, options), { databaseURL,
292
+ apiKey,
293
+ branch });
294
+ }
167
295
  class BaseClient {
168
- constructor(options, links) {
296
+ constructor(options = {}, links = {}) {
169
297
  _BaseClient_links.set(this, void 0);
170
298
  _BaseClient_branch.set(this, void 0);
171
- if (!options.databaseURL || !options.apiKey || !options.branch) {
172
- throw new Error('Options databaseURL, apiKey and branch are required');
173
- }
174
- this.options = options;
299
+ this.options = resolveXataClientOptions(options);
300
+ // Make this property not enumerable so it doesn't show up in console.dir, etc.
301
+ Object.defineProperty(this.options, 'apiKey', { enumerable: false });
175
302
  __classPrivateFieldSet(this, _BaseClient_links, links, "f");
303
+ const factory = this.options.repositoryFactory || new RestRespositoryFactory();
304
+ this.db = new Proxy({}, {
305
+ get: (_target, prop) => {
306
+ if (!(0, lang_1.isString)(prop))
307
+ throw new Error('Invalid table name');
308
+ return factory.createRepository(this, prop);
309
+ }
310
+ });
311
+ }
312
+ search(query, options) {
313
+ var _a;
314
+ return __awaiter(this, void 0, void 0, function* () {
315
+ const tables = (_a = options === null || options === void 0 ? void 0 : options.tables) !== null && _a !== void 0 ? _a : Object.keys(this.db);
316
+ // TODO: Implement global search with a single call, REST repository abstraction needed
317
+ const results = yield Promise.all(tables.map((table) => this.db[table].search(query, options).then((results) => [table, results])));
318
+ return Object.fromEntries(results);
319
+ });
176
320
  }
177
321
  initObject(table, object) {
178
- const o = {};
179
- Object.assign(o, object);
322
+ const result = {};
323
+ Object.assign(result, object);
180
324
  const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
181
325
  for (const link of tableLinks) {
182
326
  const [field, linkTable] = link;
183
- const value = o[field];
184
- if (value && typeof value === 'object') {
185
- const { id } = value;
186
- if (Object.keys(value).find((col) => col === 'id')) {
187
- o[field] = this.initObject(linkTable, value);
188
- }
189
- else if (id) {
190
- o[field] = {
191
- id,
192
- get: () => {
193
- this.db[linkTable].read(id);
194
- }
195
- };
196
- }
327
+ const value = result[field];
328
+ if (value && (0, lang_1.isObject)(value)) {
329
+ result[field] = this.initObject(linkTable, value);
197
330
  }
198
331
  }
199
332
  const db = this.db;
200
- o.read = function () {
201
- return db[table].read(o['id']);
333
+ result.read = function () {
334
+ return db[table].read(result['id']);
202
335
  };
203
- o.update = function (data) {
204
- return db[table].update(o['id'], data);
336
+ result.update = function (data) {
337
+ return db[table].update(result['id'], data);
205
338
  };
206
- o.delete = function () {
207
- return db[table].delete(o['id']);
339
+ result.delete = function () {
340
+ return db[table].delete(result['id']);
208
341
  };
209
342
  for (const prop of ['read', 'update', 'delete']) {
210
- Object.defineProperty(o, prop, { enumerable: false });
343
+ Object.defineProperty(result, prop, { enumerable: false });
211
344
  }
212
- // TODO: links and rev links
213
- Object.freeze(o);
214
- return o;
345
+ Object.freeze(result);
346
+ return result;
215
347
  }
216
348
  getBranch() {
217
349
  var e_1, _a;
@@ -249,12 +381,12 @@ _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
249
381
  const isBranchStrategyBuilder = (strategy) => {
250
382
  return typeof strategy === 'function';
251
383
  };
252
- // TODO: We can find a better implementation for links
253
384
  const transformObjectLinks = (object) => {
254
385
  return Object.entries(object).reduce((acc, [key, value]) => {
255
- if (value && typeof value === 'object' && typeof value.id === 'string') {
256
- return Object.assign(Object.assign({}, acc), { [key]: value.id });
257
- }
258
- return Object.assign(Object.assign({}, acc), { [key]: value });
386
+ // Ignore internal properties
387
+ if (key === 'xata')
388
+ return acc;
389
+ // Transform links to identifier
390
+ return Object.assign(Object.assign({}, acc), { [key]: (0, record_1.isIdentifiable)(value) ? value.id : value });
259
391
  }, {});
260
392
  };
@@ -1,14 +1,25 @@
1
- import { XataRecord } from '..';
2
- import { PartialBy } from '../util/lang';
3
- import { StringKeys, UnionToIntersection, Values } from '../util/types';
4
- import { Query } from './query';
5
- declare type Queries<T> = {
6
- [key in keyof T as T[key] extends Query<any> ? key : never]: T[key];
7
- };
8
- declare type InternalProperties = keyof Omit<XataRecord, 'id'>;
9
- export declare type Selectable<T extends XataRecord> = Omit<PartialBy<T, 'id'>, InternalProperties>;
10
- export declare type SelectableColumn<O> = '*' | (O extends Array<unknown> ? never : O extends Record<string, any> ? '*' | Values<{
11
- [K in StringKeys<O>]: O[K] extends Record<string, any> ? `${K}.${SelectableColumn<O[K]>}` : K;
12
- }> : '');
13
- 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;
14
25
  export {};
@@ -0,0 +1 @@
1
+ export {};