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