@xata.io/client 0.5.0 → 0.7.0

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 +33 -0
  3. package/dist/api/client.d.ts +2 -2
  4. package/dist/api/client.js +12 -9
  5. package/dist/api/components.d.ts +27 -31
  6. package/dist/api/components.js +27 -31
  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 +17 -27
  20. package/dist/schema/operators.js +1 -14
  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 +208 -111
  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 +2 -2
@@ -26,20 +26,24 @@ var __asyncValues = (this && this.__asyncValues) || function (o) {
26
26
  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
27
27
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
28
  };
29
- var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _BaseClient_links, _BaseClient_branch;
29
+ var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _RestRepository_bulkInsertTableRecords, _RestRepository_updateRecordWithID, _RestRepository_upsertRecordWithID, _RestRepository_deleteRecord, _BaseClient_links, _BaseClient_branch;
30
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
31
  exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
32
32
  const api_1 = require("../api");
33
- const filters_1 = require("./filters");
33
+ const fetch_1 = require("../util/fetch");
34
+ const lang_1 = require("../util/lang");
35
+ const config_1 = require("./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
48
  super(null, table, {});
45
49
  _RestRepository_instances.add(this);
@@ -48,116 +52,144 @@ class RestRepository extends Repository {
48
52
  _RestRepository_table.set(this, void 0);
49
53
  __classPrivateFieldSet(this, _RestRepository_client, client, "f");
50
54
  __classPrivateFieldSet(this, _RestRepository_table, table, "f");
51
- // TODO: Remove when integrating with API client
52
- const fetchImpl = typeof fetch !== 'undefined' ? fetch : __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch;
53
- if (!fetchImpl) {
54
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
55
- }
56
- __classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f");
55
+ __classPrivateFieldSet(this, _RestRepository_fetch, (0, fetch_1.getFetchImplementation)(__classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch), "f");
57
56
  }
58
- create(object) {
57
+ create(a, b) {
59
58
  return __awaiter(this, void 0, void 0, function* () {
60
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
61
- const record = transformObjectLinks(object);
62
- const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: {
63
- workspace: '{workspaceId}',
64
- dbBranchName: '{dbBranch}',
65
- tableName: __classPrivateFieldGet(this, _RestRepository_table, "f")
66
- }, body: record }, fetchProps));
67
- const finalObject = yield this.read(response.id);
68
- if (!finalObject) {
69
- 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);
70
62
  }
71
- return finalObject;
72
- });
73
- }
74
- createMany(objects) {
75
- return __awaiter(this, void 0, void 0, function* () {
76
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
77
- const records = objects.map((object) => transformObjectLinks(object));
78
- const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
79
- const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
80
- if (finalObjects.length !== objects.length) {
81
- 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);
68
+ }
69
+ // Create one record with id as property
70
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
71
+ if (a.id === '')
72
+ throw new Error("The id can't be empty");
73
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
82
74
  }
83
- return finalObjects;
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');
84
80
  });
85
81
  }
82
+ // TODO: Add column support: https://github.com/xataio/openapi/issues/139
86
83
  read(recordId) {
87
84
  return __awaiter(this, void 0, void 0, function* () {
88
85
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
89
- const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
90
- return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
91
- });
92
- }
93
- update(recordId, object) {
94
- return __awaiter(this, void 0, void 0, function* () {
95
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
96
- const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
97
- const item = yield this.read(response.id);
98
- if (!item)
99
- throw new Error('The server failed to save the record');
100
- 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
+ }
101
96
  });
102
97
  }
103
- insert(recordId, object) {
98
+ update(a, b) {
104
99
  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.insertRecordWithID)(Object.assign({ pathParams: {
108
- workspace: '{workspaceId}',
109
- dbBranchName: '{dbBranch}',
110
- tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
111
- recordId
112
- }, body: record }, fetchProps));
113
- const finalObject = yield this.read(response.id);
114
- if (!finalObject) {
115
- 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 }));
116
115
  }
117
- return finalObject;
116
+ throw new Error('Invalid arguments for update method');
118
117
  });
119
118
  }
120
- updateOrInsert(recordId, object) {
119
+ createOrUpdate(a, b) {
121
120
  return __awaiter(this, void 0, void 0, function* () {
122
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
123
- const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
124
- const item = yield this.read(response.id);
125
- if (!item)
126
- throw new Error('The server failed to save the record');
127
- 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');
128
138
  });
129
139
  }
130
140
  delete(recordId) {
131
141
  return __awaiter(this, void 0, void 0, function* () {
132
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
133
- 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');
134
162
  });
135
163
  }
136
- query(query, options = {}) {
137
- var _a, _b, _c;
164
+ query(query) {
165
+ var _a;
138
166
  return __awaiter(this, void 0, void 0, function* () {
139
167
  const data = query.getQueryOptions();
140
168
  const body = {
141
- filter: Object.values(data.filter).some(Boolean) ? data.filter : undefined,
142
- sort: (_a = (0, filters_1.buildSortFilter)(options === null || options === void 0 ? void 0 : options.sort)) !== null && _a !== void 0 ? _a : data.sort,
143
- page: (_b = options === null || options === void 0 ? void 0 : options.page) !== null && _b !== void 0 ? _b : data.page,
144
- 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
145
173
  };
146
174
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
147
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));
148
176
  const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record));
149
- // TODO: We should properly type this any
150
177
  return new pagination_1.Page(query, meta, records);
151
178
  });
152
179
  }
153
180
  }
154
181
  exports.RestRepository = RestRepository;
155
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;
156
184
  return __awaiter(this, void 0, void 0, function* () {
157
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
+ }
158
190
  return {
159
191
  fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
160
- apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
192
+ apiKey,
161
193
  apiUrl: '',
162
194
  // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
163
195
  workspacesApiUrl: (path, params) => {
@@ -169,6 +201,72 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
169
201
  }
170
202
  };
171
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
+ });
172
270
  };
173
271
  class RestRespositoryFactory {
174
272
  createRepository(client, table) {
@@ -176,16 +274,31 @@ class RestRespositoryFactory {
176
274
  }
177
275
  }
178
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
+ }
179
293
  class BaseClient {
180
- constructor(options, links = {}) {
294
+ constructor(options = {}, links = {}) {
181
295
  _BaseClient_links.set(this, void 0);
182
296
  _BaseClient_branch.set(this, void 0);
183
- if (!options.databaseURL || !options.apiKey || !options.branch) {
184
- throw new Error('Options databaseURL, apiKey and branch are required');
185
- }
186
- 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 });
187
300
  __classPrivateFieldSet(this, _BaseClient_links, links, "f");
188
- const factory = options.repositoryFactory || new RestRespositoryFactory();
301
+ const factory = this.options.repositoryFactory || new RestRespositoryFactory();
189
302
  this.db = new Proxy({}, {
190
303
  get: (_target, prop) => {
191
304
  if (typeof prop !== 'string')
@@ -195,43 +308,31 @@ class BaseClient {
195
308
  });
196
309
  }
197
310
  initObject(table, object) {
198
- const o = {};
199
- Object.assign(o, object);
311
+ const result = {};
312
+ Object.assign(result, object);
200
313
  const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
201
314
  for (const link of tableLinks) {
202
315
  const [field, linkTable] = link;
203
- const value = o[field];
204
- if (value && typeof value === 'object') {
205
- const { id } = value;
206
- if (Object.keys(value).find((col) => col === 'id')) {
207
- o[field] = this.initObject(linkTable, value);
208
- }
209
- else if (id) {
210
- o[field] = {
211
- id,
212
- get: () => {
213
- this.db[linkTable].read(id);
214
- }
215
- };
216
- }
316
+ const value = result[field];
317
+ if (value && (0, lang_1.isObject)(value)) {
318
+ result[field] = this.initObject(linkTable, value);
217
319
  }
218
320
  }
219
321
  const db = this.db;
220
- o.read = function () {
221
- return db[table].read(o['id']);
322
+ result.read = function () {
323
+ return db[table].read(result['id']);
222
324
  };
223
- o.update = function (data) {
224
- return db[table].update(o['id'], data);
325
+ result.update = function (data) {
326
+ return db[table].update(result['id'], data);
225
327
  };
226
- o.delete = function () {
227
- return db[table].delete(o['id']);
328
+ result.delete = function () {
329
+ return db[table].delete(result['id']);
228
330
  };
229
331
  for (const prop of ['read', 'update', 'delete']) {
230
- Object.defineProperty(o, prop, { enumerable: false });
332
+ Object.defineProperty(result, prop, { enumerable: false });
231
333
  }
232
- // TODO: links and rev links
233
- Object.freeze(o);
234
- return o;
334
+ Object.freeze(result);
335
+ return result;
235
336
  }
236
337
  getBranch() {
237
338
  var e_1, _a;
@@ -269,12 +370,8 @@ _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
269
370
  const isBranchStrategyBuilder = (strategy) => {
270
371
  return typeof strategy === 'function';
271
372
  };
272
- // TODO: We can find a better implementation for links
273
373
  const transformObjectLinks = (object) => {
274
374
  return Object.entries(object).reduce((acc, [key, value]) => {
275
- if (value && typeof value === 'object' && typeof value.id === 'string') {
276
- return Object.assign(Object.assign({}, acc), { [key]: value.id });
277
- }
278
- return Object.assign(Object.assign({}, acc), { [key]: value });
375
+ return Object.assign(Object.assign({}, acc), { [key]: (0, record_1.isIdentifiable)(value) ? value.id : value });
279
376
  }, {});
280
377
  };
@@ -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 {};