@xata.io/client 0.2.2 → 0.3.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 (44) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api/client.d.ts +95 -0
  3. package/dist/api/client.js +235 -0
  4. package/dist/api/components.d.ts +1440 -0
  5. package/dist/api/components.js +1001 -0
  6. package/dist/api/fetcher.d.ts +25 -0
  7. package/dist/api/fetcher.js +78 -0
  8. package/dist/api/index.d.ts +7 -0
  9. package/dist/api/index.js +21 -0
  10. package/dist/api/parameters.d.ts +16 -0
  11. package/dist/api/parameters.js +2 -0
  12. package/dist/api/providers.d.ts +8 -0
  13. package/dist/api/providers.js +29 -0
  14. package/dist/api/responses.d.ts +44 -0
  15. package/dist/api/responses.js +2 -0
  16. package/dist/api/schemas.d.ts +311 -0
  17. package/dist/api/schemas.js +2 -0
  18. package/dist/index.d.ts +2 -133
  19. package/dist/index.js +16 -368
  20. package/dist/schema/filters.d.ts +20 -0
  21. package/dist/schema/filters.js +24 -0
  22. package/dist/schema/index.d.ts +5 -0
  23. package/dist/schema/index.js +25 -0
  24. package/dist/schema/operators.d.ts +72 -0
  25. package/dist/schema/operators.js +91 -0
  26. package/dist/schema/pagination.d.ts +79 -0
  27. package/dist/schema/pagination.js +90 -0
  28. package/dist/schema/query.d.ts +114 -0
  29. package/dist/schema/query.js +227 -0
  30. package/dist/schema/record.d.ts +36 -0
  31. package/dist/schema/record.js +2 -0
  32. package/dist/schema/repository.d.ts +109 -0
  33. package/dist/schema/repository.js +273 -0
  34. package/dist/schema/selection.d.ts +13 -0
  35. package/dist/schema/selection.js +2 -0
  36. package/dist/util/lang.d.ts +2 -0
  37. package/dist/util/lang.js +10 -0
  38. package/dist/util/types.d.ts +3 -0
  39. package/dist/util/types.js +2 -0
  40. package/package.json +3 -3
  41. package/dist/index.test.d.ts +0 -1
  42. package/dist/index.test.js +0 -304
  43. package/src/index.test.ts +0 -392
  44. package/src/index.ts +0 -506
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
23
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
24
+ var m = o[Symbol.asyncIterator], i;
25
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
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
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
+ };
29
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
30
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
31
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
32
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
33
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
34
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
35
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
36
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
37
+ function fulfill(value) { resume("next", value); }
38
+ function reject(value) { resume("throw", value); }
39
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
40
+ };
41
+ var _Query_table, _Query_repository, _Query_data;
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.Query = void 0;
44
+ const lang_1 = require("../util/lang");
45
+ /**
46
+ * Query objects contain the information of all filters, sorting, etc. to be included in the database query.
47
+ *
48
+ * Query objects are immutable. Any method that adds more constraints or options to the query will return
49
+ * a new Query object containing the both the previous and the new constraints and options.
50
+ */
51
+ class Query {
52
+ constructor(repository, table, data, parent) {
53
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
54
+ _Query_table.set(this, void 0);
55
+ _Query_repository.set(this, void 0);
56
+ _Query_data.set(this, { filter: {} });
57
+ // Implements pagination
58
+ this.meta = { page: { cursor: 'start', more: true } };
59
+ this.records = [];
60
+ __classPrivateFieldSet(this, _Query_table, table, "f");
61
+ if (repository) {
62
+ __classPrivateFieldSet(this, _Query_repository, repository, "f");
63
+ }
64
+ else {
65
+ __classPrivateFieldSet(this, _Query_repository, this, "f");
66
+ }
67
+ __classPrivateFieldGet(this, _Query_data, "f").filter.$any = (_b = (_a = data.filter) === null || _a === void 0 ? void 0 : _a.$any) !== null && _b !== void 0 ? _b : (_c = parent === null || parent === void 0 ? void 0 : parent.filter) === null || _c === void 0 ? void 0 : _c.$any;
68
+ __classPrivateFieldGet(this, _Query_data, "f").filter.$all = (_e = (_d = data.filter) === null || _d === void 0 ? void 0 : _d.$all) !== null && _e !== void 0 ? _e : (_f = parent === null || parent === void 0 ? void 0 : parent.filter) === null || _f === void 0 ? void 0 : _f.$all;
69
+ __classPrivateFieldGet(this, _Query_data, "f").filter.$not = (_h = (_g = data.filter) === null || _g === void 0 ? void 0 : _g.$not) !== null && _h !== void 0 ? _h : (_j = parent === null || parent === void 0 ? void 0 : parent.filter) === null || _j === void 0 ? void 0 : _j.$not;
70
+ __classPrivateFieldGet(this, _Query_data, "f").filter.$none = (_l = (_k = data.filter) === null || _k === void 0 ? void 0 : _k.$none) !== null && _l !== void 0 ? _l : (_m = parent === null || parent === void 0 ? void 0 : parent.filter) === null || _m === void 0 ? void 0 : _m.$none;
71
+ __classPrivateFieldGet(this, _Query_data, "f").sort = (_o = data.sort) !== null && _o !== void 0 ? _o : parent === null || parent === void 0 ? void 0 : parent.sort;
72
+ __classPrivateFieldGet(this, _Query_data, "f").columns = (_q = (_p = data.columns) !== null && _p !== void 0 ? _p : parent === null || parent === void 0 ? void 0 : parent.columns) !== null && _q !== void 0 ? _q : ['*'];
73
+ this.any = this.any.bind(this);
74
+ this.all = this.all.bind(this);
75
+ this.not = this.not.bind(this);
76
+ this.filter = this.filter.bind(this);
77
+ this.sort = this.sort.bind(this);
78
+ this.none = this.none.bind(this);
79
+ Object.defineProperty(this, 'table', { enumerable: false });
80
+ Object.defineProperty(this, 'repository', { enumerable: false });
81
+ }
82
+ getQueryOptions() {
83
+ return __classPrivateFieldGet(this, _Query_data, "f");
84
+ }
85
+ /**
86
+ * Builds a new query object representing a logical OR between the given subqueries.
87
+ * @param queries An array of subqueries.
88
+ * @returns A new Query object.
89
+ */
90
+ any(...queries) {
91
+ const $any = queries.map((query) => query.getQueryOptions().filter);
92
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $any } }, __classPrivateFieldGet(this, _Query_data, "f"));
93
+ }
94
+ /**
95
+ * Builds a new query object representing a logical AND between the given subqueries.
96
+ * @param queries An array of subqueries.
97
+ * @returns A new Query object.
98
+ */
99
+ all(...queries) {
100
+ const $all = queries.map((query) => query.getQueryOptions().filter);
101
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f"));
102
+ }
103
+ /**
104
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
105
+ * @param queries An array of subqueries.
106
+ * @returns A new Query object.
107
+ */
108
+ not(...queries) {
109
+ const $not = queries.map((query) => query.getQueryOptions().filter);
110
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $not } }, __classPrivateFieldGet(this, _Query_data, "f"));
111
+ }
112
+ /**
113
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
114
+ * @param queries An array of subqueries.
115
+ * @returns A new Query object.
116
+ */
117
+ none(...queries) {
118
+ const $none = queries.map((query) => query.getQueryOptions().filter);
119
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $none } }, __classPrivateFieldGet(this, _Query_data, "f"));
120
+ }
121
+ filter(a, b) {
122
+ if (arguments.length === 1) {
123
+ const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
124
+ const $all = (0, lang_1.compact)([__classPrivateFieldGet(this, _Query_data, "f").filter.$all].flat().concat(constraints));
125
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f"));
126
+ }
127
+ else {
128
+ const column = a;
129
+ const value = b;
130
+ const $all = (0, lang_1.compact)([__classPrivateFieldGet(this, _Query_data, "f").filter.$all].flat().concat({ [column]: value }));
131
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f"));
132
+ }
133
+ }
134
+ /**
135
+ * Builds a new query with a new sort option.
136
+ * @param column The column name.
137
+ * @param direction The direction. Either ascending or descending.
138
+ * @returns A new Query object.
139
+ */
140
+ sort(column, direction) {
141
+ const sort = Object.assign(Object.assign({}, __classPrivateFieldGet(this, _Query_data, "f").sort), { [column]: direction });
142
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { sort }, __classPrivateFieldGet(this, _Query_data, "f"));
143
+ }
144
+ /**
145
+ * Builds a new query specifying the set of columns to be returned in the query response.
146
+ * @param columns Array of column names to be returned by the query.
147
+ * @returns A new Query object.
148
+ */
149
+ select(columns) {
150
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { columns }, __classPrivateFieldGet(this, _Query_data, "f"));
151
+ }
152
+ getPaginated(options = {}) {
153
+ return __classPrivateFieldGet(this, _Query_repository, "f").query(this, options);
154
+ }
155
+ [(_Query_table = new WeakMap(), _Query_repository = new WeakMap(), _Query_data = new WeakMap(), Symbol.asyncIterator)]() {
156
+ return __asyncGenerator(this, arguments, function* _a() {
157
+ var e_1, _b;
158
+ try {
159
+ for (var _c = __asyncValues(this.getIterator(1)), _d; _d = yield __await(_c.next()), !_d.done;) {
160
+ const [record] = _d.value;
161
+ yield yield __await(record);
162
+ }
163
+ }
164
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
165
+ finally {
166
+ try {
167
+ if (_d && !_d.done && (_b = _c.return)) yield __await(_b.call(_c));
168
+ }
169
+ finally { if (e_1) throw e_1.error; }
170
+ }
171
+ });
172
+ }
173
+ getIterator(chunk, options = {}) {
174
+ return __asyncGenerator(this, arguments, function* getIterator_1() {
175
+ let offset = 0;
176
+ let end = false;
177
+ while (!end) {
178
+ const { records, meta } = yield __await(this.getPaginated(Object.assign(Object.assign({}, options), { page: { size: chunk, offset } })));
179
+ yield yield __await(records);
180
+ offset += chunk;
181
+ end = !meta.page.more;
182
+ }
183
+ });
184
+ }
185
+ /**
186
+ * Performs the query in the database and returns a set of results.
187
+ * @param options Additional options to be used when performing the query.
188
+ * @returns An array of records from the database.
189
+ */
190
+ getMany(options = {}) {
191
+ return __awaiter(this, void 0, void 0, function* () {
192
+ const { records } = yield this.getPaginated(options);
193
+ return records;
194
+ });
195
+ }
196
+ /**
197
+ * Performs the query in the database and returns the first result.
198
+ * @param options Additional options to be used when performing the query.
199
+ * @returns The first record that matches the query, or null if no record matched the query.
200
+ */
201
+ getOne(options = {}) {
202
+ return __awaiter(this, void 0, void 0, function* () {
203
+ const records = yield this.getMany(Object.assign(Object.assign({}, options), { page: { size: 1 } }));
204
+ return records[0] || null;
205
+ });
206
+ }
207
+ /**async deleteAll(): Promise<number> {
208
+ // TODO: Return number of affected rows
209
+ return 0;
210
+ }**/
211
+ nextPage(size, offset) {
212
+ return this.firstPage(size, offset);
213
+ }
214
+ previousPage(size, offset) {
215
+ return this.firstPage(size, offset);
216
+ }
217
+ firstPage(size, offset) {
218
+ return this.getPaginated({ page: { size, offset } });
219
+ }
220
+ lastPage(size, offset) {
221
+ return this.getPaginated({ page: { size, offset, before: 'end' } });
222
+ }
223
+ hasNextPage() {
224
+ return this.meta.page.more;
225
+ }
226
+ }
227
+ exports.Query = Query;
@@ -0,0 +1,36 @@
1
+ import { Selectable } from './selection';
2
+ /**
3
+ * Represents a persisted record from the database.
4
+ */
5
+ export interface XataRecord {
6
+ /**
7
+ * Unique id of this record.
8
+ */
9
+ id: string;
10
+ /**
11
+ * Metadata of this record.
12
+ */
13
+ xata: {
14
+ /**
15
+ * Number that is increased every time the record is updated.
16
+ */
17
+ version: number;
18
+ };
19
+ /**
20
+ * Retrieves a refreshed copy of the current record from the database.
21
+ */
22
+ read(): Promise<this>;
23
+ /**
24
+ * Performs a partial update of the current record. On success a new object is
25
+ * returned and the current object is not mutated.
26
+ * @param data The columns and their values that have to be updated.
27
+ * @returns A new record containing the latest values for all the columns of the current record.
28
+ */
29
+ update(data: Partial<Selectable<this>>): Promise<this>;
30
+ /**
31
+ * Performs a deletion of the current record in the database.
32
+ *
33
+ * @throws If the record was already deleted or if an error happened while performing the deletion.
34
+ */
35
+ delete(): Promise<void>;
36
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,109 @@
1
+ import { FetchImpl } from '../api/fetcher';
2
+ import { Page } from './pagination';
3
+ import { Query, QueryOptions } from './query';
4
+ import { XataRecord } from './record';
5
+ import { Selectable, SelectableColumn, Select } from './selection';
6
+ export declare type Links = Record<string, Array<string[]>>;
7
+ /**
8
+ * Common interface for performing operations on a table.
9
+ */
10
+ export declare abstract class Repository<T extends XataRecord> extends Query<T> {
11
+ /**
12
+ * Creates a record in the table.
13
+ * @param object Object containing the column names with their values to be stored in the table.
14
+ * @returns The full persisted record.
15
+ */
16
+ abstract create(object: Selectable<T>): Promise<T>;
17
+ /**
18
+ * Creates multiple records in the table.
19
+ * @param objects Array of objects with the column names and the values to be stored in the table.
20
+ * @returns Array of the persisted records.
21
+ */
22
+ abstract createMany(objects: Selectable<T>[]): Promise<T[]>;
23
+ /**
24
+ * Queries a single record from the table given its unique id.
25
+ * @param id The unique id.
26
+ * @returns The persisted record for the given id or null if the record could not be found.
27
+ */
28
+ abstract read(id: string): Promise<T | null>;
29
+ /**
30
+ * Insert a single record with a unique id.
31
+ * @param id The unique id.
32
+ * @param object Object containing the column names with their values to be stored in the table.
33
+ * @returns The full persisted record.
34
+ */
35
+ abstract insert(id: string, object: Selectable<T>): Promise<T>;
36
+ /**
37
+ * Partially update a single record given its unique id.
38
+ * @param id The unique id.
39
+ * @param object The column names and their values that have to be updatd.
40
+ * @returns The full persisted record.
41
+ */
42
+ abstract update(id: string, object: Partial<Selectable<T>>): Promise<T>;
43
+ /**
44
+ * Updates or inserts a single record. If a record exists with the given id,
45
+ * it will be update, otherwise a new record will be created.
46
+ * @param id A unique id.
47
+ * @param object The column names and the values to be persisted.
48
+ * @returns The full persisted record.
49
+ */
50
+ abstract updateOrInsert(id: string, object: Selectable<T>): Promise<T>;
51
+ /**
52
+ * Deletes a record given its unique id.
53
+ * @param id The unique id.
54
+ * @throws If the record could not be found or there was an error while performing the deletion.
55
+ */
56
+ abstract delete(id: string): void;
57
+ abstract query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options: Options): Promise<Page<T, typeof options extends {
58
+ columns: SelectableColumn<T>[];
59
+ } ? Select<T, typeof options['columns'][number]> : R>>;
60
+ }
61
+ export declare class RestRepository<T extends XataRecord> extends Repository<T> {
62
+ #private;
63
+ constructor(client: BaseClient<any>, table: string);
64
+ create(object: Selectable<T>): Promise<T>;
65
+ createMany(objects: T[]): Promise<T[]>;
66
+ read(recordId: string): Promise<T | null>;
67
+ update(recordId: string, object: Partial<Selectable<T>>): Promise<T>;
68
+ insert(recordId: string, object: Selectable<T>): Promise<T>;
69
+ updateOrInsert(recordId: string, object: Selectable<T>): Promise<T>;
70
+ delete(recordId: string): Promise<void>;
71
+ query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options?: Options): Promise<Page<T, typeof options extends {
72
+ columns: SelectableColumn<T>[];
73
+ } ? Select<T, typeof options['columns'][number]> : R>>;
74
+ }
75
+ interface RepositoryFactory {
76
+ createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
77
+ }
78
+ export declare class RestRespositoryFactory implements RepositoryFactory {
79
+ createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
80
+ }
81
+ declare type BranchStrategyValue = string | undefined | null;
82
+ declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
83
+ declare type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder;
84
+ declare type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>;
85
+ export declare type XataClientOptions = {
86
+ /**
87
+ * Fetch implementation. This option is only required if the runtime does not include a fetch implementation
88
+ * available in the global scope. If you are running your code on Deno or Cloudflare workers for example,
89
+ * you won't need to provide a specific fetch implementation. But for most versions of Node.js you'll need
90
+ * to provide one. Such as cross-fetch, node-fetch or isomorphic-fetch.
91
+ */
92
+ fetch?: FetchImpl;
93
+ databaseURL?: string;
94
+ branch: BranchStrategyOption;
95
+ /**
96
+ * API key to be used. You can create one in your account settings at https://app.xata.io/settings.
97
+ */
98
+ apiKey: string;
99
+ repositoryFactory?: RepositoryFactory;
100
+ };
101
+ export declare class BaseClient<D extends Record<string, Repository<any>>> {
102
+ #private;
103
+ options: XataClientOptions;
104
+ db: D;
105
+ constructor(options: XataClientOptions, links?: Links);
106
+ initObject<T>(table: string, object: object): T;
107
+ getBranch(): Promise<string>;
108
+ }
109
+ export {};
@@ -0,0 +1,273 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
23
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
24
+ var m = o[Symbol.asyncIterator], i;
25
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
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
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
+ };
29
+ var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _BaseClient_links, _BaseClient_branch;
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
32
+ const api_1 = require("../api");
33
+ const filters_1 = require("./filters");
34
+ const pagination_1 = require("./pagination");
35
+ const query_1 = require("./query");
36
+ /**
37
+ * Common interface for performing operations on a table.
38
+ */
39
+ class Repository extends query_1.Query {
40
+ }
41
+ exports.Repository = Repository;
42
+ class RestRepository extends Repository {
43
+ constructor(client, table) {
44
+ super(null, table, {});
45
+ _RestRepository_instances.add(this);
46
+ _RestRepository_client.set(this, void 0);
47
+ _RestRepository_fetch.set(this, void 0);
48
+ _RestRepository_table.set(this, void 0);
49
+ __classPrivateFieldSet(this, _RestRepository_client, client, "f");
50
+ __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");
57
+ }
58
+ create(object) {
59
+ 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');
70
+ }
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
+ // TODO: Use filer.$any() to get all the records
80
+ const finalObjects = yield Promise.all(response.recordIDs.map((id) => this.read(id)));
81
+ if (finalObjects.some((object) => !object)) {
82
+ throw new Error('The server failed to save the record');
83
+ }
84
+ return finalObjects;
85
+ });
86
+ }
87
+ read(recordId) {
88
+ return __awaiter(this, void 0, void 0, function* () {
89
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
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_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
92
+ });
93
+ }
94
+ update(recordId, object) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
97
+ const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
98
+ const item = yield this.read(response.id);
99
+ if (!item)
100
+ throw new Error('The server failed to save the record');
101
+ return item;
102
+ });
103
+ }
104
+ insert(recordId, object) {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
107
+ const record = transformObjectLinks(object);
108
+ const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: {
109
+ workspace: '{workspaceId}',
110
+ dbBranchName: '{dbBranch}',
111
+ tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"),
112
+ recordId
113
+ }, body: record }, fetchProps));
114
+ const finalObject = yield this.read(response.id);
115
+ if (!finalObject) {
116
+ throw new Error('The server failed to save the record');
117
+ }
118
+ return finalObject;
119
+ });
120
+ }
121
+ updateOrInsert(recordId, object) {
122
+ return __awaiter(this, void 0, void 0, function* () {
123
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
124
+ const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
125
+ const item = yield this.read(response.id);
126
+ if (!item)
127
+ throw new Error('The server failed to save the record');
128
+ return item;
129
+ });
130
+ }
131
+ delete(recordId) {
132
+ return __awaiter(this, void 0, void 0, function* () {
133
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
134
+ yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
135
+ });
136
+ }
137
+ query(query, options = {}) {
138
+ var _a, _b, _c;
139
+ return __awaiter(this, void 0, void 0, function* () {
140
+ const data = query.getQueryOptions();
141
+ const body = {
142
+ filter: Object.values(data.filter).some(Boolean) ? data.filter : undefined,
143
+ sort: (_a = (0, filters_1.buildSortFilter)(options === null || options === void 0 ? void 0 : options.sort)) !== null && _a !== void 0 ? _a : data.sort,
144
+ page: (_b = options === null || options === void 0 ? void 0 : options.page) !== null && _b !== void 0 ? _b : data.page,
145
+ columns: (_c = options === null || options === void 0 ? void 0 : options.columns) !== null && _c !== void 0 ? _c : data.columns
146
+ };
147
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
148
+ const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body }, fetchProps));
149
+ const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record));
150
+ // TODO: We should properly type this any
151
+ return new pagination_1.Page(query, meta, records);
152
+ });
153
+ }
154
+ }
155
+ exports.RestRepository = RestRepository;
156
+ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
157
+ return __awaiter(this, void 0, void 0, function* () {
158
+ const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
159
+ return {
160
+ fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
161
+ apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
162
+ apiUrl: '',
163
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
164
+ workspacesApiUrl: (path, params) => {
165
+ var _a, _b;
166
+ const baseUrl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.databaseURL) !== null && _a !== void 0 ? _a : '';
167
+ const hasBranch = (_b = params.dbBranchName) !== null && _b !== void 0 ? _b : params.branch;
168
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branch}` : '');
169
+ return baseUrl + newPath;
170
+ }
171
+ };
172
+ });
173
+ };
174
+ class RestRespositoryFactory {
175
+ createRepository(client, table) {
176
+ return new RestRepository(client, table);
177
+ }
178
+ }
179
+ exports.RestRespositoryFactory = RestRespositoryFactory;
180
+ class BaseClient {
181
+ constructor(options, links = {}) {
182
+ _BaseClient_links.set(this, void 0);
183
+ _BaseClient_branch.set(this, void 0);
184
+ if (!options.databaseURL || !options.apiKey || !options.branch) {
185
+ throw new Error('Options databaseURL, apiKey and branch are required');
186
+ }
187
+ this.options = options;
188
+ __classPrivateFieldSet(this, _BaseClient_links, links, "f");
189
+ }
190
+ initObject(table, object) {
191
+ const o = {};
192
+ Object.assign(o, object);
193
+ const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
194
+ for (const link of tableLinks) {
195
+ const [field, linkTable] = link;
196
+ const value = o[field];
197
+ if (value && typeof value === 'object') {
198
+ const { id } = value;
199
+ if (Object.keys(value).find((col) => col === 'id')) {
200
+ o[field] = this.initObject(linkTable, value);
201
+ }
202
+ else if (id) {
203
+ o[field] = {
204
+ id,
205
+ get: () => {
206
+ this.db[linkTable].read(id);
207
+ }
208
+ };
209
+ }
210
+ }
211
+ }
212
+ const db = this.db;
213
+ o.read = function () {
214
+ return db[table].read(o['id']);
215
+ };
216
+ o.update = function (data) {
217
+ return db[table].update(o['id'], data);
218
+ };
219
+ o.delete = function () {
220
+ return db[table].delete(o['id']);
221
+ };
222
+ for (const prop of ['read', 'update', 'delete']) {
223
+ Object.defineProperty(o, prop, { enumerable: false });
224
+ }
225
+ // TODO: links and rev links
226
+ Object.freeze(o);
227
+ return o;
228
+ }
229
+ getBranch() {
230
+ var e_1, _a;
231
+ return __awaiter(this, void 0, void 0, function* () {
232
+ if (__classPrivateFieldGet(this, _BaseClient_branch, "f"))
233
+ return __classPrivateFieldGet(this, _BaseClient_branch, "f");
234
+ const { branch: param } = this.options;
235
+ const strategies = Array.isArray(param) ? [...param] : [param];
236
+ const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
237
+ return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy;
238
+ });
239
+ try {
240
+ for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
241
+ const strategy = strategies_1_1.value;
242
+ const branch = yield evaluateBranch(strategy);
243
+ if (branch) {
244
+ __classPrivateFieldSet(this, _BaseClient_branch, branch, "f");
245
+ return branch;
246
+ }
247
+ }
248
+ }
249
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
250
+ finally {
251
+ try {
252
+ if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
253
+ }
254
+ finally { if (e_1) throw e_1.error; }
255
+ }
256
+ throw new Error('Unable to resolve branch value');
257
+ });
258
+ }
259
+ }
260
+ exports.BaseClient = BaseClient;
261
+ _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
262
+ const isBranchStrategyBuilder = (strategy) => {
263
+ return typeof strategy === 'function';
264
+ };
265
+ // TODO: We can find a better implementation for links
266
+ const transformObjectLinks = (object) => {
267
+ return Object.entries(object).reduce((acc, [key, value]) => {
268
+ if (value && typeof value === 'object' && typeof value.id === 'string') {
269
+ return Object.assign(Object.assign({}, acc), { [key]: value.id });
270
+ }
271
+ return Object.assign(Object.assign({}, acc), { [key]: value });
272
+ }, {});
273
+ };