@xata.io/client 0.0.0-beta.c21e40a → 0.0.0-beta.c844f02

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.
@@ -1,72 +1,62 @@
1
- import { Constraint } from './filters';
2
- declare type ComparableType = number | Date;
1
+ import { ArrayFilter, ComparableType, ComparableTypeFilter, ExistanceFilter, PropertyFilter, StringTypeFilter } from './filters';
2
+ import { SelectableColumn } from './selection';
3
3
  /**
4
4
  * Operator to restrict results to only values that are greater than the given value.
5
5
  */
6
- export declare const gt: <T extends ComparableType>(value: T) => Constraint<T>;
6
+ export declare const gt: <T extends ComparableType>(value: T) => ComparableTypeFilter<T>;
7
7
  /**
8
8
  * Operator to restrict results to only values that are greater than or equal to the given value.
9
9
  */
10
- export declare const ge: <T extends ComparableType>(value: T) => Constraint<T>;
10
+ export declare const ge: <T extends ComparableType>(value: T) => ComparableTypeFilter<T>;
11
11
  /**
12
12
  * Operator to restrict results to only values that are greater than or equal to the given value.
13
13
  */
14
- export declare const gte: <T extends ComparableType>(value: T) => Constraint<T>;
14
+ export declare const gte: <T extends ComparableType>(value: T) => ComparableTypeFilter<T>;
15
15
  /**
16
16
  * Operator to restrict results to only values that are lower than the given value.
17
17
  */
18
- export declare const lt: <T extends ComparableType>(value: T) => Constraint<T>;
18
+ export declare const lt: <T extends ComparableType>(value: T) => ComparableTypeFilter<T>;
19
19
  /**
20
20
  * Operator to restrict results to only values that are lower than or equal to the given value.
21
21
  */
22
- export declare const lte: <T extends ComparableType>(value: T) => Constraint<T>;
22
+ export declare const lte: <T extends ComparableType>(value: T) => ComparableTypeFilter<T>;
23
23
  /**
24
24
  * Operator to restrict results to only values that are lower than or equal to the given value.
25
25
  */
26
- export declare const le: <T extends ComparableType>(value: T) => Constraint<T>;
26
+ export declare const le: <T extends ComparableType>(value: T) => ComparableTypeFilter<T>;
27
27
  /**
28
28
  * Operator to restrict results to only values that are not null.
29
29
  */
30
- export declare const exists: (column: string) => Constraint<string>;
30
+ export declare const exists: <T>(column: SelectableColumn<T, []>) => ExistanceFilter<T>;
31
31
  /**
32
32
  * Operator to restrict results to only values that are null.
33
33
  */
34
- export declare const notExists: (column: string) => Constraint<string>;
34
+ export declare const notExists: <T>(column: SelectableColumn<T, []>) => ExistanceFilter<T>;
35
35
  /**
36
36
  * Operator to restrict results to only values that start with the given prefix.
37
37
  */
38
- export declare const startsWith: (value: string) => Constraint<string>;
38
+ export declare const startsWith: (value: string) => StringTypeFilter;
39
39
  /**
40
40
  * Operator to restrict results to only values that end with the given suffix.
41
41
  */
42
- export declare const endsWith: (value: string) => Constraint<string>;
42
+ export declare const endsWith: (value: string) => StringTypeFilter;
43
43
  /**
44
44
  * Operator to restrict results to only values that match the given pattern.
45
45
  */
46
- export declare const pattern: (value: string) => Constraint<string>;
46
+ export declare const pattern: (value: string) => StringTypeFilter;
47
47
  /**
48
48
  * Operator to restrict results to only values that are equal to the given value.
49
49
  */
50
- export declare const is: <T>(value: T) => Constraint<T>;
50
+ export declare const is: <T>(value: T) => PropertyFilter<T>;
51
51
  /**
52
52
  * Operator to restrict results to only values that are not equal to the given value.
53
53
  */
54
- export declare const isNot: <T>(value: T) => Constraint<T>;
54
+ export declare const isNot: <T>(value: T) => PropertyFilter<T>;
55
55
  /**
56
56
  * Operator to restrict results to only values that contain the given value.
57
57
  */
58
- export declare const contains: <T>(value: T) => Constraint<T>;
58
+ export declare const contains: (value: string) => StringTypeFilter;
59
59
  /**
60
60
  * Operator to restrict results to only arrays that include the given value.
61
61
  */
62
- export declare const includes: (value: string) => Constraint<string>;
63
- /**
64
- * Operator to restrict results to only arrays that include a value matching the given substring.
65
- */
66
- export declare const includesSubstring: (value: string) => Constraint<string>;
67
- /**
68
- * Operator to restrict results to only arrays that include a value matching the given pattern.
69
- */
70
- export declare const includesPattern: (value: string) => Constraint<string>;
71
- export declare const includesAll: (value: string) => Constraint<string>;
72
- export {};
62
+ export declare const includes: <T>(value: T) => ArrayFilter<T>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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;
3
+ 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;
4
4
  /**
5
5
  * Operator to restrict results to only values that are greater than the given value.
6
6
  */
@@ -71,21 +71,8 @@ exports.isNot = isNot;
71
71
  */
72
72
  const contains = (value) => ({ $contains: value });
73
73
  exports.contains = contains;
74
- // TODO: these can only be applied to columns of type "multiple"
75
74
  /**
76
75
  * Operator to restrict results to only arrays that include the given value.
77
76
  */
78
77
  const includes = (value) => ({ $includes: value });
79
78
  exports.includes = includes;
80
- /**
81
- * Operator to restrict results to only arrays that include a value matching the given substring.
82
- */
83
- const includesSubstring = (value) => ({ $includesSubstring: value });
84
- exports.includesSubstring = includesSubstring;
85
- /**
86
- * Operator to restrict results to only arrays that include a value matching the given pattern.
87
- */
88
- const includesPattern = (value) => ({ $includesPattern: value });
89
- exports.includesPattern = includesPattern;
90
- const includesAll = (value) => ({ $includesAll: value });
91
- exports.includesAll = includesAll;
@@ -1,10 +1,11 @@
1
1
  import { FilterExpression } from '../api/schemas';
2
2
  import { NonEmptyArray, RequiredBy } from '../util/types';
3
- import { DeepConstraint, FilterConstraints, SortDirection, SortFilter } from './filters';
3
+ import { Filter } from './filters';
4
4
  import { Page, Paginable, PaginationOptions, PaginationQueryMeta } from './pagination';
5
5
  import { XataRecord } from './record';
6
6
  import { Repository } from './repository';
7
7
  import { SelectableColumn, SelectedPick, ValueAtColumn } from './selection';
8
+ import { SortDirection, SortFilter } from './sorting';
8
9
  export declare type QueryOptions<T extends XataRecord> = {
9
10
  page?: PaginationOptions;
10
11
  columns?: NonEmptyArray<SelectableColumn<T>>;
@@ -28,25 +29,25 @@ export declare class Query<Record extends XataRecord, Result extends XataRecord
28
29
  * @param queries An array of subqueries.
29
30
  * @returns A new Query object.
30
31
  */
31
- any(...queries: Query<Record, Result>[]): Query<Record, Result>;
32
+ any(...queries: Query<Record, any>[]): Query<Record, Result>;
32
33
  /**
33
34
  * Builds a new query object representing a logical AND between the given subqueries.
34
35
  * @param queries An array of subqueries.
35
36
  * @returns A new Query object.
36
37
  */
37
- all(...queries: Query<Record, Result>[]): Query<Record, Result>;
38
+ all(...queries: Query<Record, any>[]): Query<Record, Result>;
38
39
  /**
39
40
  * Builds a new query object representing a logical OR negating each subquery. In pseudo-code: !q1 OR !q2
40
41
  * @param queries An array of subqueries.
41
42
  * @returns A new Query object.
42
43
  */
43
- not(...queries: Query<Record, Result>[]): Query<Record, Result>;
44
+ not(...queries: Query<Record, any>[]): Query<Record, Result>;
44
45
  /**
45
46
  * Builds a new query object representing a logical AND negating each subquery. In pseudo-code: !q1 AND !q2
46
47
  * @param queries An array of subqueries.
47
48
  * @returns A new Query object.
48
49
  */
49
- none(...queries: Query<Record, Result>[]): Query<Record, Result>;
50
+ none(...queries: Query<Record, any>[]): Query<Record, Result>;
50
51
  /**
51
52
  * Builds a new query object adding one or more constraints. Examples:
52
53
  *
@@ -60,11 +61,10 @@ export declare class Query<Record extends XataRecord, Result extends XataRecord
60
61
  * })
61
62
  * ```
62
63
  *
63
- * @param constraints
64
64
  * @returns A new Query object.
65
65
  */
66
- filter(constraints: FilterConstraints<Record>): Query<Record, Result>;
67
- filter<F extends SelectableColumn<Record>>(column: F, value: FilterConstraints<ValueAtColumn<Record, F>> | DeepConstraint<ValueAtColumn<Record, F>>): Query<Record, Result>;
66
+ filter(filters: Filter<Record>): Query<Record, Result>;
67
+ filter<F extends SelectableColumn<Record>>(column: F, value: Filter<ValueAtColumn<Record, F>>): Query<Record, Result>;
68
68
  /**
69
69
  * Builds a new query with a new sort option.
70
70
  * @param column The column name.
@@ -21,20 +21,39 @@ export declare abstract class Repository<Data extends BaseData, Record extends X
21
21
  * @param objects Array of objects with the column names and the values to be stored in the table.
22
22
  * @returns Array of the persisted records.
23
23
  */
24
- abstract createMany(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
24
+ abstract create(objects: Array<EditableData<Data> & Partial<Identifiable>>): Promise<SelectedPick<Record, ['*']>[]>;
25
25
  /**
26
26
  * Queries a single record from the table given its unique id.
27
27
  * @param id The unique id.
28
28
  * @returns The persisted record for the given id or null if the record could not be found.
29
29
  */
30
30
  abstract read(id: string): Promise<SelectedPick<Record, ['*']> | null>;
31
+ /**
32
+ * Partially update a single record.
33
+ * @param object An object with its id and the columns to be updated.
34
+ * @returns The full persisted record.
35
+ */
36
+ abstract update(object: Partial<EditableData<Data>> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
31
37
  /**
32
38
  * Partially update a single record given its unique id.
33
39
  * @param id The unique id.
34
- * @param object The column names and their values that have to be updatd.
40
+ * @param object The column names and their values that have to be updated.
35
41
  * @returns The full persisted record.
36
42
  */
37
43
  abstract update(id: string, object: Partial<EditableData<Data>>): Promise<SelectedPick<Record, ['*']>>;
44
+ /**
45
+ * Partially updates multiple records.
46
+ * @param objects An array of objects with their ids and columns to be updated.
47
+ * @returns Array of the persisted records.
48
+ */
49
+ abstract update(objects: Array<Partial<EditableData<Data>> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
50
+ /**
51
+ * Creates or updates a single record. If a record exists with the given id,
52
+ * it will be update, otherwise a new record will be created.
53
+ * @param object Object containing the column names with their values to be persisted in the table.
54
+ * @returns The full persisted record.
55
+ */
56
+ abstract createOrUpdate(object: EditableData<Data> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
38
57
  /**
39
58
  * Creates or updates a single record. If a record exists with the given id,
40
59
  * it will be update, otherwise a new record will be created.
@@ -43,12 +62,37 @@ export declare abstract class Repository<Data extends BaseData, Record extends X
43
62
  * @returns The full persisted record.
44
63
  */
45
64
  abstract createOrUpdate(id: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
65
+ /**
66
+ * Creates or updates a single record. If a record exists with the given id,
67
+ * it will be update, otherwise a new record will be created.
68
+ * @param objects Array of objects with the column names and the values to be stored in the table.
69
+ * @returns Array of the persisted records.
70
+ */
71
+ abstract createOrUpdate(objects: Array<EditableData<Data> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
46
72
  /**
47
73
  * Deletes a record given its unique id.
48
74
  * @param id The unique id.
49
75
  * @throws If the record could not be found or there was an error while performing the deletion.
50
76
  */
51
- abstract delete(id: string): void;
77
+ abstract delete(id: string): Promise<void>;
78
+ /**
79
+ * Deletes a record given its unique id.
80
+ * @param id An object with a unique id.
81
+ * @throws If the record could not be found or there was an error while performing the deletion.
82
+ */
83
+ abstract delete(id: Identifiable): Promise<void>;
84
+ /**
85
+ * Deletes a record given a list of unique ids.
86
+ * @param ids The array of unique ids.
87
+ * @throws If the record could not be found or there was an error while performing the deletion.
88
+ */
89
+ abstract delete(ids: string[]): Promise<void>;
90
+ /**
91
+ * Deletes a record given a list of unique ids.
92
+ * @param ids An array of objects with unique ids.
93
+ * @throws If the record could not be found or there was an error while performing the deletion.
94
+ */
95
+ abstract delete(ids: Identifiable[]): Promise<void>;
52
96
  abstract query<Result extends XataRecord>(query: Query<Record, Result>): Promise<Page<Record, Result>>;
53
97
  }
54
98
  export declare class RestRepository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record, SelectedPick<Record, ['*']>> {
@@ -56,11 +100,15 @@ export declare class RestRepository<Data extends BaseData, Record extends XataRe
56
100
  constructor(client: BaseClient<any>, table: string);
57
101
  create(object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
58
102
  create(recordId: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
59
- createMany(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
103
+ create(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
60
104
  read(recordId: string): Promise<SelectedPick<Record, ['*']> | null>;
105
+ update(object: Partial<EditableData<Data>> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
61
106
  update(recordId: string, object: Partial<EditableData<Data>>): Promise<SelectedPick<Record, ['*']>>;
107
+ update(objects: Array<Partial<EditableData<Data>> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
108
+ createOrUpdate(object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
62
109
  createOrUpdate(recordId: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
63
- delete(recordId: string): Promise<void>;
110
+ createOrUpdate(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
111
+ delete(recordId: string | Identifiable | Array<string | Identifiable>): Promise<void>;
64
112
  query<Result extends XataRecord>(query: Query<Record, Result>): Promise<Page<Record, Result>>;
65
113
  }
66
114
  interface RepositoryFactory {
@@ -82,18 +130,18 @@ export declare type XataClientOptions = {
82
130
  */
83
131
  fetch?: FetchImpl;
84
132
  databaseURL?: string;
85
- branch: BranchStrategyOption;
133
+ branch?: BranchStrategyOption;
86
134
  /**
87
135
  * API key to be used. You can create one in your account settings at https://app.xata.io/settings.
88
136
  */
89
- apiKey: string;
137
+ apiKey?: string;
90
138
  repositoryFactory?: RepositoryFactory;
91
139
  };
92
140
  export declare class BaseClient<D extends Record<string, Repository<any>> = Record<string, Repository<any>>> {
93
141
  #private;
94
142
  options: XataClientOptions;
95
143
  db: D;
96
- constructor(options: XataClientOptions, links?: Links);
144
+ constructor(options?: XataClientOptions, links?: Links);
97
145
  initObject<T>(table: string, object: object): T;
98
146
  getBranch(): Promise<string>;
99
147
  }
@@ -26,15 +26,17 @@ var __asyncValues = (this && this.__asyncValues) || function (o) {
26
26
  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
27
27
  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
28
  };
29
- var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _BaseClient_links, _BaseClient_branch;
29
+ var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _RestRepository_insertRecordWithoutId, _RestRepository_insertRecordWithId, _RestRepository_bulkInsertTableRecords, _RestRepository_updateRecordWithID, _RestRepository_upsertRecordWithID, _RestRepository_deleteRecord, _BaseClient_links, _BaseClient_branch;
30
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
31
  exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
32
32
  const api_1 = require("../api");
33
+ const fetch_1 = require("../util/fetch");
33
34
  const lang_1 = require("../util/lang");
34
- const filters_1 = require("./filters");
35
+ const config_1 = require("./config");
35
36
  const pagination_1 = require("./pagination");
36
37
  const query_1 = require("./query");
37
38
  const record_1 = require("./record");
39
+ const sorting_1 = require("./sorting");
38
40
  /**
39
41
  * Common interface for performing operations on a table.
40
42
  */
@@ -43,7 +45,6 @@ class Repository extends query_1.Query {
43
45
  exports.Repository = Repository;
44
46
  class RestRepository extends query_1.Query {
45
47
  constructor(client, table) {
46
- var _a;
47
48
  super(null, table, {});
48
49
  _RestRepository_instances.add(this);
49
50
  _RestRepository_client.set(this, void 0);
@@ -51,80 +52,113 @@ class RestRepository extends query_1.Query {
51
52
  _RestRepository_table.set(this, void 0);
52
53
  __classPrivateFieldSet(this, _RestRepository_client, client, "f");
53
54
  __classPrivateFieldSet(this, _RestRepository_table, table, "f");
54
- // TODO: Remove when integrating with API client
55
- const globalFetch = typeof fetch !== 'undefined' ? fetch : undefined;
56
- const fetchImpl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch) !== null && _a !== void 0 ? _a : globalFetch;
57
- if (!fetchImpl) {
58
- /** @todo add a link after docs exist */
59
- throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
60
- }
61
- __classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f");
55
+ __classPrivateFieldSet(this, _RestRepository_fetch, (0, fetch_1.getFetchImplementation)(__classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch), "f");
62
56
  }
63
57
  create(a, b) {
64
58
  return __awaiter(this, void 0, void 0, function* () {
59
+ // Create many records
60
+ if (Array.isArray(a)) {
61
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_bulkInsertTableRecords).call(this, a);
62
+ }
63
+ // Create one record with id as param
65
64
  if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
66
65
  if (a === '')
67
66
  throw new Error("The id can't be empty");
68
67
  return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a, b);
69
68
  }
70
- else if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
69
+ // Create one record with id as property
70
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
71
71
  if (a.id === '')
72
72
  throw new Error("The id can't be empty");
73
73
  return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithId).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
74
74
  }
75
- else if ((0, lang_1.isObject)(a)) {
75
+ // Create one record without id
76
+ if ((0, lang_1.isObject)(a)) {
76
77
  return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_insertRecordWithoutId).call(this, a);
77
78
  }
78
- else {
79
- throw new Error('Invalid arguments for create method');
80
- }
81
- });
82
- }
83
- createMany(objects) {
84
- return __awaiter(this, void 0, void 0, function* () {
85
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
86
- const records = objects.map((object) => transformObjectLinks(object));
87
- const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
88
- const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
89
- if (finalObjects.length !== objects.length) {
90
- throw new Error('The server failed to save some records');
91
- }
92
- return finalObjects;
79
+ throw new Error('Invalid arguments for create method');
93
80
  });
94
81
  }
95
82
  // TODO: Add column support: https://github.com/xataio/openapi/issues/139
96
83
  read(recordId) {
97
84
  return __awaiter(this, void 0, void 0, function* () {
98
85
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
99
- const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
100
- return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
86
+ try {
87
+ const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
88
+ return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
89
+ }
90
+ catch (e) {
91
+ if ((0, lang_1.isObject)(e) && e.status === 404) {
92
+ return null;
93
+ }
94
+ throw e;
95
+ }
101
96
  });
102
97
  }
103
- update(recordId, object) {
98
+ update(a, b) {
104
99
  return __awaiter(this, void 0, void 0, function* () {
105
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
106
- const record = transformObjectLinks(object);
107
- const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
108
- const item = yield this.read(response.id);
109
- if (!item)
110
- throw new Error('The server failed to save the record');
111
- return item;
100
+ // Update many records
101
+ if (Array.isArray(a)) {
102
+ if (a.length > 100) {
103
+ // TODO: Implement bulk update when API has support for it
104
+ console.warn('Bulk update operation is not optimized in the Xata API yet, this request might be slow');
105
+ }
106
+ return Promise.all(a.map((object) => this.update(object)));
107
+ }
108
+ // Update one record with id as param
109
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
110
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_updateRecordWithID).call(this, a, b);
111
+ }
112
+ // Update one record with id as property
113
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
114
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_updateRecordWithID).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
115
+ }
116
+ throw new Error('Invalid arguments for update method');
112
117
  });
113
118
  }
114
- createOrUpdate(recordId, object) {
119
+ createOrUpdate(a, b) {
115
120
  return __awaiter(this, void 0, void 0, function* () {
116
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
117
- const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
118
- const item = yield this.read(response.id);
119
- if (!item)
120
- throw new Error('The server failed to save the record');
121
- return item;
121
+ // Create or update many records
122
+ if (Array.isArray(a)) {
123
+ if (a.length > 100) {
124
+ // TODO: Implement bulk update when API has support for it
125
+ console.warn('Bulk update operation is not optimized in the Xata API yet, this request might be slow');
126
+ }
127
+ return Promise.all(a.map((object) => this.createOrUpdate(object)));
128
+ }
129
+ // Create or update one record with id as param
130
+ if ((0, lang_1.isString)(a) && (0, lang_1.isObject)(b)) {
131
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_upsertRecordWithID).call(this, a, b);
132
+ }
133
+ // Create or update one record with id as property
134
+ if ((0, lang_1.isObject)(a) && (0, lang_1.isString)(a.id)) {
135
+ return __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_upsertRecordWithID).call(this, a.id, Object.assign(Object.assign({}, a), { id: undefined }));
136
+ }
137
+ throw new Error('Invalid arguments for createOrUpdate method');
122
138
  });
123
139
  }
124
140
  delete(recordId) {
125
141
  return __awaiter(this, void 0, void 0, function* () {
126
- const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
127
- yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
142
+ // Delete many records
143
+ if (Array.isArray(recordId)) {
144
+ if (recordId.length > 100) {
145
+ // TODO: Implement bulk delete when API has support for it
146
+ console.warn('Bulk delete operation is not optimized in the Xata API yet, this request might be slow');
147
+ }
148
+ yield Promise.all(recordId.map((id) => this.delete(id)));
149
+ return;
150
+ }
151
+ // Delete one record with id as param
152
+ if ((0, lang_1.isString)(recordId)) {
153
+ yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_deleteRecord).call(this, recordId);
154
+ return;
155
+ }
156
+ // Delete one record with id as property
157
+ if ((0, lang_1.isObject)(recordId) && (0, lang_1.isString)(recordId.id)) {
158
+ yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_deleteRecord).call(this, recordId.id);
159
+ return;
160
+ }
161
+ throw new Error('Invalid arguments for delete method');
128
162
  });
129
163
  }
130
164
  query(query) {
@@ -133,7 +167,7 @@ class RestRepository extends query_1.Query {
133
167
  const data = query.getQueryOptions();
134
168
  const body = {
135
169
  filter: Object.values((_a = data.filter) !== null && _a !== void 0 ? _a : {}).some(Boolean) ? data.filter : undefined,
136
- sort: (0, filters_1.buildSortFilter)(data.sort),
170
+ sort: data.sort ? (0, sorting_1.buildSortFilter)(data.sort) : undefined,
137
171
  page: data.page,
138
172
  columns: data.columns
139
173
  };
@@ -146,11 +180,16 @@ class RestRepository extends query_1.Query {
146
180
  }
147
181
  exports.RestRepository = RestRepository;
148
182
  _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() {
183
+ var _a;
149
184
  return __awaiter(this, void 0, void 0, function* () {
150
185
  const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
186
+ const apiKey = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey) !== null && _a !== void 0 ? _a : (0, config_1.getAPIKey)();
187
+ if (!apiKey) {
188
+ throw new Error('Could not resolve a valid apiKey');
189
+ }
151
190
  return {
152
191
  fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"),
153
- apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey,
192
+ apiKey,
154
193
  apiUrl: '',
155
194
  // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
156
195
  workspacesApiUrl: (path, params) => {
@@ -193,6 +232,41 @@ _RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _
193
232
  }
194
233
  return finalObject;
195
234
  });
235
+ }, _RestRepository_bulkInsertTableRecords = function _RestRepository_bulkInsertTableRecords(objects) {
236
+ return __awaiter(this, void 0, void 0, function* () {
237
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
238
+ const records = objects.map((object) => transformObjectLinks(object));
239
+ const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
240
+ const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
241
+ if (finalObjects.length !== objects.length) {
242
+ throw new Error('The server failed to save some records');
243
+ }
244
+ return finalObjects;
245
+ });
246
+ }, _RestRepository_updateRecordWithID = function _RestRepository_updateRecordWithID(recordId, object) {
247
+ return __awaiter(this, void 0, void 0, function* () {
248
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
249
+ const record = transformObjectLinks(object);
250
+ const response = yield (0, api_1.updateRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: record }, fetchProps));
251
+ const item = yield this.read(response.id);
252
+ if (!item)
253
+ throw new Error('The server failed to save the record');
254
+ return item;
255
+ });
256
+ }, _RestRepository_upsertRecordWithID = function _RestRepository_upsertRecordWithID(recordId, object) {
257
+ return __awaiter(this, void 0, void 0, function* () {
258
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
259
+ const response = yield (0, api_1.upsertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps));
260
+ const item = yield this.read(response.id);
261
+ if (!item)
262
+ throw new Error('The server failed to save the record');
263
+ return item;
264
+ });
265
+ }, _RestRepository_deleteRecord = function _RestRepository_deleteRecord(recordId) {
266
+ return __awaiter(this, void 0, void 0, function* () {
267
+ const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
268
+ yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps));
269
+ });
196
270
  };
197
271
  class RestRespositoryFactory {
198
272
  createRepository(client, table) {
@@ -200,16 +274,31 @@ class RestRespositoryFactory {
200
274
  }
201
275
  }
202
276
  exports.RestRespositoryFactory = RestRespositoryFactory;
277
+ function resolveXataClientOptions(options) {
278
+ const databaseURL = (options === null || options === void 0 ? void 0 : options.databaseURL) || (0, config_1.getDatabaseUrl)() || '';
279
+ const apiKey = (options === null || options === void 0 ? void 0 : options.apiKey) || (0, config_1.getAPIKey)() || '';
280
+ const branch = (options === null || options === void 0 ? void 0 : options.branch) ||
281
+ (() => (0, config_1.getBranch)({
282
+ apiKey,
283
+ apiUrl: databaseURL,
284
+ fetchImpl: (0, fetch_1.getFetchImplementation)(options === null || options === void 0 ? void 0 : options.fetch)
285
+ }));
286
+ if (!databaseURL || !apiKey) {
287
+ throw new Error('Options databaseURL and apiKey are required');
288
+ }
289
+ return Object.assign(Object.assign({}, options), { databaseURL,
290
+ apiKey,
291
+ branch });
292
+ }
203
293
  class BaseClient {
204
- constructor(options, links = {}) {
294
+ constructor(options = {}, links = {}) {
205
295
  _BaseClient_links.set(this, void 0);
206
296
  _BaseClient_branch.set(this, void 0);
207
- if (!options.databaseURL || !options.apiKey || !options.branch) {
208
- throw new Error('Options databaseURL, apiKey and branch are required');
209
- }
210
- this.options = options;
297
+ this.options = resolveXataClientOptions(options);
298
+ // Make this property not enumerable so it doesn't show up in console.dir, etc.
299
+ Object.defineProperty(this.options, 'apiKey', { enumerable: false });
211
300
  __classPrivateFieldSet(this, _BaseClient_links, links, "f");
212
- const factory = options.repositoryFactory || new RestRespositoryFactory();
301
+ const factory = this.options.repositoryFactory || new RestRespositoryFactory();
213
302
  this.db = new Proxy({}, {
214
303
  get: (_target, prop) => {
215
304
  if (typeof prop !== 'string')
@@ -4,7 +4,7 @@ export declare type SelectableColumn<O, RecursivePath extends any[] = []> = '*'
4
4
  export declare type SelectedPick<O extends XataRecord, Key extends SelectableColumn<O>[]> = XataRecord & UnionToIntersection<Values<{
5
5
  [K in Key[number]]: NestedValueAtColumn<O, K> & XataRecord;
6
6
  }>>;
7
- export declare type ValueAtColumn<O extends XataRecord, P extends SelectableColumn<O>> = P extends '*' ? Values<O> : P extends 'id' ? string : P extends keyof O ? O[P] : P extends `${infer K}.${infer V}` ? K extends keyof O ? Values<O[K] extends XataRecord ? (V extends SelectableColumn<O[K]> ? {
7
+ export declare type ValueAtColumn<O, P extends SelectableColumn<O>> = P extends '*' ? Values<O> : P extends 'id' ? string : P extends keyof O ? O[P] : P extends `${infer K}.${infer V}` ? K extends keyof O ? Values<O[K] extends XataRecord ? (V extends SelectableColumn<O[K]> ? {
8
8
  V: ValueAtColumn<O[K], V>;
9
9
  } : never) : O[K]> : never : never;
10
10
  declare type MAX_RECURSION = 5;
@@ -0,0 +1,17 @@
1
+ import { SingleOrArray, Values } from '../util/types';
2
+ import { XataRecord } from './record';
3
+ import { SelectableColumn } from './selection';
4
+ export declare type SortDirection = 'asc' | 'desc';
5
+ export declare type SortFilterExtended<T extends XataRecord> = {
6
+ column: SelectableColumn<T>;
7
+ direction?: SortDirection;
8
+ };
9
+ export declare type SortFilter<T extends XataRecord> = SelectableColumn<T> | SortFilterExtended<T>;
10
+ export declare type ApiSortFilter<T extends XataRecord> = SingleOrArray<Values<{
11
+ [key in SelectableColumn<T>]: {
12
+ [K in key]: SortDirection;
13
+ };
14
+ }>>;
15
+ export declare function isSortFilterString<T extends XataRecord>(value: any): value is SelectableColumn<T>;
16
+ export declare function isSortFilterObject<T extends XataRecord>(filter: SortFilter<T>): filter is SortFilterExtended<T>;
17
+ export declare function buildSortFilter<T extends XataRecord>(filter: SingleOrArray<SortFilter<T>>): ApiSortFilter<T>;