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