@xata.io/client 0.0.0-beta.bbcb88d → 0.0.0-beta.c9e08d0

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/src/index.ts DELETED
@@ -1,501 +0,0 @@
1
- import { errors } from './util/errors';
2
-
3
- export interface XataRecord {
4
- id: string;
5
- xata: {
6
- version: number;
7
- };
8
- read(): Promise<this>;
9
- update(data: Selectable<this>): Promise<this>;
10
- delete(): Promise<void>;
11
- }
12
-
13
- export type Queries<T> = {
14
- [key in keyof T as T[key] extends Query<infer A, infer B> ? key : never]: T[key];
15
- };
16
-
17
- export type OmitQueries<T> = {
18
- [key in keyof T as T[key] extends Query<infer A, infer B> ? never : key]: T[key];
19
- };
20
-
21
- export type OmitLinks<T> = {
22
- [key in keyof T as T[key] extends XataRecord ? never : key]: T[key];
23
- };
24
-
25
- export type OmitMethods<T> = {
26
- // eslint-disable-next-line @typescript-eslint/ban-types
27
- [key in keyof T as T[key] extends Function ? never : key]: T[key];
28
- };
29
-
30
- export type Selectable<T> = Omit<OmitQueries<OmitMethods<T>>, 'id' | 'xata'>;
31
-
32
- export type Select<T, K extends keyof T> = Pick<T, K> & Queries<T> & XataRecord;
33
-
34
- export type Include<T> = {
35
- [key in keyof T as T[key] extends XataRecord ? key : never]?: boolean | Array<keyof Selectable<T[key]>>;
36
- };
37
-
38
- type SortDirection = 'asc' | 'desc';
39
-
40
- type Operator =
41
- | '$gt'
42
- | '$lt'
43
- | '$ge'
44
- | '$le'
45
- | '$exists'
46
- | '$notExists'
47
- | '$endsWith'
48
- | '$startsWith'
49
- | '$pattern'
50
- | '$is'
51
- | '$isNot'
52
- | '$contains'
53
- | '$includes'
54
- | '$includesSubstring'
55
- | '$includesPattern'
56
- | '$includesAll';
57
-
58
- // TODO: restrict constraints depending on type?
59
- // E.g. startsWith cannot be used with numbers
60
- type Constraint<T> = { [key in Operator]?: T };
61
-
62
- type DeepConstraint<T> = T extends Record<string, any>
63
- ? {
64
- [key in keyof T]?: T[key] | DeepConstraint<T[key]>;
65
- }
66
- : Constraint<T>;
67
-
68
- type ComparableType = number | Date;
69
-
70
- export const gt = <T extends ComparableType>(value: T): Constraint<T> => ({ $gt: value });
71
- export const ge = <T extends ComparableType>(value: T): Constraint<T> => ({ $ge: value });
72
- export const gte = <T extends ComparableType>(value: T): Constraint<T> => ({ $ge: value });
73
- export const lt = <T extends ComparableType>(value: T): Constraint<T> => ({ $lt: value });
74
- export const lte = <T extends ComparableType>(value: T): Constraint<T> => ({ $le: value });
75
- export const le = <T extends ComparableType>(value: T): Constraint<T> => ({ $le: value });
76
- export const exists = (column: string): Constraint<string> => ({ $exists: column });
77
- export const notExists = (column: string): Constraint<string> => ({ $notExists: column });
78
- export const startsWith = (value: string): Constraint<string> => ({ $startsWith: value });
79
- export const endsWith = (value: string): Constraint<string> => ({ $endsWith: value });
80
- export const pattern = (value: string): Constraint<string> => ({ $pattern: value });
81
- export const is = <T>(value: T): Constraint<T> => ({ $is: value });
82
- export const isNot = <T>(value: T): Constraint<T> => ({ $isNot: value });
83
- export const contains = <T>(value: T): Constraint<T> => ({ $contains: value });
84
-
85
- // TODO: these can only be applied to columns of type "multiple"
86
- export const includes = (value: string): Constraint<string> => ({ $includes: value });
87
- export const includesSubstring = (value: string): Constraint<string> => ({ $includesSubstring: value });
88
- export const includesPattern = (value: string): Constraint<string> => ({ $includesPattern: value });
89
- export const includesAll = (value: string): Constraint<string> => ({ $includesAll: value });
90
-
91
- type FilterConstraints<T> = {
92
- [key in keyof T]?: T[key] extends Record<string, any> ? FilterConstraints<T[key]> : T[key] | DeepConstraint<T[key]>;
93
- };
94
-
95
- type BulkQueryOptions<T> = {
96
- filter?: FilterConstraints<T>;
97
- sort?:
98
- | {
99
- column: keyof T;
100
- direction?: SortDirection;
101
- }
102
- | keyof T;
103
- };
104
-
105
- type QueryOrConstraint<T, R> = Query<T, R> | Constraint<T>;
106
-
107
- export class Query<T, R = T> {
108
- table: string;
109
- repository: Repository<T>;
110
-
111
- readonly $any?: QueryOrConstraint<T, R>[];
112
- readonly $all?: QueryOrConstraint<T, R>[];
113
- readonly $not?: QueryOrConstraint<T, R>[];
114
- readonly $none?: QueryOrConstraint<T, R>[];
115
- readonly $sort?: Record<string, SortDirection>;
116
-
117
- constructor(repository: Repository<T> | null, table: string, data: Partial<Query<T, R>>, parent?: Query<T, R>) {
118
- if (repository) {
119
- this.repository = repository;
120
- } else {
121
- this.repository = this as any;
122
- }
123
- this.table = table;
124
-
125
- // For some reason Object.assign(this, parent) didn't work in this case
126
- // so doing all this manually:
127
- this.$any = parent?.$any;
128
- this.$all = parent?.$all;
129
- this.$not = parent?.$not;
130
- this.$none = parent?.$none;
131
- this.$sort = parent?.$sort;
132
-
133
- Object.assign(this, data);
134
- // These bindings are used to support deconstructing
135
- // const { any, not, filter, sort } = xata.users.query()
136
- this.any = this.any.bind(this);
137
- this.all = this.all.bind(this);
138
- this.not = this.not.bind(this);
139
- this.filter = this.filter.bind(this);
140
- this.sort = this.sort.bind(this);
141
- this.none = this.none.bind(this);
142
-
143
- Object.defineProperty(this, 'table', { enumerable: false });
144
- Object.defineProperty(this, 'repository', { enumerable: false });
145
- }
146
-
147
- any(...queries: Query<T, R>[]): Query<T, R> {
148
- return new Query<T, R>(
149
- this.repository,
150
- this.table,
151
- {
152
- $any: (this.$any || []).concat(queries)
153
- },
154
- this
155
- );
156
- }
157
-
158
- all(...queries: Query<T, R>[]): Query<T, R> {
159
- return new Query<T, R>(
160
- this.repository,
161
- this.table,
162
- {
163
- $all: (this.$all || []).concat(queries)
164
- },
165
- this
166
- );
167
- }
168
-
169
- not(...queries: Query<T, R>[]): Query<T, R> {
170
- return new Query<T, R>(
171
- this.repository,
172
- this.table,
173
- {
174
- $not: (this.$not || []).concat(queries)
175
- },
176
- this
177
- );
178
- }
179
-
180
- none(...queries: Query<T, R>[]): Query<T, R> {
181
- return new Query<T, R>(
182
- this.repository,
183
- this.table,
184
- {
185
- $none: (this.$none || []).concat(queries)
186
- },
187
- this
188
- );
189
- }
190
-
191
- filter(constraints: FilterConstraints<T>): Query<T, R>;
192
- filter<F extends keyof T>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>;
193
- filter(a: any, b?: any): Query<T, R> {
194
- if (arguments.length === 1) {
195
- const constraints = a as FilterConstraints<T>;
196
- const queries: QueryOrConstraint<T, R>[] = [];
197
- for (const [column, constraint] of Object.entries(constraints)) {
198
- queries.push({ [column]: constraint });
199
- }
200
- return new Query<T, R>(
201
- this.repository,
202
- this.table,
203
- {
204
- $all: (this.$all || []).concat(queries)
205
- },
206
- this
207
- );
208
- } else {
209
- const column = a as keyof T;
210
- const value = b as Partial<T[keyof T]> | Constraint<T[keyof T]>;
211
- return new Query<T, R>(
212
- this.repository,
213
- this.table,
214
- {
215
- $all: (this.$all || []).concat({ [column]: value })
216
- },
217
- this
218
- );
219
- }
220
- }
221
-
222
- sort<F extends keyof T>(column: F, direction: SortDirection): Query<T, R> {
223
- const sort = { ...this.$sort, [column]: direction };
224
- const q = new Query<T, R>(
225
- this.repository,
226
- this.table,
227
- {
228
- $sort: sort
229
- },
230
- this
231
- );
232
-
233
- return q;
234
- }
235
-
236
- // TODO: pagination. Maybe implement different methods for different type of paginations
237
- // and one to simply get the first records returned by the query with no pagination.
238
- async getMany(options?: BulkQueryOptions<T>): Promise<R[]> {
239
- // TODO: use options
240
- return this.repository.query(this);
241
- }
242
-
243
- async getOne(options?: BulkQueryOptions<T>): Promise<R | null> {
244
- // TODO: use options
245
- const arr = await this.getMany(); // TODO, limit to 1
246
- return arr[0] || null;
247
- }
248
-
249
- async deleteAll(): Promise<number> {
250
- // Return number of affected rows
251
- return 0;
252
- }
253
-
254
- include(columns: Include<T>) {
255
- // TODO
256
- return this;
257
- }
258
- }
259
-
260
- export abstract class Repository<T> extends Query<T, Selectable<T>> {
261
- select<K extends keyof Selectable<T>>(...columns: K[]) {
262
- return new Query<T, Select<T, K>>(this.repository, this.table, {});
263
- }
264
-
265
- abstract create(object: Selectable<T>): Promise<T>;
266
-
267
- abstract read(id: string): Promise<T | null>;
268
-
269
- abstract update(id: string, object: Partial<T>): Promise<T>;
270
-
271
- abstract delete(id: string): void;
272
-
273
- // Used by the Query object internally
274
- abstract query<R>(query: Query<T, R>): Promise<R[]>;
275
- }
276
-
277
- export class RestRepository<T> extends Repository<T> {
278
- client: BaseClient<any>;
279
- fetch: any;
280
-
281
- constructor(client: BaseClient<any>, table: string) {
282
- super(null, table, {});
283
- this.client = client;
284
-
285
- const doWeHaveFetch = typeof fetch !== 'undefined';
286
- const isInjectedFetchProblematic = !this.client.options.fetch;
287
-
288
- if (doWeHaveFetch) {
289
- this.fetch = fetch;
290
- } else if (isInjectedFetchProblematic) {
291
- throw new Error(errors.falsyFetchImplementation);
292
- } else {
293
- this.fetch = this.client.options.fetch;
294
- }
295
-
296
- Object.defineProperty(this, 'client', { enumerable: false });
297
- Object.defineProperty(this, 'fetch', { enumerable: false });
298
- Object.defineProperty(this, 'hostname', { enumerable: false });
299
- }
300
-
301
- async request(method: string, path: string, body?: unknown) {
302
- const { databaseURL, apiKey } = this.client.options;
303
- const branch = await this.client.getBranch();
304
-
305
- const resp: Response = await this.fetch(`${databaseURL}:${branch}${path}`, {
306
- method,
307
- headers: {
308
- Accept: '*/*',
309
- 'Content-Type': 'application/json',
310
- Authorization: `Bearer ${apiKey}`
311
- },
312
- body: JSON.stringify(body)
313
- });
314
- if (!resp.ok) {
315
- try {
316
- const json = await resp.json();
317
- const message = json.message;
318
- if (typeof message === 'string') {
319
- throw new XataError(message, resp.status);
320
- }
321
- } catch (err) {
322
- if (err instanceof XataError) throw err;
323
- // Ignore errors for other reasons.
324
- // For example if the response's body cannot be parsed as JSON
325
- }
326
- throw new XataError(resp.statusText, resp.status);
327
- }
328
- if (resp.status === 204) return;
329
- return resp.json();
330
- }
331
-
332
- select<K extends keyof T>(...columns: K[]) {
333
- return new Query<T, Select<T, K>>(this.repository, this.table, {});
334
- }
335
-
336
- async create(object: T): Promise<T> {
337
- const body = { ...object } as Record<string, unknown>;
338
- for (const key of Object.keys(body)) {
339
- const value = body[key];
340
- if (value && typeof value === 'object' && typeof (value as Record<string, unknown>).id === 'string') {
341
- body[key] = (value as XataRecord).id;
342
- }
343
- }
344
- const obj = await this.request('POST', `/tables/${this.table}/data`, body);
345
- return this.client.initObject(this.table, obj);
346
- }
347
-
348
- async read(id: string): Promise<T | null> {
349
- try {
350
- const obj = await this.request('GET', `/tables/${this.table}/data/${id}`);
351
- return this.client.initObject(this.table, obj);
352
- } catch (err) {
353
- if ((err as XataError).status === 404) return null;
354
- throw err;
355
- }
356
- }
357
-
358
- async update(id: string, object: Partial<T>): Promise<T> {
359
- const obj = await this.request('PUT', `/tables/${this.table}/data/${id}`, object);
360
- return this.client.initObject(this.table, obj);
361
- }
362
-
363
- async delete(id: string) {
364
- await this.request('DELETE', `/tables/${this.table}/data/${id}`);
365
- }
366
-
367
- async query<R>(query: Query<T, R>): Promise<R[]> {
368
- const filter = {
369
- $any: query.$any,
370
- $all: query.$all,
371
- $not: query.$not,
372
- $none: query.$none
373
- };
374
- const body = {
375
- filter: Object.values(filter).some(Boolean) ? filter : undefined,
376
- sort: query.$sort
377
- };
378
- const result = await this.request('POST', `/tables/${this.table}/query`, body);
379
- return result.records.map((record: object) => this.client.initObject(this.table, record));
380
- }
381
- }
382
-
383
- interface RepositoryFactory {
384
- createRepository<T>(client: BaseClient<any>, table: string): Repository<T>;
385
- }
386
-
387
- export class RestRespositoryFactory implements RepositoryFactory {
388
- createRepository<T>(client: BaseClient<any>, table: string): Repository<T> {
389
- return new RestRepository<T>(client, table);
390
- }
391
- }
392
-
393
- type BranchStrategyValue = string | undefined | null;
394
- type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
395
- type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder;
396
- type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>;
397
-
398
- export type XataClientOptions = {
399
- fetch?: unknown;
400
- databaseURL: string;
401
- branch: BranchStrategyOption;
402
- apiKey: string;
403
- repositoryFactory?: RepositoryFactory;
404
- };
405
-
406
- export class BaseClient<D extends Record<string, Repository<any>>> {
407
- options: XataClientOptions;
408
- private links: Links;
409
- private branch: BranchStrategyValue;
410
- db!: D;
411
-
412
- constructor(options: XataClientOptions, links: Links) {
413
- if (!options.databaseURL || !options.apiKey || !options.branch) {
414
- throw new Error('Options databaseURL, apiKey and branch are required');
415
- }
416
-
417
- this.options = options;
418
- this.links = links;
419
- }
420
-
421
- public initObject<T>(table: string, object: object) {
422
- const o: Record<string, unknown> = {};
423
- Object.assign(o, object);
424
-
425
- const tableLinks = this.links[table] || [];
426
- for (const link of tableLinks) {
427
- const [field, linkTable] = link;
428
- const value = o[field];
429
-
430
- if (value && typeof value === 'object') {
431
- const { id } = value as any;
432
- if (Object.keys(value).find((col) => col === 'id')) {
433
- o[field] = this.initObject(linkTable, value);
434
- } else if (id) {
435
- o[field] = {
436
- id,
437
- get: () => {
438
- this.db[linkTable].read(id);
439
- }
440
- };
441
- }
442
- }
443
- }
444
-
445
- const db = this.db;
446
- o.read = function () {
447
- return db[table].read(o['id'] as string);
448
- };
449
- o.update = function (data: any) {
450
- return db[table].update(o['id'] as string, data);
451
- };
452
- o.delete = function () {
453
- return db[table].delete(o['id'] as string);
454
- };
455
-
456
- for (const prop of ['read', 'update', 'delete']) {
457
- Object.defineProperty(o, prop, { enumerable: false });
458
- }
459
-
460
- // TODO: links and rev links
461
-
462
- Object.freeze(o);
463
- return o as T;
464
- }
465
-
466
- public async getBranch(): Promise<string> {
467
- if (this.branch) return this.branch;
468
-
469
- const { branch: param } = this.options;
470
- const strategies = Array.isArray(param) ? [...param] : [param];
471
-
472
- const evaluateBranch = async (strategy: BranchStrategy) => {
473
- return isBranchStrategyBuilder(strategy) ? await strategy() : strategy;
474
- };
475
-
476
- for await (const strategy of strategies) {
477
- const branch = await evaluateBranch(strategy);
478
- if (branch) {
479
- this.branch = branch;
480
- return branch;
481
- }
482
- }
483
-
484
- throw new Error('Unable to resolve branch value');
485
- }
486
- }
487
-
488
- export class XataError extends Error {
489
- readonly status: number;
490
-
491
- constructor(message: string, status: number) {
492
- super(message);
493
- this.status = status;
494
- }
495
- }
496
-
497
- export type Links = Record<string, Array<string[]>>;
498
-
499
- const isBranchStrategyBuilder = (strategy: BranchStrategy): strategy is BranchStrategyBuilder => {
500
- return typeof strategy === 'function';
501
- };
@@ -1,6 +0,0 @@
1
- export const errors = {
2
- falsyFetchImplementation: `The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.
3
-
4
- More in the docs:
5
- ` /** @todo add a link after docs exist */
6
- };
package/tsconfig.json DELETED
@@ -1,21 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES6",
4
- "lib": ["dom", "esnext"],
5
- "allowJs": true,
6
- "skipLibCheck": true,
7
- "esModuleInterop": true,
8
- "allowSyntheticDefaultImports": true,
9
- "strict": true,
10
- "forceConsistentCasingInFileNames": true,
11
- "noFallthroughCasesInSwitch": true,
12
- "module": "CommonJS",
13
- "moduleResolution": "node",
14
- "resolveJsonModule": true,
15
- "isolatedModules": true,
16
- "noEmit": false,
17
- "outDir": "dist",
18
- "declaration": true
19
- },
20
- "include": ["src"]
21
- }