@xata.io/client 0.6.0 → 0.7.2

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.
@@ -26,15 +26,17 @@ 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, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _BaseClient_links, _BaseClient_branch;
29
+ var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_links, _RestRepository_branch, _RestRepository_getFetchProps, _RestRepository_getBranch, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _RestRepository_bulkInsertTableRecords, _RestRepository_updateRecordWithID, _RestRepository_upsertRecordWithID, _RestRepository_deleteRecord, _RestRepository_initObject;
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 fetch_1 = require("../util/fetch");
33
34
  const lang_1 = require("../util/lang");
34
- const filters_1 = require("./filters");
35
+ const config_1 = require("../util/config");
35
36
  const pagination_1 = require("./pagination");
36
37
  const query_1 = require("./query");
37
38
  const record_1 = require("./record");
39
+ const sorting_1 = require("./sorting");
38
40
  /**
39
41
  * Common interface for performing operations on a table.
40
42
  */
@@ -42,89 +44,131 @@ class Repository extends query_1.Query {
42
44
  }
43
45
  exports.Repository = Repository;
44
46
  class RestRepository extends query_1.Query {
45
- constructor(client, table) {
46
- var _a;
47
+ constructor(client, table, links) {
47
48
  super(null, table, {});
48
49
  _RestRepository_instances.add(this);
49
50
  _RestRepository_client.set(this, void 0);
50
51
  _RestRepository_fetch.set(this, void 0);
51
52
  _RestRepository_table.set(this, void 0);
53
+ _RestRepository_links.set(this, void 0);
54
+ _RestRepository_branch.set(this, void 0);
52
55
  __classPrivateFieldSet(this, _RestRepository_client, client, "f");
53
56
  __classPrivateFieldSet(this, _RestRepository_table, table, "f");
54
- // TODO: Remove when integrating with API client
55
- const globalFetch = typeof fetch !== 'undefined' ? fetch : undefined;
56
- const fetchImpl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch) !== null && _a !== void 0 ? _a : globalFetch;
57
- if (!fetchImpl) {
58
- /** @todo add a link after docs exist */
59
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
60
- }
61
- __classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f");
57
+ __classPrivateFieldSet(this, _RestRepository_fetch, (0, fetch_1.getFetchImplementation)(__classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch), "f");
58
+ __classPrivateFieldSet(this, _RestRepository_links, links !== null && links !== void 0 ? links : {}, "f");
62
59
  }
63
60
  create(a, b) {
64
61
  return __awaiter(this, void 0, void 0, function* () {
62
+ // Create many records
63
+ if (Array.isArray(a)) {
64
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_bulkInsertTableRecords).call(this, a);
65
+ }
66
+ // Create one record with id as param
65
67
  if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
66
68
  if (a === '')
67
69
  throw new Error("The id can't be empty");
68
70
  return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a, b);
69
71
  }
70
- else if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
72
+ // Create one record with id as property
73
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
71
74
  if (a.id === '')
72
75
  throw new Error("The id can't be empty");
73
76
  return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
74
77
  }
75
- else if ((0, lang_1.isObject)(a)) {
78
+ // Create one record without id
79
+ if ((0, lang_1.isObject)(a)) {
76
80
  return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithoutId).call(this, a);
77
81
  }
78
- else {
79
- throw new Error('Invalid arguments for create method');
80
- }
82
+ throw new Error('Invalid arguments for create method');
81
83
  });
82
84
  }
83
- createMany(objects) {
85
+ // TODO: Add column support: https://github.com/xataio/openapi/issues/139
86
+ read(recordId) {
84
87
  return __awaiter(this, void 0, void 0, function* () {
85
88
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
86
- const records = objects.map((object) => transformObjectLinks(object));
87
- const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
88
- const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
89
- if (finalObjects.length !== objects.length) {
90
- throw new Error('The server failed to save some records');
89
+ try {
90
+ const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
91
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), response);
92
+ }
93
+ catch (e) {
94
+ if ((0, lang_1.isObject)(e) && e.status === 404) {
95
+ return null;
96
+ }
97
+ throw e;
91
98
  }
92
- return finalObjects;
93
99
  });
94
100
  }
95
- // TODO: Add column support: https://github.com/xataio/openapi/issues/139
96
- read(recordId) {
101
+ update(a, b) {
97
102
  return __awaiter(this, void 0, void 0, function* () {
98
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
99
- const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
100
- return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
103
+ // Update many records
104
+ if (Array.isArray(a)) {
105
+ if (a.length > 100) {
106
+ // TODO: Implement bulk update when API has support for it
107
+ console.warn('Bulk update operation is not optimized in the Xata API yet, this request might be slow');
108
+ }
109
+ return Promise.all(a.map((object) => this.update(object)));
110
+ }
111
+ // Update one record with id as param
112
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
113
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_updateRecordWithID).call(this, a, b);
114
+ }
115
+ // Update one record with id as property
116
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
117
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_updateRecordWithID).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
118
+ }
119
+ throw new Error('Invalid arguments for update method');
101
120
  });
102
121
  }
103
- update(recordId, object) {
122
+ createOrUpdate(a, b) {
104
123
  return __awaiter(this, void 0, void 0, function* () {
105
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
106
- const record = transformObjectLinks(object);
107
- const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
108
- const item = yield this.read(response.id);
109
- if (!item)
110
- throw new Error('The server failed to save the record');
111
- return item;
124
+ // Create or update many records
125
+ if (Array.isArray(a)) {
126
+ if (a.length > 100) {
127
+ // TODO: Implement bulk update when API has support for it
128
+ console.warn('Bulk update operation is not optimized in the Xata API yet, this request might be slow');
129
+ }
130
+ return Promise.all(a.map((object) => this.createOrUpdate(object)));
131
+ }
132
+ // Create or update one record with id as param
133
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
134
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_upsertRecordWithID).call(this, a, b);
135
+ }
136
+ // Create or update one record with id as property
137
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
138
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_upsertRecordWithID).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
139
+ }
140
+ throw new Error('Invalid arguments for createOrUpdate method');
112
141
  });
113
142
  }
114
- createOrUpdate(recordId, object) {
143
+ delete(recordId) {
115
144
  return __awaiter(this, void 0, void 0, function* () {
116
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
117
- const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
118
- const item = yield this.read(response.id);
119
- if (!item)
120
- throw new Error('The server failed to save the record');
121
- return item;
145
+ // Delete many records
146
+ if (Array.isArray(recordId)) {
147
+ if (recordId.length > 100) {
148
+ // TODO: Implement bulk delete when API has support for it
149
+ console.warn('Bulk delete operation is not optimized in the Xata API yet, this request might be slow');
150
+ }
151
+ yield Promise.all(recordId.map((id) => this.delete(id)));
152
+ return;
153
+ }
154
+ // Delete one record with id as param
155
+ if ((0, lang_1.isString)(recordId)) {
156
+ yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_deleteRecord).call(this, recordId);
157
+ return;
158
+ }
159
+ // Delete one record with id as property
160
+ if ((0, lang_1.isObject)(recordId) && (0, lang_1.isString)(recordId.id)) {
161
+ yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_deleteRecord).call(this, recordId.id);
162
+ return;
163
+ }
164
+ throw new Error('Invalid arguments for delete method');
122
165
  });
123
166
  }
124
- delete(recordId) {
167
+ search(query, options = {}) {
125
168
  return __awaiter(this, void 0, void 0, function* () {
126
169
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
127
- yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
170
+ 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));
171
+ return records.map((item) => __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), item));
128
172
  });
129
173
  }
130
174
  query(query) {
@@ -133,24 +177,29 @@ class RestRepository extends query_1.Query {
133
177
  const data = query.getQueryOptions();
134
178
  const body = {
135
179
  filter: Object.values((_a = data.filter) !== null && _a !== void 0 ? _a : {}).some(Boolean) ? data.filter : undefined,
136
- sort: (0, filters_1.buildSortFilter)(data.sort),
180
+ sort: data.sort ? (0, sorting_1.buildSortFilter)(data.sort) : undefined,
137
181
  page: data.page,
138
182
  columns: data.columns
139
183
  };
140
184
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
141
185
  const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body }, fetchProps));
142
- const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record));
186
+ const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, __classPrivateFieldGet(this, _RestRepository_table, "f"), record));
143
187
  return new pagination_1.Page(query, meta, records);
144
188
  });
145
189
  }
146
190
  }
147
191
  exports.RestRepository = RestRepository;
148
- _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
192
+ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_links = new WeakMap(), _RestRepository_branch = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
193
+ var _a;
149
194
  return __awaiter(this, void 0, void 0, function* () {
150
- const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
195
+ const branch = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getBranch).call(this);
196
+ const apiKey = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey) !== null && _a !== void 0 ? _a : (0, config_1.getAPIKey)();
197
+ if (!apiKey) {
198
+ throw new Error('Could not resolve a valid apiKey');
199
+ }
151
200
  return {
152
201
  fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
153
- apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
202
+ apiKey,
154
203
  apiUrl: '',
155
204
  // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
156
205
  workspacesApiUrl: (path, params) => {
@@ -162,6 +211,35 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
162
211
  }
163
212
  };
164
213
  });
214
+ }, _RestRepository_getBranch = function _RestRepository_getBranch() {
215
+ var e_1, _a;
216
+ return __awaiter(this, void 0, void 0, function* () {
217
+ if (__classPrivateFieldGet(this, _RestRepository_branch, "f"))
218
+ return __classPrivateFieldGet(this, _RestRepository_branch, "f");
219
+ const { branch: param } = __classPrivateFieldGet(this, _RestRepository_client, "f").options;
220
+ const strategies = Array.isArray(param) ? [...param] : [param];
221
+ const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
222
+ return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy;
223
+ });
224
+ try {
225
+ for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
226
+ const strategy = strategies_1_1.value;
227
+ const branch = yield evaluateBranch(strategy);
228
+ if (branch) {
229
+ __classPrivateFieldSet(this, _RestRepository_branch, branch, "f");
230
+ return branch;
231
+ }
232
+ }
233
+ }
234
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
235
+ finally {
236
+ try {
237
+ if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
238
+ }
239
+ finally { if (e_1) throw e_1.error; }
240
+ }
241
+ throw new Error('Unable to resolve branch value');
242
+ });
165
243
  }, _RestRepository_insertRecordWithoutId = function _RestRepository_insertRecordWithoutId(object) {
166
244
  return __awaiter(this, void 0, void 0, function* () {
167
245
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
@@ -193,96 +271,119 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
193
271
  }
194
272
  return finalObject;
195
273
  });
274
+ }, _RestRepository_bulkInsertTableRecords = function _RestRepository_bulkInsertTableRecords(objects) {
275
+ return __awaiter(this, void 0, void 0, function* () {
276
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
277
+ const records = objects.map((object) => transformObjectLinks(object));
278
+ const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
279
+ const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
280
+ if (finalObjects.length !== objects.length) {
281
+ throw new Error('The server failed to save some records');
282
+ }
283
+ return finalObjects;
284
+ });
285
+ }, _RestRepository_updateRecordWithID = function _RestRepository_updateRecordWithID(recordId, object) {
286
+ return __awaiter(this, void 0, void 0, function* () {
287
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
288
+ const record = transformObjectLinks(object);
289
+ const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
290
+ const item = yield this.read(response.id);
291
+ if (!item)
292
+ throw new Error('The server failed to save the record');
293
+ return item;
294
+ });
295
+ }, _RestRepository_upsertRecordWithID = function _RestRepository_upsertRecordWithID(recordId, object) {
296
+ return __awaiter(this, void 0, void 0, function* () {
297
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
298
+ const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
299
+ const item = yield this.read(response.id);
300
+ if (!item)
301
+ throw new Error('The server failed to save the record');
302
+ return item;
303
+ });
304
+ }, _RestRepository_deleteRecord = function _RestRepository_deleteRecord(recordId) {
305
+ return __awaiter(this, void 0, void 0, function* () {
306
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
307
+ yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
308
+ });
309
+ }, _RestRepository_initObject = function _RestRepository_initObject(table, object) {
310
+ const result = {};
311
+ Object.assign(result, object);
312
+ const tableLinks = __classPrivateFieldGet(this, _RestRepository_links, "f")[table] || [];
313
+ for (const link of tableLinks) {
314
+ const [field, linkTable] = link;
315
+ const value = result[field];
316
+ if (value && (0, lang_1.isObject)(value)) {
317
+ result[field] = __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_initObject).call(this, linkTable, value);
318
+ }
319
+ }
320
+ const db = __classPrivateFieldGet(this, _RestRepository_client, "f").db;
321
+ result.read = function () {
322
+ return db[table].read(result['id']);
323
+ };
324
+ result.update = function (data) {
325
+ return db[table].update(result['id'], data);
326
+ };
327
+ result.delete = function () {
328
+ return db[table].delete(result['id']);
329
+ };
330
+ for (const prop of ['read', 'update', 'delete']) {
331
+ Object.defineProperty(result, prop, { enumerable: false });
332
+ }
333
+ Object.freeze(result);
334
+ return result;
196
335
  };
197
336
  class RestRespositoryFactory {
198
- createRepository(client, table) {
199
- return new RestRepository(client, table);
337
+ createRepository(client, table, links) {
338
+ return new RestRepository(client, table, links);
200
339
  }
201
340
  }
202
341
  exports.RestRespositoryFactory = RestRespositoryFactory;
342
+ function resolveXataClientOptions(options) {
343
+ const databaseURL = (options === null || options === void 0 ? void 0 : options.databaseURL) || (0, config_1.getDatabaseURL)() || '';
344
+ const apiKey = (options === null || options === void 0 ? void 0 : options.apiKey) || (0, config_1.getAPIKey)() || '';
345
+ 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 }));
346
+ if (!databaseURL || !apiKey) {
347
+ throw new Error('Options databaseURL and apiKey are required');
348
+ }
349
+ return Object.assign(Object.assign({}, options), { databaseURL,
350
+ apiKey,
351
+ branch });
352
+ }
203
353
  class BaseClient {
204
- constructor(options, links = {}) {
205
- _BaseClient_links.set(this, void 0);
206
- _BaseClient_branch.set(this, void 0);
207
- if (!options.databaseURL || !options.apiKey || !options.branch) {
208
- throw new Error('Options databaseURL, apiKey and branch are required');
209
- }
210
- this.options = options;
211
- __classPrivateFieldSet(this, _BaseClient_links, links, "f");
212
- const factory = options.repositoryFactory || new RestRespositoryFactory();
354
+ constructor(options = {}, links) {
355
+ this.options = resolveXataClientOptions(options);
356
+ // Make this property not enumerable so it doesn't show up in console.dir, etc.
357
+ Object.defineProperty(this.options, 'apiKey', { enumerable: false });
358
+ const factory = this.options.repositoryFactory || new RestRespositoryFactory();
213
359
  this.db = new Proxy({}, {
214
360
  get: (_target, prop) => {
215
- if (typeof prop !== 'string')
361
+ if (!(0, lang_1.isString)(prop))
216
362
  throw new Error('Invalid table name');
217
- return factory.createRepository(this, prop);
363
+ return factory.createRepository(this, prop, links);
218
364
  }
219
365
  });
220
366
  }
221
- initObject(table, object) {
222
- const result = {};
223
- Object.assign(result, object);
224
- const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
225
- for (const link of tableLinks) {
226
- const [field, linkTable] = link;
227
- const value = result[field];
228
- if (value && (0, lang_1.isObject)(value)) {
229
- result[field] = this.initObject(linkTable, value);
230
- }
231
- }
232
- const db = this.db;
233
- result.read = function () {
234
- return db[table].read(result['id']);
235
- };
236
- result.update = function (data) {
237
- return db[table].update(result['id'], data);
238
- };
239
- result.delete = function () {
240
- return db[table].delete(result['id']);
241
- };
242
- for (const prop of ['read', 'update', 'delete']) {
243
- Object.defineProperty(result, prop, { enumerable: false });
244
- }
245
- Object.freeze(result);
246
- return result;
247
- }
248
- getBranch() {
249
- var e_1, _a;
367
+ search(query, options) {
368
+ var _a;
250
369
  return __awaiter(this, void 0, void 0, function* () {
251
- if (__classPrivateFieldGet(this, _BaseClient_branch, "f"))
252
- return __classPrivateFieldGet(this, _BaseClient_branch, "f");
253
- const { branch: param } = this.options;
254
- const strategies = Array.isArray(param) ? [...param] : [param];
255
- const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
256
- return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy;
257
- });
258
- try {
259
- for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
260
- const strategy = strategies_1_1.value;
261
- const branch = yield evaluateBranch(strategy);
262
- if (branch) {
263
- __classPrivateFieldSet(this, _BaseClient_branch, branch, "f");
264
- return branch;
265
- }
266
- }
267
- }
268
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
269
- finally {
270
- try {
271
- if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
272
- }
273
- finally { if (e_1) throw e_1.error; }
274
- }
275
- throw new Error('Unable to resolve branch value');
370
+ const tables = (_a = options === null || options === void 0 ? void 0 : options.tables) !== null && _a !== void 0 ? _a : Object.keys(this.db);
371
+ // TODO: Implement global search with a single call, REST repository abstraction needed
372
+ const results = yield Promise.all(tables.map((table) => this.db[table].search(query, options).then((results) => [table, results])));
373
+ return Object.fromEntries(results);
276
374
  });
277
375
  }
278
376
  }
279
377
  exports.BaseClient = BaseClient;
280
- _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
281
378
  const isBranchStrategyBuilder = (strategy) => {
282
379
  return typeof strategy === 'function';
283
380
  };
284
381
  const transformObjectLinks = (object) => {
285
382
  return Object.entries(object).reduce((acc, [key, value]) => {
383
+ // Ignore internal properties
384
+ if (key === 'xata')
385
+ return acc;
386
+ // Transform links to identifier
286
387
  return Object.assign(Object.assign({}, acc), { [key]: (0, record_1.isIdentifiable)(value) ? value.id : value });
287
388
  }, {});
288
389
  };
@@ -4,7 +4,7 @@ export declare type SelectableColumn<O, RecursivePath extends any[] = []> = '*'
4
4
  export declare type SelectedPick<O extends XataRecord, Key extends SelectableColumn<O>[]> = XataRecord & UnionToIntersection<Values<{
5
5
  [K in Key[number]]: NestedValueAtColumn<O, K> & XataRecord;
6
6
  }>>;
7
- export declare type ValueAtColumn<O extends XataRecord, P extends SelectableColumn<O>> = P extends '*' ? Values<O> : P extends 'id' ? string : P extends keyof O ? O[P] : P extends `${infer K}.${infer V}` ? K extends keyof O ? Values<O[K] extends XataRecord ? (V extends SelectableColumn<O[K]> ? {
7
+ export declare type ValueAtColumn<O, P extends SelectableColumn<O>> = P extends '*' ? Values<O> : P extends 'id' ? string : P extends keyof O ? O[P] : P extends `${infer K}.${infer V}` ? K extends keyof O ? Values<O[K] extends XataRecord ? (V extends SelectableColumn<O[K]> ? {
8
8
  V: ValueAtColumn<O[K], V>;
9
9
  } : never) : O[K]> : never : never;
10
10
  declare type MAX_RECURSION = 5;
@@ -15,10 +15,11 @@ declare type NestedColumns<O, RecursivePath extends any[]> = RecursivePath['leng
15
15
  }>, never>;
16
16
  declare type DataProps<O> = Exclude<StringKeys<O>, StringKeys<XataRecord>>;
17
17
  declare type NestedValueAtColumn<O, Key extends SelectableColumn<O>> = Key extends `${infer N}.${infer M}` ? N extends DataProps<O> ? {
18
- [K in N]: M extends SelectableColumn<NonNullable<O[K]>> ? NestedValueAtColumn<NonNullable<O[K]>, M> & XataRecord : unknown;
18
+ [K in N]: M extends SelectableColumn<NonNullable<O[K]>> ? NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], NestedValueAtColumn<NonNullable<O[K]>, M> & XataRecord> : ForwardNullable<O[K], NestedValueAtColumn<NonNullable<O[K]>, M>> : unknown;
19
19
  } : unknown : Key extends DataProps<O> ? {
20
- [K in Key]: NonNullable<O[K]> extends XataRecord ? SelectedPick<NonNullable<O[K]>, ['*']> : O[K];
20
+ [K in Key]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], SelectedPick<NonNullable<O[K]>, ['*']>> : O[K];
21
21
  } : Key extends '*' ? {
22
- [K in keyof NonNullable<O>]: NonNullable<NonNullable<O>[K]> extends XataRecord ? NonNullable<O>[K] extends XataRecord ? Link<NonNullable<O>[K]> : Link<NonNullable<NonNullable<O>[K]>> | null : NonNullable<O>[K];
22
+ [K in StringKeys<O>]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], Link<NonNullable<O[K]>>> : O[K];
23
23
  } : unknown;
24
+ declare type ForwardNullable<T, R> = T extends NonNullable<T> ? R : R | null;
24
25
  export {};