@xata.io/client 0.5.1 → 0.7.1

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