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

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 (43) hide show
  1. package/dist/api/client.d.ts +90 -0
  2. package/dist/api/client.js +220 -0
  3. package/dist/api/components.d.ts +1430 -0
  4. package/dist/api/components.js +1001 -0
  5. package/dist/api/fetcher.d.ts +25 -0
  6. package/dist/api/fetcher.js +78 -0
  7. package/dist/api/index.d.ts +7 -0
  8. package/dist/api/index.js +17 -0
  9. package/dist/api/parameters.d.ts +16 -0
  10. package/dist/api/parameters.js +2 -0
  11. package/dist/api/providers.d.ts +8 -0
  12. package/dist/api/providers.js +29 -0
  13. package/dist/api/responses.d.ts +38 -0
  14. package/dist/api/responses.js +2 -0
  15. package/dist/api/schemas.d.ts +311 -0
  16. package/dist/api/schemas.js +2 -0
  17. package/dist/index.d.ts +21 -95
  18. package/dist/index.js +117 -231
  19. package/dist/schema/filters.d.ts +20 -0
  20. package/dist/schema/filters.js +24 -0
  21. package/dist/schema/index.d.ts +1 -0
  22. package/dist/schema/index.js +13 -0
  23. package/dist/schema/operators.d.ts +21 -0
  24. package/dist/schema/operators.js +40 -0
  25. package/dist/schema/pagination.d.ts +41 -0
  26. package/dist/schema/pagination.js +58 -0
  27. package/dist/schema/query.d.ts +45 -0
  28. package/dist/schema/query.js +190 -0
  29. package/dist/schema/selection.d.ts +18 -0
  30. package/dist/schema/selection.js +2 -0
  31. package/dist/util/lang.d.ts +1 -0
  32. package/dist/util/lang.js +10 -0
  33. package/dist/util/types.d.ts +3 -0
  34. package/dist/util/types.js +2 -0
  35. package/package.json +3 -3
  36. package/dist/index.test.d.ts +0 -1
  37. package/dist/index.test.js +0 -304
  38. package/dist/util/errors.d.ts +0 -3
  39. package/dist/util/errors.js +0 -9
  40. package/src/index.test.ts +0 -392
  41. package/src/index.ts +0 -501
  42. package/src/util/errors.ts +0 -6
  43. package/tsconfig.json +0 -21
package/dist/index.d.ts CHANGED
@@ -1,3 +1,7 @@
1
+ import { FetchImpl } from './api/fetcher';
2
+ import { Page } from './schema/pagination';
3
+ import { Query, QueryOptions } from './schema/query';
4
+ import { Selectable, SelectableColumn, Select } from './schema/selection';
1
5
  export interface XataRecord {
2
6
  id: string;
3
7
  xata: {
@@ -7,123 +11,44 @@ export interface XataRecord {
7
11
  update(data: Selectable<this>): Promise<this>;
8
12
  delete(): Promise<void>;
9
13
  }
10
- export declare type Queries<T> = {
11
- [key in keyof T as T[key] extends Query<infer A, infer B> ? key : never]: T[key];
12
- };
13
- export declare type OmitQueries<T> = {
14
- [key in keyof T as T[key] extends Query<infer A, infer B> ? never : key]: T[key];
15
- };
16
- export declare type OmitLinks<T> = {
17
- [key in keyof T as T[key] extends XataRecord ? never : key]: T[key];
18
- };
19
- export declare type OmitMethods<T> = {
20
- [key in keyof T as T[key] extends Function ? never : key]: T[key];
21
- };
22
- export declare type Selectable<T> = Omit<OmitQueries<OmitMethods<T>>, 'id' | 'xata'>;
23
- export declare type Select<T, K extends keyof T> = Pick<T, K> & Queries<T> & XataRecord;
24
- export declare type Include<T> = {
25
- [key in keyof T as T[key] extends XataRecord ? key : never]?: boolean | Array<keyof Selectable<T[key]>>;
26
- };
27
- declare type SortDirection = 'asc' | 'desc';
28
- declare type Operator = '$gt' | '$lt' | '$ge' | '$le' | '$exists' | '$notExists' | '$endsWith' | '$startsWith' | '$pattern' | '$is' | '$isNot' | '$contains' | '$includes' | '$includesSubstring' | '$includesPattern' | '$includesAll';
29
- declare type Constraint<T> = {
30
- [key in Operator]?: T;
31
- };
32
- declare type DeepConstraint<T> = T extends Record<string, any> ? {
33
- [key in keyof T]?: T[key] | DeepConstraint<T[key]>;
34
- } : Constraint<T>;
35
- declare type ComparableType = number | Date;
36
- export declare const gt: <T extends ComparableType>(value: T) => Constraint<T>;
37
- export declare const ge: <T extends ComparableType>(value: T) => Constraint<T>;
38
- export declare const gte: <T extends ComparableType>(value: T) => Constraint<T>;
39
- export declare const lt: <T extends ComparableType>(value: T) => Constraint<T>;
40
- export declare const lte: <T extends ComparableType>(value: T) => Constraint<T>;
41
- export declare const le: <T extends ComparableType>(value: T) => Constraint<T>;
42
- export declare const exists: (column: string) => Constraint<string>;
43
- export declare const notExists: (column: string) => Constraint<string>;
44
- export declare const startsWith: (value: string) => Constraint<string>;
45
- export declare const endsWith: (value: string) => Constraint<string>;
46
- export declare const pattern: (value: string) => Constraint<string>;
47
- export declare const is: <T>(value: T) => Constraint<T>;
48
- export declare const isNot: <T>(value: T) => Constraint<T>;
49
- export declare const contains: <T>(value: T) => Constraint<T>;
50
- export declare const includes: (value: string) => Constraint<string>;
51
- export declare const includesSubstring: (value: string) => Constraint<string>;
52
- export declare const includesPattern: (value: string) => Constraint<string>;
53
- export declare const includesAll: (value: string) => Constraint<string>;
54
- declare type FilterConstraints<T> = {
55
- [key in keyof T]?: T[key] extends Record<string, any> ? FilterConstraints<T[key]> : T[key] | DeepConstraint<T[key]>;
56
- };
57
- declare type BulkQueryOptions<T> = {
58
- filter?: FilterConstraints<T>;
59
- sort?: {
60
- column: keyof T;
61
- direction?: SortDirection;
62
- } | keyof T;
63
- };
64
- declare type QueryOrConstraint<T, R> = Query<T, R> | Constraint<T>;
65
- export declare class Query<T, R = T> {
66
- table: string;
67
- repository: Repository<T>;
68
- readonly $any?: QueryOrConstraint<T, R>[];
69
- readonly $all?: QueryOrConstraint<T, R>[];
70
- readonly $not?: QueryOrConstraint<T, R>[];
71
- readonly $none?: QueryOrConstraint<T, R>[];
72
- readonly $sort?: Record<string, SortDirection>;
73
- constructor(repository: Repository<T> | null, table: string, data: Partial<Query<T, R>>, parent?: Query<T, R>);
74
- any(...queries: Query<T, R>[]): Query<T, R>;
75
- all(...queries: Query<T, R>[]): Query<T, R>;
76
- not(...queries: Query<T, R>[]): Query<T, R>;
77
- none(...queries: Query<T, R>[]): Query<T, R>;
78
- filter(constraints: FilterConstraints<T>): Query<T, R>;
79
- filter<F extends keyof T>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>;
80
- sort<F extends keyof T>(column: F, direction: SortDirection): Query<T, R>;
81
- getMany(options?: BulkQueryOptions<T>): Promise<R[]>;
82
- getOne(options?: BulkQueryOptions<T>): Promise<R | null>;
83
- deleteAll(): Promise<number>;
84
- include(columns: Include<T>): this;
85
- }
86
- export declare abstract class Repository<T> extends Query<T, Selectable<T>> {
87
- select<K extends keyof Selectable<T>>(...columns: K[]): Query<T, Select<T, K>>;
14
+ export declare abstract class Repository<T extends XataRecord> extends Query<T> {
88
15
  abstract create(object: Selectable<T>): Promise<T>;
16
+ abstract createMany(objects: Selectable<T>[]): Promise<T[]>;
89
17
  abstract read(id: string): Promise<T | null>;
90
18
  abstract update(id: string, object: Partial<T>): Promise<T>;
91
19
  abstract delete(id: string): void;
92
- abstract query<R>(query: Query<T, R>): Promise<R[]>;
20
+ abstract query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>;
93
21
  }
94
- export declare class RestRepository<T> extends Repository<T> {
95
- client: BaseClient<any>;
96
- fetch: any;
22
+ export declare class RestRepository<T extends XataRecord> extends Repository<T> {
23
+ #private;
97
24
  constructor(client: BaseClient<any>, table: string);
98
- request(method: string, path: string, body?: unknown): Promise<any>;
99
- select<K extends keyof T>(...columns: K[]): Query<T, Select<T, K>>;
100
25
  create(object: T): Promise<T>;
101
- read(id: string): Promise<T | null>;
102
- update(id: string, object: Partial<T>): Promise<T>;
103
- delete(id: string): Promise<void>;
104
- query<R>(query: Query<T, R>): Promise<R[]>;
26
+ createMany(objects: T[]): Promise<T[]>;
27
+ read(recordId: string): Promise<T | null>;
28
+ update(recordId: string, object: Partial<T>): Promise<T>;
29
+ delete(recordId: string): Promise<void>;
30
+ query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>;
105
31
  }
106
32
  interface RepositoryFactory {
107
- createRepository<T>(client: BaseClient<any>, table: string): Repository<T>;
33
+ createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
108
34
  }
109
35
  export declare class RestRespositoryFactory implements RepositoryFactory {
110
- createRepository<T>(client: BaseClient<any>, table: string): Repository<T>;
36
+ createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
111
37
  }
112
38
  declare type BranchStrategyValue = string | undefined | null;
113
39
  declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
114
40
  declare type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder;
115
41
  declare type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>;
116
42
  export declare type XataClientOptions = {
117
- fetch?: unknown;
118
- databaseURL: string;
43
+ fetch?: FetchImpl;
44
+ databaseURL?: string;
119
45
  branch: BranchStrategyOption;
120
46
  apiKey: string;
121
47
  repositoryFactory?: RepositoryFactory;
122
48
  };
123
49
  export declare class BaseClient<D extends Record<string, Repository<any>>> {
50
+ #private;
124
51
  options: XataClientOptions;
125
- private links;
126
- private branch;
127
52
  db: D;
128
53
  constructor(options: XataClientOptions, links: Links);
129
54
  initObject<T>(table: string, object: object): T;
@@ -134,4 +59,5 @@ export declare class XataError extends Error {
134
59
  constructor(message: string, status: number);
135
60
  }
136
61
  export declare type Links = Record<string, Array<string[]>>;
137
- export {};
62
+ export * from './api';
63
+ export * from './schema';
package/dist/index.js CHANGED
@@ -1,4 +1,14 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
2
12
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
13
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
14
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -8,6 +18,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
18
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
19
  });
10
20
  };
21
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
22
+ if (kind === "m") throw new TypeError("Private method is not writable");
23
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
24
+ 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");
25
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
26
+ };
27
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
28
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
29
+ 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");
30
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
31
+ };
11
32
  var __asyncValues = (this && this.__asyncValues) || function (o) {
12
33
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
34
  var m = o[Symbol.asyncIterator], i;
@@ -15,264 +36,115 @@ var __asyncValues = (this && this.__asyncValues) || function (o) {
15
36
  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); }); }; }
16
37
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
38
  };
39
+ var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _BaseClient_links, _BaseClient_branch;
18
40
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.XataError = exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = exports.Query = exports.includesAll = exports.includesPattern = exports.includesSubstring = exports.includes = exports.contains = exports.isNot = exports.is = exports.pattern = exports.endsWith = exports.startsWith = exports.notExists = exports.exists = exports.le = exports.lte = exports.lt = exports.gte = exports.ge = exports.gt = void 0;
20
- const errors_1 = require("./util/errors");
21
- const gt = (value) => ({ $gt: value });
22
- exports.gt = gt;
23
- const ge = (value) => ({ $ge: value });
24
- exports.ge = ge;
25
- const gte = (value) => ({ $ge: value });
26
- exports.gte = gte;
27
- const lt = (value) => ({ $lt: value });
28
- exports.lt = lt;
29
- const lte = (value) => ({ $le: value });
30
- exports.lte = lte;
31
- const le = (value) => ({ $le: value });
32
- exports.le = le;
33
- const exists = (column) => ({ $exists: column });
34
- exports.exists = exists;
35
- const notExists = (column) => ({ $notExists: column });
36
- exports.notExists = notExists;
37
- const startsWith = (value) => ({ $startsWith: value });
38
- exports.startsWith = startsWith;
39
- const endsWith = (value) => ({ $endsWith: value });
40
- exports.endsWith = endsWith;
41
- const pattern = (value) => ({ $pattern: value });
42
- exports.pattern = pattern;
43
- const is = (value) => ({ $is: value });
44
- exports.is = is;
45
- const isNot = (value) => ({ $isNot: value });
46
- exports.isNot = isNot;
47
- const contains = (value) => ({ $contains: value });
48
- exports.contains = contains;
49
- // TODO: these can only be applied to columns of type "multiple"
50
- const includes = (value) => ({ $includes: value });
51
- exports.includes = includes;
52
- const includesSubstring = (value) => ({ $includesSubstring: value });
53
- exports.includesSubstring = includesSubstring;
54
- const includesPattern = (value) => ({ $includesPattern: value });
55
- exports.includesPattern = includesPattern;
56
- const includesAll = (value) => ({ $includesAll: value });
57
- exports.includesAll = includesAll;
58
- class Query {
59
- constructor(repository, table, data, parent) {
60
- if (repository) {
61
- this.repository = repository;
62
- }
63
- else {
64
- this.repository = this;
65
- }
66
- this.table = table;
67
- // For some reason Object.assign(this, parent) didn't work in this case
68
- // so doing all this manually:
69
- this.$any = parent === null || parent === void 0 ? void 0 : parent.$any;
70
- this.$all = parent === null || parent === void 0 ? void 0 : parent.$all;
71
- this.$not = parent === null || parent === void 0 ? void 0 : parent.$not;
72
- this.$none = parent === null || parent === void 0 ? void 0 : parent.$none;
73
- this.$sort = parent === null || parent === void 0 ? void 0 : parent.$sort;
74
- Object.assign(this, data);
75
- // These bindings are used to support deconstructing
76
- // const { any, not, filter, sort } = xata.users.query()
77
- this.any = this.any.bind(this);
78
- this.all = this.all.bind(this);
79
- this.not = this.not.bind(this);
80
- this.filter = this.filter.bind(this);
81
- this.sort = this.sort.bind(this);
82
- this.none = this.none.bind(this);
83
- Object.defineProperty(this, 'table', { enumerable: false });
84
- Object.defineProperty(this, 'repository', { enumerable: false });
85
- }
86
- any(...queries) {
87
- return new Query(this.repository, this.table, {
88
- $any: (this.$any || []).concat(queries)
89
- }, this);
90
- }
91
- all(...queries) {
92
- return new Query(this.repository, this.table, {
93
- $all: (this.$all || []).concat(queries)
94
- }, this);
95
- }
96
- not(...queries) {
97
- return new Query(this.repository, this.table, {
98
- $not: (this.$not || []).concat(queries)
99
- }, this);
100
- }
101
- none(...queries) {
102
- return new Query(this.repository, this.table, {
103
- $none: (this.$none || []).concat(queries)
104
- }, this);
105
- }
106
- filter(a, b) {
107
- if (arguments.length === 1) {
108
- const constraints = a;
109
- const queries = [];
110
- for (const [column, constraint] of Object.entries(constraints)) {
111
- queries.push({ [column]: constraint });
112
- }
113
- return new Query(this.repository, this.table, {
114
- $all: (this.$all || []).concat(queries)
115
- }, this);
116
- }
117
- else {
118
- const column = a;
119
- const value = b;
120
- return new Query(this.repository, this.table, {
121
- $all: (this.$all || []).concat({ [column]: value })
122
- }, this);
123
- }
124
- }
125
- sort(column, direction) {
126
- const sort = Object.assign(Object.assign({}, this.$sort), { [column]: direction });
127
- const q = new Query(this.repository, this.table, {
128
- $sort: sort
129
- }, this);
130
- return q;
131
- }
132
- // TODO: pagination. Maybe implement different methods for different type of paginations
133
- // and one to simply get the first records returned by the query with no pagination.
134
- getMany(options) {
135
- return __awaiter(this, void 0, void 0, function* () {
136
- // TODO: use options
137
- return this.repository.query(this);
138
- });
139
- }
140
- getOne(options) {
141
- return __awaiter(this, void 0, void 0, function* () {
142
- // TODO: use options
143
- const arr = yield this.getMany(); // TODO, limit to 1
144
- return arr[0] || null;
145
- });
146
- }
147
- deleteAll() {
148
- return __awaiter(this, void 0, void 0, function* () {
149
- // Return number of affected rows
150
- return 0;
151
- });
152
- }
153
- include(columns) {
154
- // TODO
155
- return this;
156
- }
157
- }
158
- exports.Query = Query;
159
- class Repository extends Query {
160
- select(...columns) {
161
- return new Query(this.repository, this.table, {});
162
- }
41
+ exports.XataError = exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
42
+ const api_1 = require("./api");
43
+ const filters_1 = require("./schema/filters");
44
+ const pagination_1 = require("./schema/pagination");
45
+ const query_1 = require("./schema/query");
46
+ class Repository extends query_1.Query {
163
47
  }
164
48
  exports.Repository = Repository;
165
49
  class RestRepository extends Repository {
166
50
  constructor(client, table) {
167
51
  super(null, table, {});
168
- this.client = client;
169
- const doWeHaveFetch = typeof fetch !== 'undefined';
170
- const isInjectedFetchProblematic = !this.client.options.fetch;
171
- if (doWeHaveFetch) {
172
- this.fetch = fetch;
52
+ _RestRepository_instances.add(this);
53
+ _RestRepository_client.set(this, void 0);
54
+ _RestRepository_fetch.set(this, void 0);
55
+ _RestRepository_table.set(this, void 0);
56
+ __classPrivateFieldSet(this, _RestRepository_client, client, "f");
57
+ __classPrivateFieldSet(this, _RestRepository_table, table, "f");
58
+ // TODO: Remove when integrating with API client
59
+ const fetchImpl = typeof fetch !== 'undefined' ? fetch : __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch;
60
+ if (!fetchImpl) {
61
+ throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
173
62
  }
174
- else if (isInjectedFetchProblematic) {
175
- throw new Error(errors_1.errors.falsyFetchImplementation);
176
- }
177
- else {
178
- this.fetch = this.client.options.fetch;
179
- }
180
- Object.defineProperty(this, 'client', { enumerable: false });
181
- Object.defineProperty(this, 'fetch', { enumerable: false });
182
- Object.defineProperty(this, 'hostname', { enumerable: false });
63
+ __classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f");
183
64
  }
184
- request(method, path, body) {
65
+ create(object) {
185
66
  return __awaiter(this, void 0, void 0, function* () {
186
- const { databaseURL, apiKey } = this.client.options;
187
- const branch = yield this.client.getBranch();
188
- const resp = yield this.fetch(`${databaseURL}:${branch}${path}`, {
189
- method,
190
- headers: {
191
- Accept: '*/*',
192
- 'Content-Type': 'application/json',
193
- Authorization: `Bearer ${apiKey}`
194
- },
195
- body: JSON.stringify(body)
196
- });
197
- if (!resp.ok) {
198
- try {
199
- const json = yield resp.json();
200
- const message = json.message;
201
- if (typeof message === 'string') {
202
- throw new XataError(message, resp.status);
203
- }
204
- }
205
- catch (err) {
206
- if (err instanceof XataError)
207
- throw err;
208
- // Ignore errors for other reasons.
209
- // For example if the response's body cannot be parsed as JSON
210
- }
211
- throw new XataError(resp.statusText, resp.status);
67
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
68
+ const record = transformObjectLinks(object);
69
+ const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: record }, fetchProps));
70
+ const finalObject = yield this.read(response.id);
71
+ if (!finalObject) {
72
+ throw new Error('The server failed to save the record');
212
73
  }
213
- if (resp.status === 204)
214
- return;
215
- return resp.json();
74
+ return finalObject;
216
75
  });
217
76
  }
218
- select(...columns) {
219
- return new Query(this.repository, this.table, {});
220
- }
221
- create(object) {
77
+ createMany(objects) {
222
78
  return __awaiter(this, void 0, void 0, function* () {
223
- const body = Object.assign({}, object);
224
- for (const key of Object.keys(body)) {
225
- const value = body[key];
226
- if (value && typeof value === 'object' && typeof value.id === 'string') {
227
- body[key] = value.id;
228
- }
79
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
80
+ const records = objects.map((object) => transformObjectLinks(object));
81
+ const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
82
+ // TODO: Use filer.$any() to get all the records
83
+ const finalObjects = yield Promise.all(response.recordIDs.map((id) => this.read(id)));
84
+ if (finalObjects.some((object) => !object)) {
85
+ throw new Error('The server failed to save the record');
229
86
  }
230
- const obj = yield this.request('POST', `/tables/${this.table}/data`, body);
231
- return this.client.initObject(this.table, obj);
87
+ return finalObjects;
232
88
  });
233
89
  }
234
- read(id) {
90
+ read(recordId) {
235
91
  return __awaiter(this, void 0, void 0, function* () {
236
- try {
237
- const obj = yield this.request('GET', `/tables/${this.table}/data/${id}`);
238
- return this.client.initObject(this.table, obj);
239
- }
240
- catch (err) {
241
- if (err.status === 404)
242
- return null;
243
- throw err;
244
- }
92
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
93
+ const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
94
+ return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
245
95
  });
246
96
  }
247
- update(id, object) {
97
+ update(recordId, object) {
248
98
  return __awaiter(this, void 0, void 0, function* () {
249
- const obj = yield this.request('PUT', `/tables/${this.table}/data/${id}`, object);
250
- return this.client.initObject(this.table, obj);
99
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
100
+ const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
101
+ // TODO: Review this, not sure we are properly initializing the object
102
+ return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
251
103
  });
252
104
  }
253
- delete(id) {
105
+ delete(recordId) {
254
106
  return __awaiter(this, void 0, void 0, function* () {
255
- yield this.request('DELETE', `/tables/${this.table}/data/${id}`);
107
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
108
+ yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
256
109
  });
257
110
  }
258
- query(query) {
111
+ query(query, options) {
112
+ var _a, _b, _c;
259
113
  return __awaiter(this, void 0, void 0, function* () {
260
- const filter = {
261
- $any: query.$any,
262
- $all: query.$all,
263
- $not: query.$not,
264
- $none: query.$none
265
- };
114
+ const data = query.getQueryOptions();
266
115
  const body = {
267
- filter: Object.values(filter).some(Boolean) ? filter : undefined,
268
- sort: query.$sort
116
+ filter: Object.values(data.filter).some(Boolean) ? data.filter : undefined,
117
+ sort: (_a = (0, filters_1.buildSortFilter)(options === null || options === void 0 ? void 0 : options.sort)) !== null && _a !== void 0 ? _a : data.sort,
118
+ page: (_b = options === null || options === void 0 ? void 0 : options.page) !== null && _b !== void 0 ? _b : data.page,
119
+ columns: (_c = options === null || options === void 0 ? void 0 : options.columns) !== null && _c !== void 0 ? _c : data.columns
269
120
  };
270
- const result = yield this.request('POST', `/tables/${this.table}/query`, body);
271
- return result.records.map((record) => this.client.initObject(this.table, record));
121
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
122
+ const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body }, fetchProps));
123
+ const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record));
124
+ // TODO: We should properly type this any
125
+ return new pagination_1.Page(query, meta, records);
272
126
  });
273
127
  }
274
128
  }
275
129
  exports.RestRepository = RestRepository;
130
+ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
131
+ return __awaiter(this, void 0, void 0, function* () {
132
+ const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
133
+ return {
134
+ fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
135
+ apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
136
+ apiUrl: '',
137
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
138
+ workspacesApiUrl: (path, params) => {
139
+ var _a, _b;
140
+ const baseUrl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.databaseURL) !== null && _a !== void 0 ? _a : '';
141
+ const hasBranch = (_b = params.dbBranchName) !== null && _b !== void 0 ? _b : params.branch;
142
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branch}` : '');
143
+ return baseUrl + newPath;
144
+ }
145
+ };
146
+ });
147
+ };
276
148
  class RestRespositoryFactory {
277
149
  createRepository(client, table) {
278
150
  return new RestRepository(client, table);
@@ -281,16 +153,18 @@ class RestRespositoryFactory {
281
153
  exports.RestRespositoryFactory = RestRespositoryFactory;
282
154
  class BaseClient {
283
155
  constructor(options, links) {
156
+ _BaseClient_links.set(this, void 0);
157
+ _BaseClient_branch.set(this, void 0);
284
158
  if (!options.databaseURL || !options.apiKey || !options.branch) {
285
159
  throw new Error('Options databaseURL, apiKey and branch are required');
286
160
  }
287
161
  this.options = options;
288
- this.links = links;
162
+ __classPrivateFieldSet(this, _BaseClient_links, links, "f");
289
163
  }
290
164
  initObject(table, object) {
291
165
  const o = {};
292
166
  Object.assign(o, object);
293
- const tableLinks = this.links[table] || [];
167
+ const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || [];
294
168
  for (const link of tableLinks) {
295
169
  const [field, linkTable] = link;
296
170
  const value = o[field];
@@ -329,8 +203,8 @@ class BaseClient {
329
203
  getBranch() {
330
204
  var e_1, _a;
331
205
  return __awaiter(this, void 0, void 0, function* () {
332
- if (this.branch)
333
- return this.branch;
206
+ if (__classPrivateFieldGet(this, _BaseClient_branch, "f"))
207
+ return __classPrivateFieldGet(this, _BaseClient_branch, "f");
334
208
  const { branch: param } = this.options;
335
209
  const strategies = Array.isArray(param) ? [...param] : [param];
336
210
  const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
@@ -341,7 +215,7 @@ class BaseClient {
341
215
  const strategy = strategies_1_1.value;
342
216
  const branch = yield evaluateBranch(strategy);
343
217
  if (branch) {
344
- this.branch = branch;
218
+ __classPrivateFieldSet(this, _BaseClient_branch, branch, "f");
345
219
  return branch;
346
220
  }
347
221
  }
@@ -358,6 +232,7 @@ class BaseClient {
358
232
  }
359
233
  }
360
234
  exports.BaseClient = BaseClient;
235
+ _BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap();
361
236
  class XataError extends Error {
362
237
  constructor(message, status) {
363
238
  super(message);
@@ -368,3 +243,14 @@ exports.XataError = XataError;
368
243
  const isBranchStrategyBuilder = (strategy) => {
369
244
  return typeof strategy === 'function';
370
245
  };
246
+ // TODO: We can find a better implementation for links
247
+ const transformObjectLinks = (object) => {
248
+ return Object.entries(object).reduce((acc, [key, value]) => {
249
+ if (value && typeof value === 'object' && typeof value.id === 'string') {
250
+ return Object.assign(Object.assign({}, acc), { [key]: value.id });
251
+ }
252
+ return Object.assign(Object.assign({}, acc), { [key]: value });
253
+ }, {});
254
+ };
255
+ __exportStar(require("./api"), exports);
256
+ __exportStar(require("./schema"), exports);
@@ -0,0 +1,20 @@
1
+ export declare type SortDirection = 'asc' | 'desc';
2
+ export declare type SortFilterExtended<T> = {
3
+ column: keyof T;
4
+ direction?: SortDirection;
5
+ };
6
+ export declare type SortFilter<T> = SortFilterExtended<T> | keyof T;
7
+ export declare function isSortFilterObject<T>(filter: SortFilter<T>): filter is SortFilterExtended<T>;
8
+ export declare type FilterOperator = '$gt' | '$lt' | '$ge' | '$le' | '$exists' | '$notExists' | '$endsWith' | '$startsWith' | '$pattern' | '$is' | '$isNot' | '$contains' | '$includes' | '$includesSubstring' | '$includesPattern' | '$includesAll';
9
+ export declare function buildSortFilter<T>(filter?: SortFilter<T> | SortFilter<T>[]): {
10
+ [key: string]: SortDirection;
11
+ } | undefined;
12
+ export declare type Constraint<T> = {
13
+ [key in FilterOperator]?: T;
14
+ };
15
+ export declare type DeepConstraint<T> = T extends Record<string, any> ? {
16
+ [key in keyof T]?: T[key] | DeepConstraint<T[key]>;
17
+ } : Constraint<T>;
18
+ export declare type FilterConstraints<T> = {
19
+ [key in keyof T]?: T[key] extends Record<string, any> ? FilterConstraints<T[key]> : T[key] | DeepConstraint<T[key]>;
20
+ };
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSortFilter = exports.isSortFilterObject = void 0;
4
+ function isSortFilterObject(filter) {
5
+ return typeof filter === 'object' && filter.column !== undefined;
6
+ }
7
+ exports.isSortFilterObject = isSortFilterObject;
8
+ function buildSortFilter(filter) {
9
+ if (!filter)
10
+ return undefined;
11
+ const filters = Array.isArray(filter) ? filter : [filter];
12
+ return filters.reduce((acc, item) => {
13
+ if (typeof item === 'string') {
14
+ return Object.assign(Object.assign({}, acc), { [item]: 'asc' });
15
+ }
16
+ else if (isSortFilterObject(item)) {
17
+ return Object.assign(Object.assign({}, acc), { [item.column]: item.direction });
18
+ }
19
+ else {
20
+ return acc;
21
+ }
22
+ }, {});
23
+ }
24
+ exports.buildSortFilter = buildSortFilter;
@@ -0,0 +1 @@
1
+ export * from './operators';
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./operators"), exports);