@xata.io/client 0.0.0-beta.f12621e → 0.0.0-beta.fddf861

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.
@@ -1,43 +1,129 @@
1
- import { XataRecord, Repository } from '..';
2
- import { Constraint, DeepConstraint, FilterConstraints, SortDirection, SortFilter } from './filters';
3
- import { PaginationOptions, BasePage, PaginationQueryMeta, Page } from './pagination';
4
- import { Selectable, SelectableColumn, Select } from './selection';
5
- export declare type QueryOptions<T> = {
1
+ import { ColumnsFilter, FilterExpression, PageConfig, SortExpression } from '../api/schemas';
2
+ import { DeepConstraint, FilterConstraints, SortDirection, SortFilter } from './filters';
3
+ import { Page, Paginable, PaginationOptions, PaginationQueryMeta } from './pagination';
4
+ import { XataRecord } from './record';
5
+ import { Repository } from './repository';
6
+ import { Select, Selectable, SelectableColumn } from './selection';
7
+ export declare type QueryOptions<T extends XataRecord> = {
6
8
  page?: PaginationOptions;
7
- columns?: Array<keyof Selectable<T>>;
9
+ columns?: Extract<keyof Selectable<T>, string>[];
8
10
  sort?: SortFilter<T> | SortFilter<T>[];
9
11
  };
10
- declare type QueryOrConstraint<T extends XataRecord, R extends XataRecord> = Query<T, R> | Constraint<T>;
11
- export declare class Query<T extends XataRecord, R extends XataRecord = T> implements BasePage<T, R> {
12
- table: string;
13
- repository: Repository<T>;
14
- readonly $any?: QueryOrConstraint<T, R>[];
15
- readonly $all?: QueryOrConstraint<T, R>[];
16
- readonly $not?: QueryOrConstraint<T, R>[];
17
- readonly $none?: QueryOrConstraint<T, R>[];
18
- readonly $sort?: Record<string, SortDirection>;
19
- readonly columns: SelectableColumn<T>[];
20
- readonly query: Query<T, R>;
12
+ export declare type QueryTableOptions = {
13
+ filter: FilterExpression;
14
+ sort?: SortExpression;
15
+ page?: PageConfig;
16
+ columns?: ColumnsFilter;
17
+ };
18
+ /**
19
+ * Query objects contain the information of all filters, sorting, etc. to be included in the database query.
20
+ *
21
+ * Query objects are immutable. Any method that adds more constraints or options to the query will return
22
+ * a new Query object containing the both the previous and the new constraints and options.
23
+ */
24
+ export declare class Query<T extends XataRecord, R extends XataRecord = T> implements Paginable<T, R> {
25
+ #private;
21
26
  readonly meta: PaginationQueryMeta;
22
27
  readonly records: R[];
23
- constructor(repository: Repository<T> | null, table: string, data: Partial<Query<T, R>>, parent?: Query<T, R>);
28
+ constructor(repository: Repository<T> | null, table: string, data: Partial<QueryTableOptions>, parent?: Partial<QueryTableOptions>);
29
+ getQueryOptions(): QueryTableOptions;
30
+ /**
31
+ * Builds a new query object representing a logical OR between the given subqueries.
32
+ * @param queries An array of subqueries.
33
+ * @returns A new Query object.
34
+ */
24
35
  any(...queries: Query<T, R>[]): Query<T, R>;
36
+ /**
37
+ * Builds a new query object representing a logical AND between the given subqueries.
38
+ * @param queries An array of subqueries.
39
+ * @returns A new Query object.
40
+ */
25
41
  all(...queries: Query<T, R>[]): Query<T, R>;
42
+ /**
43
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
44
+ * @param queries An array of subqueries.
45
+ * @returns A new Query object.
46
+ */
26
47
  not(...queries: Query<T, R>[]): Query<T, R>;
48
+ /**
49
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
50
+ * @param queries An array of subqueries.
51
+ * @returns A new Query object.
52
+ */
27
53
  none(...queries: Query<T, R>[]): Query<T, R>;
54
+ /**
55
+ * Builds a new query object adding one or more constraints. Examples:
56
+ *
57
+ * ```
58
+ * query.filter("columnName", columnValue)
59
+ * query.filter({
60
+ * "columnName": columnValue
61
+ * })
62
+ * query.filter({
63
+ * "columnName": operator(columnValue) // Use gt, gte, lt, lte, startsWith,...
64
+ * })
65
+ * ```
66
+ *
67
+ * @param constraints
68
+ * @returns A new Query object.
69
+ */
28
70
  filter(constraints: FilterConstraints<T>): Query<T, R>;
29
- filter<F extends keyof T>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>;
71
+ filter<F extends keyof Selectable<T>>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>;
72
+ /**
73
+ * Builds a new query with a new sort option.
74
+ * @param column The column name.
75
+ * @param direction The direction. Either ascending or descending.
76
+ * @returns A new Query object.
77
+ */
30
78
  sort<F extends keyof T>(column: F, direction: SortDirection): Query<T, R>;
31
- getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>;
79
+ /**
80
+ * Builds a new query specifying the set of columns to be returned in the query response.
81
+ * @param columns Array of column names to be returned by the query.
82
+ * @returns A new Query object.
83
+ */
84
+ select<K extends SelectableColumn<T>>(columns: K[]): Query<T, Select<T, K>>;
85
+ getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, GetWithColumnOptions<T, R, typeof options>>>;
32
86
  [Symbol.asyncIterator](): AsyncIterableIterator<R>;
33
- getIterator(chunk: number, options?: Omit<QueryOptions<T>, 'page'>): AsyncGenerator<R[]>;
34
- getMany<Options extends QueryOptions<T>>(options?: Options): Promise<(typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R)[]>;
35
- getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<(typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R) | null>;
36
- deleteAll(): Promise<number>;
87
+ getIterator<Options extends QueryOptions<T>>(chunk: number, options?: Omit<Options, 'page'>): AsyncGenerator<GetWithColumnOptions<T, R, typeof options>[]>;
88
+ /**
89
+ * Performs the query in the database and returns a set of results.
90
+ * @param options Additional options to be used when performing the query.
91
+ * @returns An array of records from the database.
92
+ */
93
+ getMany<Options extends QueryOptions<T>>(options?: Options): Promise<GetWithColumnOptions<T, R, typeof options>[]>;
94
+ /**
95
+ * Performs the query in the database and returns all the results.
96
+ * Warning: If there are a large number of results, this method can have performance implications.
97
+ * @param options Additional options to be used when performing the query.
98
+ * @returns An array of records from the database.
99
+ */
100
+ getAll<Options extends QueryOptions<T>>(chunk?: number, options?: Omit<Options, 'page'>): Promise<GetWithColumnOptions<T, R, typeof options>[]>;
101
+ /**
102
+ * Performs the query in the database and returns the first result.
103
+ * @param options Additional options to be used when performing the query.
104
+ * @returns The first record that matches the query, or null if no record matched the query.
105
+ */
106
+ getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<GetWithColumnOptions<T, R, typeof options> | null>;
107
+ /**async deleteAll(): Promise<number> {
108
+ // TODO: Return number of affected rows
109
+ return 0;
110
+ }**/
37
111
  nextPage(size?: number, offset?: number): Promise<Page<T, R>>;
38
112
  previousPage(size?: number, offset?: number): Promise<Page<T, R>>;
39
113
  firstPage(size?: number, offset?: number): Promise<Page<T, R>>;
40
114
  lastPage(size?: number, offset?: number): Promise<Page<T, R>>;
41
115
  hasNextPage(): boolean;
42
116
  }
117
+ /**
118
+ * Helper type to read options and compute the correct type for the result values
119
+ * T: Original type
120
+ * R: Default destination type
121
+ * Options: QueryOptions
122
+ *
123
+ * If the columns are overriden in the options, the result type is the pick of the original type and the columns
124
+ * If the columns are not overriden, the result type is the default destination type
125
+ */
126
+ declare type GetWithColumnOptions<T, R, Options> = Options extends {
127
+ columns: SelectableColumn<T>[];
128
+ } ? Select<T, Options['columns'][number]> : R;
43
129
  export {};
@@ -8,6 +8,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
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
+ };
11
22
  var __asyncValues = (this && this.__asyncValues) || function (o) {
12
23
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
24
  var m = o[Symbol.asyncIterator], i;
@@ -27,32 +38,39 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar
27
38
  function reject(value) { resume("throw", value); }
28
39
  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
29
40
  };
41
+ var _Query_table, _Query_repository, _Query_data;
30
42
  Object.defineProperty(exports, "__esModule", { value: true });
31
43
  exports.Query = void 0;
44
+ const lang_1 = require("../util/lang");
45
+ const pagination_1 = require("./pagination");
46
+ /**
47
+ * Query objects contain the information of all filters, sorting, etc. to be included in the database query.
48
+ *
49
+ * Query objects are immutable. Any method that adds more constraints or options to the query will return
50
+ * a new Query object containing the both the previous and the new constraints and options.
51
+ */
32
52
  class Query {
33
53
  constructor(repository, table, data, parent) {
34
- this.columns = ['*'];
35
- // Cursor pagination
36
- this.query = this;
54
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
55
+ _Query_table.set(this, void 0);
56
+ _Query_repository.set(this, void 0);
57
+ _Query_data.set(this, { filter: {} });
58
+ // Implements pagination
37
59
  this.meta = { page: { cursor: 'start', more: true } };
38
60
  this.records = [];
61
+ __classPrivateFieldSet(this, _Query_table, table, "f");
39
62
  if (repository) {
40
- this.repository = repository;
63
+ __classPrivateFieldSet(this, _Query_repository, repository, "f");
41
64
  }
42
65
  else {
43
- this.repository = this;
66
+ __classPrivateFieldSet(this, _Query_repository, this, "f");
44
67
  }
45
- this.table = table;
46
- // For some reason Object.assign(this, parent) didn't work in this case
47
- // so doing all this manually:
48
- this.$any = parent === null || parent === void 0 ? void 0 : parent.$any;
49
- this.$all = parent === null || parent === void 0 ? void 0 : parent.$all;
50
- this.$not = parent === null || parent === void 0 ? void 0 : parent.$not;
51
- this.$none = parent === null || parent === void 0 ? void 0 : parent.$none;
52
- this.$sort = parent === null || parent === void 0 ? void 0 : parent.$sort;
53
- Object.assign(this, data);
54
- // These bindings are used to support deconstructing
55
- // const { any, not, filter, sort } = xata.users.query()
68
+ __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;
69
+ __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;
70
+ __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;
71
+ __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;
72
+ __classPrivateFieldGet(this, _Query_data, "f").sort = (_o = data.sort) !== null && _o !== void 0 ? _o : parent === null || parent === void 0 ? void 0 : parent.sort;
73
+ __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 : ['*'];
56
74
  this.any = this.any.bind(this);
57
75
  this.all = this.all.bind(this);
58
76
  this.not = this.not.bind(this);
@@ -62,58 +80,80 @@ class Query {
62
80
  Object.defineProperty(this, 'table', { enumerable: false });
63
81
  Object.defineProperty(this, 'repository', { enumerable: false });
64
82
  }
65
- any(...queries) {
66
- return new Query(this.repository, this.table, {
67
- $any: (this.$any || []).concat(queries)
68
- }, this);
83
+ getQueryOptions() {
84
+ return __classPrivateFieldGet(this, _Query_data, "f");
69
85
  }
86
+ /**
87
+ * Builds a new query object representing a logical OR between the given subqueries.
88
+ * @param queries An array of subqueries.
89
+ * @returns A new Query object.
90
+ */
91
+ any(...queries) {
92
+ const $any = queries.map((query) => query.getQueryOptions().filter);
93
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $any } }, __classPrivateFieldGet(this, _Query_data, "f"));
94
+ }
95
+ /**
96
+ * Builds a new query object representing a logical AND between the given subqueries.
97
+ * @param queries An array of subqueries.
98
+ * @returns A new Query object.
99
+ */
70
100
  all(...queries) {
71
- return new Query(this.repository, this.table, {
72
- $all: (this.$all || []).concat(queries)
73
- }, this);
74
- }
101
+ const $all = queries.map((query) => query.getQueryOptions().filter);
102
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f"));
103
+ }
104
+ /**
105
+ * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
106
+ * @param queries An array of subqueries.
107
+ * @returns A new Query object.
108
+ */
75
109
  not(...queries) {
76
- return new Query(this.repository, this.table, {
77
- $not: (this.$not || []).concat(queries)
78
- }, this);
79
- }
110
+ const $not = queries.map((query) => query.getQueryOptions().filter);
111
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $not } }, __classPrivateFieldGet(this, _Query_data, "f"));
112
+ }
113
+ /**
114
+ * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
115
+ * @param queries An array of subqueries.
116
+ * @returns A new Query object.
117
+ */
80
118
  none(...queries) {
81
- return new Query(this.repository, this.table, {
82
- $none: (this.$none || []).concat(queries)
83
- }, this);
119
+ const $none = queries.map((query) => query.getQueryOptions().filter);
120
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $none } }, __classPrivateFieldGet(this, _Query_data, "f"));
84
121
  }
85
122
  filter(a, b) {
86
123
  if (arguments.length === 1) {
87
- const constraints = a;
88
- const queries = [];
89
- for (const [column, constraint] of Object.entries(constraints)) {
90
- queries.push({ [column]: constraint });
91
- }
92
- return new Query(this.repository, this.table, {
93
- $all: (this.$all || []).concat(queries)
94
- }, this);
124
+ const constraints = Object.entries(a).map(([column, constraint]) => ({ [column]: constraint }));
125
+ const $all = (0, lang_1.compact)([__classPrivateFieldGet(this, _Query_data, "f").filter.$all].flat().concat(constraints));
126
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f"));
95
127
  }
96
128
  else {
97
129
  const column = a;
98
130
  const value = b;
99
- return new Query(this.repository, this.table, {
100
- $all: (this.$all || []).concat({ [column]: value })
101
- }, this);
131
+ const $all = (0, lang_1.compact)([__classPrivateFieldGet(this, _Query_data, "f").filter.$all].flat().concat({ [column]: value }));
132
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f"));
102
133
  }
103
134
  }
135
+ /**
136
+ * Builds a new query with a new sort option.
137
+ * @param column The column name.
138
+ * @param direction The direction. Either ascending or descending.
139
+ * @returns A new Query object.
140
+ */
104
141
  sort(column, direction) {
105
- const sort = Object.assign(Object.assign({}, this.$sort), { [column]: direction });
106
- const q = new Query(this.repository, this.table, {
107
- $sort: sort
108
- }, this);
109
- return q;
142
+ const sort = Object.assign(Object.assign({}, __classPrivateFieldGet(this, _Query_data, "f").sort), { [column]: direction });
143
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { sort }, __classPrivateFieldGet(this, _Query_data, "f"));
144
+ }
145
+ /**
146
+ * Builds a new query specifying the set of columns to be returned in the query response.
147
+ * @param columns Array of column names to be returned by the query.
148
+ * @returns A new Query object.
149
+ */
150
+ select(columns) {
151
+ return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { columns }, __classPrivateFieldGet(this, _Query_data, "f"));
110
152
  }
111
153
  getPaginated(options = {}) {
112
- return __awaiter(this, void 0, void 0, function* () {
113
- return this.repository._runQuery(this, options);
114
- });
154
+ return __classPrivateFieldGet(this, _Query_repository, "f").query(this, options);
115
155
  }
116
- [Symbol.asyncIterator]() {
156
+ [(_Query_table = new WeakMap(), _Query_repository = new WeakMap(), _Query_data = new WeakMap(), Symbol.asyncIterator)]() {
117
157
  return __asyncGenerator(this, arguments, function* _a() {
118
158
  var e_1, _b;
119
159
  try {
@@ -143,43 +183,69 @@ class Query {
143
183
  }
144
184
  });
145
185
  }
186
+ /**
187
+ * Performs the query in the database and returns a set of results.
188
+ * @param options Additional options to be used when performing the query.
189
+ * @returns An array of records from the database.
190
+ */
146
191
  getMany(options = {}) {
147
192
  return __awaiter(this, void 0, void 0, function* () {
148
193
  const { records } = yield this.getPaginated(options);
149
194
  return records;
150
195
  });
151
196
  }
152
- getOne(options = {}) {
197
+ /**
198
+ * Performs the query in the database and returns all the results.
199
+ * Warning: If there are a large number of results, this method can have performance implications.
200
+ * @param options Additional options to be used when performing the query.
201
+ * @returns An array of records from the database.
202
+ */
203
+ getAll(chunk = pagination_1.PAGINATION_MAX_SIZE, options = {}) {
204
+ var e_2, _a;
153
205
  return __awaiter(this, void 0, void 0, function* () {
154
- const records = yield this.getMany(Object.assign(Object.assign({}, options), { page: { size: 1 } }));
155
- return records[0] || null;
206
+ const results = [];
207
+ try {
208
+ for (var _b = __asyncValues(this.getIterator(chunk, options)), _c; _c = yield _b.next(), !_c.done;) {
209
+ const page = _c.value;
210
+ results.push(...page);
211
+ }
212
+ }
213
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
214
+ finally {
215
+ try {
216
+ if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
217
+ }
218
+ finally { if (e_2) throw e_2.error; }
219
+ }
220
+ return results;
156
221
  });
157
222
  }
158
- deleteAll() {
223
+ /**
224
+ * Performs the query in the database and returns the first result.
225
+ * @param options Additional options to be used when performing the query.
226
+ * @returns The first record that matches the query, or null if no record matched the query.
227
+ */
228
+ getOne(options = {}) {
159
229
  return __awaiter(this, void 0, void 0, function* () {
160
- // TODO: Return number of affected rows
161
- return 0;
230
+ const records = yield this.getMany(Object.assign(Object.assign({}, options), { page: { size: 1 } }));
231
+ return records[0] || null;
162
232
  });
163
233
  }
234
+ /**async deleteAll(): Promise<number> {
235
+ // TODO: Return number of affected rows
236
+ return 0;
237
+ }**/
164
238
  nextPage(size, offset) {
165
- return __awaiter(this, void 0, void 0, function* () {
166
- return this.firstPage(size, offset);
167
- });
239
+ return this.firstPage(size, offset);
168
240
  }
169
241
  previousPage(size, offset) {
170
- return __awaiter(this, void 0, void 0, function* () {
171
- return this.firstPage(size, offset);
172
- });
242
+ return this.firstPage(size, offset);
173
243
  }
174
244
  firstPage(size, offset) {
175
- return __awaiter(this, void 0, void 0, function* () {
176
- return this.getPaginated({ page: { size, offset } });
177
- });
245
+ return this.getPaginated({ page: { size, offset } });
178
246
  }
179
247
  lastPage(size, offset) {
180
- return __awaiter(this, void 0, void 0, function* () {
181
- return this.getPaginated({ page: { size, offset, before: 'end' } });
182
- });
248
+ return this.getPaginated({ page: { size, offset, before: 'end' } });
183
249
  }
184
250
  hasNextPage() {
185
251
  return this.meta.page.more;
@@ -0,0 +1,44 @@
1
+ import { Selectable } from './selection';
2
+ /**
3
+ * Represents an identifiable record from the database.
4
+ */
5
+ export interface Identifiable {
6
+ /**
7
+ * Unique id of this record.
8
+ */
9
+ id: string;
10
+ }
11
+ export interface BaseData {
12
+ [key: string]: any;
13
+ }
14
+ /**
15
+ * Represents a persisted record from the database.
16
+ */
17
+ export interface XataRecord extends Identifiable {
18
+ /**
19
+ * Metadata of this record.
20
+ */
21
+ xata: {
22
+ /**
23
+ * Number that is increased every time the record is updated.
24
+ */
25
+ version: number;
26
+ };
27
+ /**
28
+ * Retrieves a refreshed copy of the current record from the database.
29
+ */
30
+ read(): Promise<this>;
31
+ /**
32
+ * Performs a partial update of the current record. On success a new object is
33
+ * returned and the current object is not mutated.
34
+ * @param data The columns and their values that have to be updated.
35
+ * @returns A new record containing the latest values for all the columns of the current record.
36
+ */
37
+ update(data: Partial<Selectable<this>>): Promise<this>;
38
+ /**
39
+ * Performs a deletion of the current record in the database.
40
+ *
41
+ * @throws If the record was already deleted or if an error happened while performing the deletion.
42
+ */
43
+ delete(): Promise<void>;
44
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,104 @@
1
+ import { FetchImpl } from '../api/fetcher';
2
+ import { Page } from './pagination';
3
+ import { Query, QueryOptions } from './query';
4
+ import { BaseData, XataRecord } from './record';
5
+ import { Select, SelectableColumn } 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<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record> {
11
+ abstract create(object: Data): Promise<Record>;
12
+ /**
13
+ * Creates multiple records in the table.
14
+ * @param objects Array of objects with the column names and the values to be stored in the table.
15
+ * @returns Array of the persisted records.
16
+ */
17
+ abstract createMany(objects: Data[]): Promise<Record[]>;
18
+ /**
19
+ * Queries a single record from the table given its unique id.
20
+ * @param id The unique id.
21
+ * @returns The persisted record for the given id or null if the record could not be found.
22
+ */
23
+ abstract read(id: string): Promise<Record | null>;
24
+ /**
25
+ * Insert a single record with a unique id.
26
+ * @param id The unique id.
27
+ * @param object Object containing the column names with their values to be stored in the table.
28
+ * @returns The full persisted record.
29
+ */
30
+ abstract insert(id: string, object: Data): Promise<Record>;
31
+ /**
32
+ * Partially update a single record given its unique id.
33
+ * @param id The unique id.
34
+ * @param object The column names and their values that have to be updatd.
35
+ * @returns The full persisted record.
36
+ */
37
+ abstract update(id: string, object: Partial<Data>): Promise<Record>;
38
+ /**
39
+ * Updates or inserts a single record. If a record exists with the given id,
40
+ * it will be update, otherwise a new record will be created.
41
+ * @param id A unique id.
42
+ * @param object The column names and the values to be persisted.
43
+ * @returns The full persisted record.
44
+ */
45
+ abstract updateOrInsert(id: string, object: Data): Promise<Record>;
46
+ /**
47
+ * Deletes a record given its unique id.
48
+ * @param id The unique id.
49
+ * @throws If the record could not be found or there was an error while performing the deletion.
50
+ */
51
+ abstract delete(id: string): void;
52
+ abstract query<Result extends XataRecord, Options extends QueryOptions<Record>>(query: Query<Record, Result>, options: Options): Promise<Page<Record, typeof options extends {
53
+ columns: SelectableColumn<Data>[];
54
+ } ? Select<Data, typeof options['columns'][number]> : Result>>;
55
+ }
56
+ export declare class RestRepository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Repository<Data, Record> {
57
+ #private;
58
+ constructor(client: BaseClient<any>, table: string);
59
+ create(object: Data): Promise<Record>;
60
+ createMany(objects: Data[]): Promise<Record[]>;
61
+ read(recordId: string): Promise<Record | null>;
62
+ update(recordId: string, object: Partial<Data>): Promise<Record>;
63
+ insert(recordId: string, object: Data): Promise<Record>;
64
+ updateOrInsert(recordId: string, object: Data): Promise<Record>;
65
+ delete(recordId: string): Promise<void>;
66
+ query<Result extends XataRecord, Options extends QueryOptions<Record>>(query: Query<Record, Result>, options?: Options): Promise<Page<Record, typeof options extends {
67
+ columns: SelectableColumn<Data>[];
68
+ } ? Select<Data, typeof options['columns'][number]> : Result>>;
69
+ }
70
+ interface RepositoryFactory {
71
+ createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data>;
72
+ }
73
+ export declare class RestRespositoryFactory implements RepositoryFactory {
74
+ createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data>;
75
+ }
76
+ declare type BranchStrategyValue = string | undefined | null;
77
+ declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
78
+ declare type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder;
79
+ declare type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>;
80
+ export declare type XataClientOptions = {
81
+ /**
82
+ * Fetch implementation. This option is only required if the runtime does not include a fetch implementation
83
+ * available in the global scope. If you are running your code on Deno or Cloudflare workers for example,
84
+ * you won't need to provide a specific fetch implementation. But for most versions of Node.js you'll need
85
+ * to provide one. Such as cross-fetch, node-fetch or isomorphic-fetch.
86
+ */
87
+ fetch?: FetchImpl;
88
+ databaseURL?: string;
89
+ branch: BranchStrategyOption;
90
+ /**
91
+ * API key to be used. You can create one in your account settings at https://app.xata.io/settings.
92
+ */
93
+ apiKey: string;
94
+ repositoryFactory?: RepositoryFactory;
95
+ };
96
+ export declare class BaseClient<D extends Record<string, Repository<any>> = Record<string, Repository<any>>> {
97
+ #private;
98
+ options: XataClientOptions;
99
+ db: D;
100
+ constructor(options: XataClientOptions, links?: Links);
101
+ initObject<T>(table: string, object: object): T;
102
+ getBranch(): Promise<string>;
103
+ }
104
+ export {};