@xata.io/client 0.1.4 → 0.3.0

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