@xata.io/client 0.0.0-alpha.fed4b2b → 0.0.0-beta.036d273

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 (44) hide show
  1. package/.eslintrc.cjs +13 -0
  2. package/CHANGELOG.md +44 -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/index.d.ts +1 -0
  12. package/dist/index.js +1 -0
  13. package/dist/schema/filters.d.ts +93 -18
  14. package/dist/schema/filters.js +0 -22
  15. package/dist/schema/filters.spec.d.ts +1 -0
  16. package/dist/schema/filters.spec.js +175 -0
  17. package/dist/schema/index.d.ts +2 -1
  18. package/dist/schema/index.js +4 -1
  19. package/dist/schema/operators.d.ts +26 -24
  20. package/dist/schema/operators.js +13 -11
  21. package/dist/schema/pagination.js +0 -1
  22. package/dist/schema/query.d.ts +23 -19
  23. package/dist/schema/query.js +13 -19
  24. package/dist/schema/record.d.ts +23 -2
  25. package/dist/schema/record.js +2 -1
  26. package/dist/schema/repository.d.ts +100 -42
  27. package/dist/schema/repository.js +261 -154
  28. package/dist/schema/selection.d.ts +14 -17
  29. package/dist/schema/selection.spec.d.ts +1 -0
  30. package/dist/schema/selection.spec.js +203 -0
  31. package/dist/schema/sorting.d.ts +17 -0
  32. package/dist/schema/sorting.js +28 -0
  33. package/dist/schema/sorting.spec.d.ts +1 -0
  34. package/dist/schema/sorting.spec.js +9 -0
  35. package/dist/util/config.d.ts +11 -0
  36. package/dist/util/config.js +121 -0
  37. package/dist/util/environment.d.ts +5 -0
  38. package/dist/util/environment.js +68 -0
  39. package/dist/util/fetch.d.ts +2 -0
  40. package/dist/util/fetch.js +13 -0
  41. package/dist/util/lang.d.ts +3 -0
  42. package/dist/util/lang.js +13 -1
  43. package/dist/util/types.d.ts +11 -2
  44. package/package.json +5 -2
@@ -26,14 +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, _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 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");
36
38
  const record_1 = require("./record");
39
+ const sorting_1 = require("./sorting");
37
40
  /**
38
41
  * Common interface for performing operations on a table.
39
42
  */
@@ -41,102 +44,131 @@ class Repository extends query_1.Query {
41
44
  }
42
45
  exports.Repository = Repository;
43
46
  class RestRepository extends query_1.Query {
44
- constructor(client, table) {
45
- var _a;
47
+ constructor(client, table, links) {
46
48
  super(null, table, {});
47
49
  _RestRepository_instances.add(this);
48
50
  _RestRepository_client.set(this, void 0);
49
51
  _RestRepository_fetch.set(this, void 0);
50
52
  _RestRepository_table.set(this, void 0);
53
+ _RestRepository_links.set(this, void 0);
54
+ _RestRepository_branch.set(this, void 0);
51
55
  __classPrivateFieldSet(this, _RestRepository_client, client, "f");
52
56
  __classPrivateFieldSet(this, _RestRepository_table, table, "f");
53
- // TODO: Remove when integrating with API client
54
- const globalFetch = typeof fetch !== 'undefined' ? fetch : undefined;
55
- const fetchImpl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch) !== null && _a !== void 0 ? _a : globalFetch;
56
- if (!fetchImpl) {
57
- /** @todo add a link after docs exist */
58
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
59
- }
60
- __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");
61
59
  }
62
- create(object) {
60
+ create(a, b) {
63
61
  return __awaiter(this, void 0, void 0, function* () {
64
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
65
- const record = transformObjectLinks(object);
66
- const response = 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');
62
+ // Create many records
63
+ if (Array.isArray(a)) {
64
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_bulkInsertTableRecords).call(this, a);
74
65
  }
75
- return finalObject;
76
- });
77
- }
78
- createMany(objects) {
79
- return __awaiter(this, void 0, void 0, function* () {
80
- 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
- const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
84
- if (finalObjects.length !== objects.length) {
85
- throw new Error('The server failed to save some records');
66
+ // Create one record with id as param
67
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
68
+ if (a === '')
69
+ throw new Error("The id can't be empty");
70
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a, b);
71
+ }
72
+ // Create one record with id as property
73
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
74
+ if (a.id === '')
75
+ throw new Error("The id can't be empty");
76
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
86
77
  }
87
- // @ts-ignore TODO: FIXME: This is a hack to get the correct type
88
- return finalObjects;
78
+ // Create one record without id
79
+ if ((0, lang_1.isObject)(a)) {
80
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithoutId).call(this, a);
81
+ }
82
+ throw new Error('Invalid arguments for create method');
89
83
  });
90
84
  }
85
+ // TODO: Add column support: https://github.com/xataio/openapi/issues/139
91
86
  read(recordId) {
92
87
  return __awaiter(this, void 0, void 0, function* () {
93
88
  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);
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;
98
+ }
96
99
  });
97
100
  }
98
- update(recordId, object) {
101
+ update(a, b) {
99
102
  return __awaiter(this, void 0, void 0, function* () {
100
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
101
- const record = transformObjectLinks(object);
102
- const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
103
- const item = yield this.read(response.id);
104
- if (!item)
105
- throw new Error('The server failed to save the record');
106
- return item;
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');
107
120
  });
108
121
  }
109
- insert(recordId, object) {
122
+ createOrUpdate(a, b) {
110
123
  return __awaiter(this, void 0, void 0, function* () {
111
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
112
- const record = transformObjectLinks(object);
113
- const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
114
- workspace: '{workspaceId}',
115
- dbBranchName: '{dbBranch}',
116
- tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
117
- recordId
118
- }, body: record }, fetchProps));
119
- const finalObject = yield this.read(response.id);
120
- if (!finalObject) {
121
- throw new Error('The server failed to save the record');
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 }));
122
139
  }
123
- return finalObject;
140
+ throw new Error('Invalid arguments for createOrUpdate method');
124
141
  });
125
142
  }
126
- updateOrInsert(recordId, object) {
143
+ delete(recordId) {
127
144
  return __awaiter(this, void 0, void 0, function* () {
128
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
129
- const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
130
- const item = yield this.read(response.id);
131
- if (!item)
132
- throw new Error('The server failed to save the record');
133
- 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');
134
165
  });
135
166
  }
136
- delete(recordId) {
167
+ search(query, options = {}) {
137
168
  return __awaiter(this, void 0, void 0, function* () {
138
169
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
139
- 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));
140
172
  });
141
173
  }
142
174
  query(query) {
@@ -145,24 +177,29 @@ class RestRepository extends query_1.Query {
145
177
  const data = query.getQueryOptions();
146
178
  const body = {
147
179
  filter: Object.values((_a = data.filter) !== null && _a !== void 0 ? _a : {}).some(Boolean) ? data.filter : undefined,
148
- sort: (0, filters_1.buildSortFilter)(data.sort),
180
+ sort: data.sort ? (0, sorting_1.buildSortFilter)(data.sort) : undefined,
149
181
  page: data.page,
150
182
  columns: data.columns
151
183
  };
152
184
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
153
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));
154
- 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));
155
187
  return new pagination_1.Page(query, meta, records);
156
188
  });
157
189
  }
158
190
  }
159
191
  exports.RestRepository = RestRepository;
160
- _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;
161
194
  return __awaiter(this, void 0, void 0, function* () {
162
- 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
+ }
163
200
  return {
164
201
  fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
165
- apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
202
+ apiKey,
166
203
  apiUrl: '',
167
204
  // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
168
205
  workspacesApiUrl: (path, params) => {
@@ -174,109 +211,179 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
174
211
  }
175
212
  };
176
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
+ });
243
+ }, _RestRepository_insertRecordWithoutId = function _RestRepository_insertRecordWithoutId(object) {
244
+ return __awaiter(this, void 0, void 0, function* () {
245
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
246
+ const record = transformObjectLinks(object);
247
+ const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
248
+ workspace: '{workspaceId}',
249
+ dbBranchName: '{dbBranch}',
250
+ tableName: __classPrivateFieldGet(this, _RestRepository_table, "f")
251
+ }, body: record }, fetchProps));
252
+ const finalObject = yield this.read(response.id);
253
+ if (!finalObject) {
254
+ throw new Error('The server failed to save the record');
255
+ }
256
+ return finalObject;
257
+ });
258
+ }, _RestRepository_insertRecordWithId = function _RestRepository_insertRecordWithId(recordId, object) {
259
+ return __awaiter(this, void 0, void 0, function* () {
260
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
261
+ const record = transformObjectLinks(object);
262
+ const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
263
+ workspace: '{workspaceId}',
264
+ dbBranchName: '{dbBranch}',
265
+ tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
266
+ recordId
267
+ }, body: record, queryParams: { createOnly: true } }, fetchProps));
268
+ const finalObject = yield this.read(response.id);
269
+ if (!finalObject) {
270
+ throw new Error('The server failed to save the record');
271
+ }
272
+ return finalObject;
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;
177
335
  };
178
336
  class RestRespositoryFactory {
179
- createRepository(client, table) {
180
- return new RestRepository(client, table);
337
+ createRepository(client, table, links) {
338
+ return new RestRepository(client, table, links);
181
339
  }
182
340
  }
183
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
+ }
184
353
  class BaseClient {
185
- constructor(options, links = {}) {
186
- _BaseClient_links.set(this, void 0);
187
- _BaseClient_branch.set(this, void 0);
188
- if (!options.databaseURL || !options.apiKey || !options.branch) {
189
- throw new Error('Options databaseURL, apiKey and branch are required');
190
- }
191
- this.options = options;
192
- __classPrivateFieldSet(this, _BaseClient_links, links, "f");
193
- 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();
194
359
  this.db = new Proxy({}, {
195
360
  get: (_target, prop) => {
196
- if (typeof prop !== 'string')
361
+ if (!(0, lang_1.isString)(prop))
197
362
  throw new Error('Invalid table name');
198
- return factory.createRepository(this, prop);
363
+ return factory.createRepository(this, prop, links);
199
364
  }
200
365
  });
201
366
  }
202
- initObject(table, object) {
203
- const o = {};
204
- Object.assign(o, object);
205
- const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
206
- for (const link of tableLinks) {
207
- const [field, linkTable] = link;
208
- const value = o[field];
209
- if (value && typeof value === 'object') {
210
- const { id } = value;
211
- if (Object.keys(value).find((col) => col === 'id')) {
212
- o[field] = this.initObject(linkTable, value);
213
- }
214
- else if (id) {
215
- o[field] = {
216
- id,
217
- get: () => {
218
- this.db[linkTable].read(id);
219
- }
220
- };
221
- }
222
- }
223
- }
224
- const db = this.db;
225
- o.read = function () {
226
- return db[table].read(o['id']);
227
- };
228
- o.update = function (data) {
229
- return db[table].update(o['id'], data);
230
- };
231
- o.delete = function () {
232
- return db[table].delete(o['id']);
233
- };
234
- for (const prop of ['read', 'update', 'delete']) {
235
- Object.defineProperty(o, prop, { enumerable: false });
236
- }
237
- // TODO: links and rev links
238
- Object.freeze(o);
239
- return o;
240
- }
241
- getBranch() {
242
- var e_1, _a;
367
+ search(query, options) {
368
+ var _a;
243
369
  return __awaiter(this, void 0, void 0, function* () {
244
- if (__classPrivateFieldGet(this, _BaseClient_branch, "f"))
245
- return __classPrivateFieldGet(this, _BaseClient_branch, "f");
246
- const { branch: param } = this.options;
247
- const strategies = Array.isArray(param) ? [...param] : [param];
248
- const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
249
- return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy;
250
- });
251
- try {
252
- for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
253
- const strategy = strategies_1_1.value;
254
- const branch = yield evaluateBranch(strategy);
255
- if (branch) {
256
- __classPrivateFieldSet(this, _BaseClient_branch, branch, "f");
257
- return branch;
258
- }
259
- }
260
- }
261
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
262
- finally {
263
- try {
264
- if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
265
- }
266
- finally { if (e_1) throw e_1.error; }
267
- }
268
- 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);
269
374
  });
270
375
  }
271
376
  }
272
377
  exports.BaseClient = BaseClient;
273
- _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
274
378
  const isBranchStrategyBuilder = (strategy) => {
275
379
  return typeof strategy === 'function';
276
380
  };
277
- // TODO: We can find a better implementation for links
278
381
  const transformObjectLinks = (object) => {
279
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
280
387
  return Object.assign(Object.assign({}, acc), { [key]: (0, record_1.isIdentifiable)(value) ? value.id : value });
281
388
  }, {});
282
389
  };
@@ -1,28 +1,25 @@
1
1
  import { If, IsArray, IsObject, StringKeys, UnionToIntersection, Values } from '../util/types';
2
- import { XataRecord } from './record';
2
+ import { Link, XataRecord } from './record';
3
3
  export declare type SelectableColumn<O, RecursivePath extends any[] = []> = '*' | 'id' | DataProps<O> | NestedColumns<O, RecursivePath>;
4
- export declare type SelectedRecordPick<O extends XataRecord, Key extends SelectableColumn<O>[]> = InternalSelectedPick<O, Key, true> extends XataRecord ? InternalSelectedPick<O, Key, true> : XataRecord;
5
- 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<V extends SelectableColumn<O[K]> ? {
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]> ? {
6
8
  V: ValueAtColumn<O[K], V>;
7
- } : never> : never : never;
9
+ } : never) : O[K]> : never : never;
8
10
  declare type MAX_RECURSION = 5;
9
11
  declare type NestedColumns<O, RecursivePath extends any[]> = RecursivePath['length'] extends MAX_RECURSION ? never : If<IsObject<O>, Values<{
10
- [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
11
- If<IsObject<NonNullable<O[K]>>, SelectableColumn<NonNullable<O[K]>, [...RecursivePath, O[K]]> extends string ? `${K}` | `${K}.${SelectableColumn<O[K], [...RecursivePath, O[K]]>}` : never, K>>;
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>>;
12
15
  }>, never>;
13
16
  declare type DataProps<O> = Exclude<StringKeys<O>, StringKeys<XataRecord>>;
14
- declare type InternalSelectedPick<O extends XataRecord, Key extends SelectableColumn<O>[], IncludeRecord> = UnionToIntersection<Values<{
15
- [K in Key[number]]: NestedValueAtColumn<O, K, IncludeRecord> & ExtraProperties<O, IncludeRecord>;
16
- }>>;
17
- declare type ExtraProperties<O, IncludeRecord> = O extends XataRecord ? IncludeRecord extends true ? XataRecord : {
18
- id?: string;
19
- } : never;
20
- declare type NestedValueAtColumn<O, Key extends SelectableColumn<O>, IncludeRecord> = Key extends `${infer N}.${infer M}` ? N extends DataProps<O> ? {
21
- [K in N]: M extends SelectableColumn<O[K]> ? // @ts-ignore: M does not infer the correct type, probably a TS bug...
22
- NestedValueAtColumn<NonNullable<O[K]>, M, IncludeRecord> & ExtraProperties<XataRecord, IncludeRecord> : unknown;
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;
23
19
  } : unknown : Key extends DataProps<O> ? {
24
- [K in Key]: O[K];
20
+ [K in Key]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], SelectedPick<NonNullable<O[K]>, ['*']>> : O[K];
25
21
  } : Key extends '*' ? {
26
- [K in IncludeRecord extends true ? keyof NonNullable<O> : Exclude<keyof NonNullable<O>, keyof XataRecord>]: NonNullable<NonNullable<O>[K]> extends XataRecord ? ExtraProperties<XataRecord, IncludeRecord> : NonNullable<O>[K];
22
+ [K in StringKeys<O>]: NonNullable<O[K]> extends XataRecord ? ForwardNullable<O[K], Link<NonNullable<O[K]>>> : O[K];
27
23
  } : unknown;
24
+ declare type ForwardNullable<T, R> = T extends NonNullable<T> ? R : R | null;
28
25
  export {};
@@ -0,0 +1 @@
1
+ export {};