@xata.io/client 0.3.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # @xata.io/client
2
2
 
3
+ ## 0.5.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 12729ab: Make API client fetch implementation optional
8
+
9
+ ## 0.5.0
10
+
11
+ ### Patch Changes
12
+
13
+ - 14ec7d1: Fix in Selectable type
14
+
15
+ ## 0.4.0
16
+
17
+ ### Patch Changes
18
+
19
+ - b951331: Add support for new float column
20
+ - d470610: Add new getAll() method
21
+ - eaf92a8: Expose pagination constants (size and offset limits)
22
+ - 57fde77: Reduce subrequests for createMany
23
+ - eaf92a8: Implement schema-less client
24
+ - 97a3caa: Make createBranch from optional with empty branch
25
+
3
26
  ## 0.3.0
4
27
 
5
28
  ### Minor Changes
@@ -4,7 +4,7 @@ import { HostProvider } from './providers';
4
4
  import type * as Responses from './responses';
5
5
  import type * as Schemas from './schemas';
6
6
  export interface XataApiClientOptions {
7
- fetch: FetchImpl;
7
+ fetch?: FetchImpl;
8
8
  apiKey: string;
9
9
  host?: HostProvider;
10
10
  }
@@ -17,14 +17,15 @@ const components_1 = require("./components");
17
17
  const providers_1 = require("./providers");
18
18
  class XataApiClient {
19
19
  constructor(options) {
20
- var _a;
20
+ var _a, _b;
21
21
  _XataApiClient_extraProps.set(this, void 0);
22
- const fetchImpl = typeof fetch !== 'undefined' ? fetch : options.fetch;
22
+ const globalFetch = typeof fetch !== 'undefined' ? fetch : undefined;
23
+ const fetchImpl = (_a = options.fetch) !== null && _a !== void 0 ? _a : globalFetch;
23
24
  if (!fetchImpl) {
24
25
  /** @todo add a link after docs exist */
25
26
  throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
26
27
  }
27
- const provider = (_a = options.host) !== null && _a !== void 0 ? _a : 'production';
28
+ const provider = (_b = options.host) !== null && _b !== void 0 ? _b : 'production';
28
29
  __classPrivateFieldSet(this, _XataApiClient_extraProps, {
29
30
  apiUrl: (0, providers_1.getHostUrl)(provider, 'main'),
30
31
  workspacesApiUrl: (0, providers_1.getHostUrl)(provider, 'workspaces'),
@@ -141,7 +142,7 @@ class BranchApi {
141
142
  getBranchDetails(workspace, database, branch) {
142
143
  return components_1.operationsByTag.branch.getBranchDetails(Object.assign({ pathParams: { workspace, dbBranchName: `${database}:${branch}` } }, this.extraProps));
143
144
  }
144
- createBranch(workspace, database, branch, from, options = {}) {
145
+ createBranch(workspace, database, branch, from = '', options = {}) {
145
146
  return components_1.operationsByTag.branch.createBranch(Object.assign({ pathParams: { workspace, dbBranchName: `${database}:${branch}` }, queryParams: { from }, body: options }, this.extraProps));
146
147
  }
147
148
  deleteBranch(workspace, database, branch) {
@@ -875,7 +875,7 @@ export declare type QueryTableVariables = {
875
875
  * `$none`, etc.
876
876
  *
877
877
  * All operators start with an `$` to differentiate them from column names
878
- * (which are not allowed to start with an underscore).
878
+ * (which are not allowed to start with an dollar sign).
879
879
  *
880
880
  * #### Exact matching and control operators
881
881
  *
@@ -943,27 +943,17 @@ export declare type QueryTableVariables = {
943
943
  * }
944
944
  * ```
945
945
  *
946
- * If you want to OR together multiple values, you can use an array of values:
946
+ * If you want to OR together multiple values, you can use the `$any` operator with an array of values:
947
947
  *
948
948
  * ```json
949
949
  * {
950
950
  * "filter": {
951
- * "settings.plan": ["free", "paid"]
951
+ * "settings.plan": {"$any": ["free", "paid"]}
952
952
  * },
953
953
  * }
954
954
  * ```
955
955
  *
956
- * Same query with `$is` operator:
957
- *
958
- * ```json
959
- * {
960
- * "filter": {
961
- * "settings.plan": { "$is": ["free", "paid"]}
962
- * },
963
- * }
964
- * ```
965
- *
966
- * Specifying multiple columns, ANDs them together:
956
+ * If you specify multiple columns in the same filter, they are logically AND'ed together:
967
957
  *
968
958
  * ```json
969
959
  * {
@@ -974,6 +964,8 @@ export declare type QueryTableVariables = {
974
964
  * }
975
965
  * ```
976
966
  *
967
+ * The above matches if both conditions are met.
968
+ *
977
969
  * To be more explicit about it, you can use `$all` or `$any`:
978
970
  *
979
971
  * ```json
@@ -981,13 +973,13 @@ export declare type QueryTableVariables = {
981
973
  * "filter": {
982
974
  * "$any": {
983
975
  * "settings.dark": true,
984
- * "settings.plan": "free",
976
+ * "settings.plan": "free"
985
977
  * }
986
978
  * },
987
979
  * }
988
980
  * ```
989
981
  *
990
- * `$all` and `$any` can also receive an array of objects, which allows for repeating columns:
982
+ * The `$all` and `$any` operators can also receive an array of objects, which allows for repeating column names:
991
983
  *
992
984
  * ```json
993
985
  * {
@@ -1030,7 +1022,7 @@ export declare type QueryTableVariables = {
1030
1022
  * }
1031
1023
  * ```
1032
1024
  *
1033
- * We can also make the negation version, `$notExists` :
1025
+ * Or you can use the inverse operator `$notExists`:
1034
1026
  *
1035
1027
  * ```json
1036
1028
  * {
@@ -1083,7 +1075,7 @@ export declare type QueryTableVariables = {
1083
1075
  * }
1084
1076
  * ```
1085
1077
  *
1086
- * #### Numeric/date ranges
1078
+ * #### Numeric ranges
1087
1079
  *
1088
1080
  * ```json
1089
1081
  * {
@@ -1098,18 +1090,6 @@ export declare type QueryTableVariables = {
1098
1090
  *
1099
1091
  * The supported operators are `$gt`, `$lt`, `$ge`, `$le`.
1100
1092
  *
1101
- * Date ranges would support the same operators, with the date as string in RFC 3339:
1102
- *
1103
- * ```json
1104
- * {
1105
- * "filter": {
1106
- * "<column_name>": {
1107
- * "$gt": "2019-10-12T07:20:50.52Z",
1108
- * "$lt": "2021-10-12T07:20:50.52Z"
1109
- * }
1110
- * }
1111
- * }
1112
- * ```
1113
1093
  *
1114
1094
  * #### Negations
1115
1095
  *
@@ -1162,7 +1142,7 @@ export declare type QueryTableVariables = {
1162
1142
  * }
1163
1143
  * ```
1164
1144
  *
1165
- * In addition, we can add specific operators like `$isNot` to simplify expressions:
1145
+ * In addition, you can use operators like `$isNot` or `$notExists` to simplify expressions:
1166
1146
  *
1167
1147
  * ```json
1168
1148
  * {
@@ -1213,6 +1193,22 @@ export declare type QueryTableVariables = {
1213
1193
  * predicate. The `$includes` operator is a synonym for the `$includesAny`
1214
1194
  * operator.
1215
1195
  *
1196
+ * Here is an example of using the `$includesAll` operator:
1197
+ *
1198
+ * ```json
1199
+ * {
1200
+ * "filter": {
1201
+ * "settings.labels": {
1202
+ * "$includesAll": [
1203
+ * {"$contains": "label"},
1204
+ * ]
1205
+ * }
1206
+ * }
1207
+ * }
1208
+ * ```
1209
+ *
1210
+ * The above matches if all label values contain the string "labels".
1211
+ *
1216
1212
  * ### Sorting
1217
1213
  *
1218
1214
  * Sorting by one element:
@@ -458,7 +458,7 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
458
458
  * `$none`, etc.
459
459
  *
460
460
  * All operators start with an `$` to differentiate them from column names
461
- * (which are not allowed to start with an underscore).
461
+ * (which are not allowed to start with an dollar sign).
462
462
  *
463
463
  * #### Exact matching and control operators
464
464
  *
@@ -526,27 +526,17 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
526
526
  * }
527
527
  * ```
528
528
  *
529
- * If you want to OR together multiple values, you can use an array of values:
529
+ * If you want to OR together multiple values, you can use the `$any` operator with an array of values:
530
530
  *
531
531
  * ```json
532
532
  * {
533
533
  * "filter": {
534
- * "settings.plan": ["free", "paid"]
534
+ * "settings.plan": {"$any": ["free", "paid"]}
535
535
  * },
536
536
  * }
537
537
  * ```
538
538
  *
539
- * Same query with `$is` operator:
540
- *
541
- * ```json
542
- * {
543
- * "filter": {
544
- * "settings.plan": { "$is": ["free", "paid"]}
545
- * },
546
- * }
547
- * ```
548
- *
549
- * Specifying multiple columns, ANDs them together:
539
+ * If you specify multiple columns in the same filter, they are logically AND'ed together:
550
540
  *
551
541
  * ```json
552
542
  * {
@@ -557,6 +547,8 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
557
547
  * }
558
548
  * ```
559
549
  *
550
+ * The above matches if both conditions are met.
551
+ *
560
552
  * To be more explicit about it, you can use `$all` or `$any`:
561
553
  *
562
554
  * ```json
@@ -564,13 +556,13 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
564
556
  * "filter": {
565
557
  * "$any": {
566
558
  * "settings.dark": true,
567
- * "settings.plan": "free",
559
+ * "settings.plan": "free"
568
560
  * }
569
561
  * },
570
562
  * }
571
563
  * ```
572
564
  *
573
- * `$all` and `$any` can also receive an array of objects, which allows for repeating columns:
565
+ * The `$all` and `$any` operators can also receive an array of objects, which allows for repeating column names:
574
566
  *
575
567
  * ```json
576
568
  * {
@@ -613,7 +605,7 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
613
605
  * }
614
606
  * ```
615
607
  *
616
- * We can also make the negation version, `$notExists` :
608
+ * Or you can use the inverse operator `$notExists`:
617
609
  *
618
610
  * ```json
619
611
  * {
@@ -666,7 +658,7 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
666
658
  * }
667
659
  * ```
668
660
  *
669
- * #### Numeric/date ranges
661
+ * #### Numeric ranges
670
662
  *
671
663
  * ```json
672
664
  * {
@@ -681,18 +673,6 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
681
673
  *
682
674
  * The supported operators are `$gt`, `$lt`, `$ge`, `$le`.
683
675
  *
684
- * Date ranges would support the same operators, with the date as string in RFC 3339:
685
- *
686
- * ```json
687
- * {
688
- * "filter": {
689
- * "<column_name>": {
690
- * "$gt": "2019-10-12T07:20:50.52Z",
691
- * "$lt": "2021-10-12T07:20:50.52Z"
692
- * }
693
- * }
694
- * }
695
- * ```
696
676
  *
697
677
  * #### Negations
698
678
  *
@@ -745,7 +725,7 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
745
725
  * }
746
726
  * ```
747
727
  *
748
- * In addition, we can add specific operators like `$isNot` to simplify expressions:
728
+ * In addition, you can use operators like `$isNot` or `$notExists` to simplify expressions:
749
729
  *
750
730
  * ```json
751
731
  * {
@@ -796,6 +776,22 @@ exports.bulkInsertTableRecords = bulkInsertTableRecords;
796
776
  * predicate. The `$includes` operator is a synonym for the `$includesAny`
797
777
  * operator.
798
778
  *
779
+ * Here is an example of using the `$includesAll` operator:
780
+ *
781
+ * ```json
782
+ * {
783
+ * "filter": {
784
+ * "settings.labels": {
785
+ * "$includesAll": [
786
+ * {"$contains": "label"},
787
+ * ]
788
+ * }
789
+ * }
790
+ * }
791
+ * ```
792
+ *
793
+ * The above matches if all label values contain the string "labels".
794
+ *
799
795
  * ### Sorting
800
796
  *
801
797
  * Sorting by one element:
@@ -130,7 +130,7 @@ export declare type Table = {
130
130
  */
131
131
  export declare type Column = {
132
132
  name: string;
133
- type: 'bool' | 'int' | 'string' | 'text' | 'email' | 'multiple' | 'link' | 'object';
133
+ type: 'bool' | 'int' | 'float' | 'string' | 'text' | 'email' | 'multiple' | 'link' | 'object';
134
134
  link?: {
135
135
  table: string;
136
136
  };
@@ -1,5 +1,6 @@
1
1
  export * from './operators';
2
- export type { XataRecord } from './record';
3
- export { Repository, RestRepository, RestRespositoryFactory, BaseClient } from './repository';
4
- export type { XataClientOptions } from './repository';
2
+ export * from './pagination';
5
3
  export { Query } from './query';
4
+ export type { Identifiable, XataRecord } from './record';
5
+ export { BaseClient, Repository, RestRepository, RestRespositoryFactory } from './repository';
6
+ export type { XataClientOptions } from './repository';
@@ -14,12 +14,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.Query = exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
17
+ exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = exports.BaseClient = exports.Query = void 0;
18
18
  __exportStar(require("./operators"), exports);
19
+ __exportStar(require("./pagination"), exports);
20
+ var query_1 = require("./query");
21
+ Object.defineProperty(exports, "Query", { enumerable: true, get: function () { return query_1.Query; } });
19
22
  var repository_1 = require("./repository");
23
+ Object.defineProperty(exports, "BaseClient", { enumerable: true, get: function () { return repository_1.BaseClient; } });
20
24
  Object.defineProperty(exports, "Repository", { enumerable: true, get: function () { return repository_1.Repository; } });
21
25
  Object.defineProperty(exports, "RestRepository", { enumerable: true, get: function () { return repository_1.RestRepository; } });
22
26
  Object.defineProperty(exports, "RestRespositoryFactory", { enumerable: true, get: function () { return repository_1.RestRespositoryFactory; } });
23
- Object.defineProperty(exports, "BaseClient", { enumerable: true, get: function () { return repository_1.BaseClient; } });
24
- var query_1 = require("./query");
25
- Object.defineProperty(exports, "Query", { enumerable: true, get: function () { return query_1.Query; } });
@@ -1,5 +1,5 @@
1
- import { XataRecord } from '..';
2
1
  import { Query } from './query';
2
+ import { XataRecord } from './record';
3
3
  export declare type PaginationQueryMeta = {
4
4
  page: {
5
5
  cursor: string;
@@ -19,7 +19,7 @@ export interface Paginable<T extends XataRecord, R extends XataRecord = T> {
19
19
  * A Page contains a set of results from a query plus metadata about the retrieved
20
20
  * set of values such as the cursor, required to retrieve additional records.
21
21
  */
22
- export declare class Page<T extends XataRecord, R extends XataRecord> implements Paginable<T, R> {
22
+ export declare class Page<T extends XataRecord, R extends XataRecord = T> implements Paginable<T, R> {
23
23
  #private;
24
24
  /**
25
25
  * Page metadata, required to retrieve additional records.
@@ -77,3 +77,7 @@ export declare type OffsetNavigationOptions = {
77
77
  offset?: number;
78
78
  };
79
79
  export declare type PaginationOptions = CursorNavigationOptions & OffsetNavigationOptions;
80
+ export declare const PAGINATION_MAX_SIZE = 200;
81
+ export declare const PAGINATION_DEFAULT_SIZE = 200;
82
+ export declare const PAGINATION_MAX_OFFSET = 800;
83
+ export declare const PAGINATION_DEFAULT_OFFSET = 0;
@@ -21,7 +21,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
21
21
  };
22
22
  var _Page_query;
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.Page = void 0;
24
+ exports.PAGINATION_DEFAULT_OFFSET = exports.PAGINATION_MAX_OFFSET = exports.PAGINATION_DEFAULT_SIZE = exports.PAGINATION_MAX_SIZE = exports.Page = void 0;
25
25
  /**
26
26
  * A Page contains a set of results from a query plus metadata about the retrieved
27
27
  * set of values such as the cursor, required to retrieve additional records.
@@ -88,3 +88,7 @@ class Page {
88
88
  }
89
89
  exports.Page = Page;
90
90
  _Page_query = new WeakMap();
91
+ exports.PAGINATION_MAX_SIZE = 200;
92
+ exports.PAGINATION_DEFAULT_SIZE = 200;
93
+ exports.PAGINATION_MAX_OFFSET = 800;
94
+ exports.PAGINATION_DEFAULT_OFFSET = 0;
@@ -1,8 +1,9 @@
1
- import { XataRecord, Repository } from '..';
2
- import { FilterExpression, SortExpression, PageConfig, ColumnsFilter } from '../api/schemas';
1
+ import { ColumnsFilter, FilterExpression, PageConfig, SortExpression } from '../api/schemas';
3
2
  import { DeepConstraint, FilterConstraints, SortDirection, SortFilter } from './filters';
4
- import { PaginationOptions, Page, Paginable, PaginationQueryMeta } from './pagination';
5
- import { Selectable, SelectableColumn, Select } from './selection';
3
+ import { Page, Paginable, PaginationOptions, PaginationQueryMeta } from './pagination';
4
+ import { XataRecord } from './record';
5
+ import { Repository } from './repository';
6
+ import { Select, Selectable, SelectableColumn } from './selection';
6
7
  export declare type QueryOptions<T extends XataRecord> = {
7
8
  page?: PaginationOptions;
8
9
  columns?: Extract<keyof Selectable<T>, string>[];
@@ -81,27 +82,28 @@ export declare class Query<T extends XataRecord, R extends XataRecord = T> imple
81
82
  * @returns A new Query object.
82
83
  */
83
84
  select<K extends SelectableColumn<T>>(columns: K[]): Query<T, Select<T, K>>;
84
- getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, typeof options extends {
85
- columns: SelectableColumn<T>[];
86
- } ? Select<T, typeof options['columns'][number]> : R>>;
85
+ getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, GetWithColumnOptions<T, R, typeof options>>>;
87
86
  [Symbol.asyncIterator](): AsyncIterableIterator<R>;
88
- getIterator(chunk: number, options?: Omit<QueryOptions<T>, 'page'>): AsyncGenerator<R[]>;
87
+ getIterator<Options extends QueryOptions<T>>(chunk: number, options?: Omit<Options, 'page'>): AsyncGenerator<GetWithColumnOptions<T, R, typeof options>[]>;
89
88
  /**
90
89
  * Performs the query in the database and returns a set of results.
91
90
  * @param options Additional options to be used when performing the query.
92
91
  * @returns An array of records from the database.
93
92
  */
94
- getMany<Options extends QueryOptions<T>>(options?: Options): Promise<(typeof options extends {
95
- columns: SelectableColumn<T>[];
96
- } ? Select<T, typeof options['columns'][number]> : R)[]>;
93
+ getMany<Options extends QueryOptions<T>>(options?: Options): Promise<GetWithColumnOptions<T, R, typeof options>[]>;
94
+ /**
95
+ * Performs the query in the database and returns all the results.
96
+ * Warning: If there are a large number of results, this method can have performance implications.
97
+ * @param options Additional options to be used when performing the query.
98
+ * @returns An array of records from the database.
99
+ */
100
+ getAll<Options extends QueryOptions<T>>(chunk?: number, options?: Omit<Options, 'page'>): Promise<GetWithColumnOptions<T, R, typeof options>[]>;
97
101
  /**
98
102
  * Performs the query in the database and returns the first result.
99
103
  * @param options Additional options to be used when performing the query.
100
104
  * @returns The first record that matches the query, or null if no record matched the query.
101
105
  */
102
- getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<(typeof options extends {
103
- columns: SelectableColumn<T>[];
104
- } ? Select<T, typeof options['columns'][number]> : R) | null>;
106
+ getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<GetWithColumnOptions<T, R, typeof options> | null>;
105
107
  /**async deleteAll(): Promise<number> {
106
108
  // TODO: Return number of affected rows
107
109
  return 0;
@@ -112,3 +114,16 @@ export declare class Query<T extends XataRecord, R extends XataRecord = T> imple
112
114
  lastPage(size?: number, offset?: number): Promise<Page<T, R>>;
113
115
  hasNextPage(): boolean;
114
116
  }
117
+ /**
118
+ * Helper type to read options and compute the correct type for the result values
119
+ * T: Original type
120
+ * R: Default destination type
121
+ * Options: QueryOptions
122
+ *
123
+ * If the columns are overriden in the options, the result type is the pick of the original type and the columns
124
+ * If the columns are not overriden, the result type is the default destination type
125
+ */
126
+ declare type GetWithColumnOptions<T, R, Options> = Options extends {
127
+ columns: SelectableColumn<T>[];
128
+ } ? Select<T, Options['columns'][number]> : R;
129
+ export {};
@@ -42,6 +42,7 @@ var _Query_table, _Query_repository, _Query_data;
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
43
  exports.Query = void 0;
44
44
  const lang_1 = require("../util/lang");
45
+ const pagination_1 = require("./pagination");
45
46
  /**
46
47
  * Query objects contain the information of all filters, sorting, etc. to be included in the database query.
47
48
  *
@@ -193,6 +194,32 @@ class Query {
193
194
  return records;
194
195
  });
195
196
  }
197
+ /**
198
+ * Performs the query in the database and returns all the results.
199
+ * Warning: If there are a large number of results, this method can have performance implications.
200
+ * @param options Additional options to be used when performing the query.
201
+ * @returns An array of records from the database.
202
+ */
203
+ getAll(chunk = pagination_1.PAGINATION_MAX_SIZE, options = {}) {
204
+ var e_2, _a;
205
+ return __awaiter(this, void 0, void 0, function* () {
206
+ const results = [];
207
+ try {
208
+ for (var _b = __asyncValues(this.getIterator(chunk, options)), _c; _c = yield _b.next(), !_c.done;) {
209
+ const page = _c.value;
210
+ results.push(...page);
211
+ }
212
+ }
213
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
214
+ finally {
215
+ try {
216
+ if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
217
+ }
218
+ finally { if (e_2) throw e_2.error; }
219
+ }
220
+ return results;
221
+ });
222
+ }
196
223
  /**
197
224
  * Performs the query in the database and returns the first result.
198
225
  * @param options Additional options to be used when performing the query.
@@ -1,12 +1,20 @@
1
1
  import { Selectable } from './selection';
2
2
  /**
3
- * Represents a persisted record from the database.
3
+ * Represents an identifiable record from the database.
4
4
  */
5
- export interface XataRecord {
5
+ export interface Identifiable {
6
6
  /**
7
7
  * Unique id of this record.
8
8
  */
9
9
  id: string;
10
+ }
11
+ export interface BaseData {
12
+ [key: string]: any;
13
+ }
14
+ /**
15
+ * Represents a persisted record from the database.
16
+ */
17
+ export interface XataRecord extends Identifiable {
10
18
  /**
11
19
  * Metadata of this record.
12
20
  */
@@ -1,45 +1,40 @@
1
1
  import { FetchImpl } from '../api/fetcher';
2
2
  import { Page } from './pagination';
3
3
  import { Query, QueryOptions } from './query';
4
- import { XataRecord } from './record';
5
- import { Selectable, SelectableColumn, Select } from './selection';
4
+ import { BaseData, XataRecord } from './record';
5
+ import { Select, SelectableColumn } from './selection';
6
6
  export declare type Links = Record<string, Array<string[]>>;
7
7
  /**
8
8
  * Common interface for performing operations on a table.
9
9
  */
10
- export declare abstract class Repository<T extends XataRecord> extends Query<T> {
11
- /**
12
- * Creates a record in the table.
13
- * @param object Object containing the column names with their values to be stored in the table.
14
- * @returns The full persisted record.
15
- */
16
- abstract create(object: Selectable<T>): Promise<T>;
10
+ export declare abstract class Repository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record> {
11
+ abstract create(object: Data): Promise<Record>;
17
12
  /**
18
13
  * Creates multiple records in the table.
19
14
  * @param objects Array of objects with the column names and the values to be stored in the table.
20
15
  * @returns Array of the persisted records.
21
16
  */
22
- abstract createMany(objects: Selectable<T>[]): Promise<T[]>;
17
+ abstract createMany(objects: Data[]): Promise<Record[]>;
23
18
  /**
24
19
  * Queries a single record from the table given its unique id.
25
20
  * @param id The unique id.
26
21
  * @returns The persisted record for the given id or null if the record could not be found.
27
22
  */
28
- abstract read(id: string): Promise<T | null>;
23
+ abstract read(id: string): Promise<Record | null>;
29
24
  /**
30
25
  * Insert a single record with a unique id.
31
26
  * @param id The unique id.
32
27
  * @param object Object containing the column names with their values to be stored in the table.
33
28
  * @returns The full persisted record.
34
29
  */
35
- abstract insert(id: string, object: Selectable<T>): Promise<T>;
30
+ abstract insert(id: string, object: Data): Promise<Record>;
36
31
  /**
37
32
  * Partially update a single record given its unique id.
38
33
  * @param id The unique id.
39
34
  * @param object The column names and their values that have to be updatd.
40
35
  * @returns The full persisted record.
41
36
  */
42
- abstract update(id: string, object: Partial<Selectable<T>>): Promise<T>;
37
+ abstract update(id: string, object: Partial<Data>): Promise<Record>;
43
38
  /**
44
39
  * Updates or inserts a single record. If a record exists with the given id,
45
40
  * it will be update, otherwise a new record will be created.
@@ -47,36 +42,36 @@ export declare abstract class Repository<T extends XataRecord> extends Query<T>
47
42
  * @param object The column names and the values to be persisted.
48
43
  * @returns The full persisted record.
49
44
  */
50
- abstract updateOrInsert(id: string, object: Selectable<T>): Promise<T>;
45
+ abstract updateOrInsert(id: string, object: Data): Promise<Record>;
51
46
  /**
52
47
  * Deletes a record given its unique id.
53
48
  * @param id The unique id.
54
49
  * @throws If the record could not be found or there was an error while performing the deletion.
55
50
  */
56
51
  abstract delete(id: string): void;
57
- abstract query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options: Options): Promise<Page<T, typeof options extends {
58
- columns: SelectableColumn<T>[];
59
- } ? Select<T, typeof options['columns'][number]> : R>>;
52
+ abstract query<Result extends XataRecord, Options extends QueryOptions<Record>>(query: Query<Record, Result>, options: Options): Promise<Page<Record, typeof options extends {
53
+ columns: SelectableColumn<Data>[];
54
+ } ? Select<Data, typeof options['columns'][number]> : Result>>;
60
55
  }
61
- export declare class RestRepository<T extends XataRecord> extends Repository<T> {
56
+ export declare class RestRepository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Repository<Data, Record> {
62
57
  #private;
63
58
  constructor(client: BaseClient<any>, table: string);
64
- create(object: Selectable<T>): Promise<T>;
65
- createMany(objects: T[]): Promise<T[]>;
66
- read(recordId: string): Promise<T | null>;
67
- update(recordId: string, object: Partial<Selectable<T>>): Promise<T>;
68
- insert(recordId: string, object: Selectable<T>): Promise<T>;
69
- updateOrInsert(recordId: string, object: Selectable<T>): Promise<T>;
59
+ create(object: Data): Promise<Record>;
60
+ createMany(objects: Data[]): Promise<Record[]>;
61
+ read(recordId: string): Promise<Record | null>;
62
+ update(recordId: string, object: Partial<Data>): Promise<Record>;
63
+ insert(recordId: string, object: Data): Promise<Record>;
64
+ updateOrInsert(recordId: string, object: Data): Promise<Record>;
70
65
  delete(recordId: string): Promise<void>;
71
- query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options?: Options): Promise<Page<T, typeof options extends {
72
- columns: SelectableColumn<T>[];
73
- } ? Select<T, typeof options['columns'][number]> : R>>;
66
+ query<Result extends XataRecord, Options extends QueryOptions<Record>>(query: Query<Record, Result>, options?: Options): Promise<Page<Record, typeof options extends {
67
+ columns: SelectableColumn<Data>[];
68
+ } ? Select<Data, typeof options['columns'][number]> : Result>>;
74
69
  }
75
70
  interface RepositoryFactory {
76
- createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
71
+ createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data>;
77
72
  }
78
73
  export declare class RestRespositoryFactory implements RepositoryFactory {
79
- createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
74
+ createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data>;
80
75
  }
81
76
  declare type BranchStrategyValue = string | undefined | null;
82
77
  declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
@@ -98,7 +93,7 @@ export declare type XataClientOptions = {
98
93
  apiKey: string;
99
94
  repositoryFactory?: RepositoryFactory;
100
95
  };
101
- export declare class BaseClient<D extends Record<string, Repository<any>>> {
96
+ export declare class BaseClient<D extends Record<string, Repository<any>> = Record<string, Repository<any>>> {
102
97
  #private;
103
98
  options: XataClientOptions;
104
99
  db: D;
@@ -41,6 +41,7 @@ class Repository extends query_1.Query {
41
41
  exports.Repository = Repository;
42
42
  class RestRepository extends Repository {
43
43
  constructor(client, table) {
44
+ var _a;
44
45
  super(null, table, {});
45
46
  _RestRepository_instances.add(this);
46
47
  _RestRepository_client.set(this, void 0);
@@ -49,8 +50,10 @@ class RestRepository extends Repository {
49
50
  __classPrivateFieldSet(this, _RestRepository_client, client, "f");
50
51
  __classPrivateFieldSet(this, _RestRepository_table, table, "f");
51
52
  // TODO: Remove when integrating with API client
52
- const fetchImpl = typeof fetch !== 'undefined' ? fetch : __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch;
53
+ const globalFetch = typeof fetch !== 'undefined' ? fetch : undefined;
54
+ const fetchImpl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch) !== null && _a !== void 0 ? _a : globalFetch;
53
55
  if (!fetchImpl) {
56
+ /** @todo add a link after docs exist */
54
57
  throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`);
55
58
  }
56
59
  __classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f");
@@ -76,10 +79,9 @@ class RestRepository extends Repository {
76
79
  const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this);
77
80
  const records = objects.map((object) => transformObjectLinks(object));
78
81
  const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps));
79
- // TODO: Use filer.$any() to get all the records
80
- const finalObjects = yield Promise.all(response.recordIDs.map((id) => this.read(id)));
81
- if (finalObjects.some((object) => !object)) {
82
- throw new Error('The server failed to save the record');
82
+ const finalObjects = yield this.any(...response.recordIDs.map((id) => this.filter('id', id))).getAll();
83
+ if (finalObjects.length !== objects.length) {
84
+ throw new Error('The server failed to save some records');
83
85
  }
84
86
  return finalObjects;
85
87
  });
@@ -186,6 +188,14 @@ class BaseClient {
186
188
  }
187
189
  this.options = options;
188
190
  __classPrivateFieldSet(this, _BaseClient_links, links, "f");
191
+ const factory = options.repositoryFactory || new RestRespositoryFactory();
192
+ this.db = new Proxy({}, {
193
+ get: (_target, prop) => {
194
+ if (typeof prop !== 'string')
195
+ throw new Error('Invalid table name');
196
+ return factory.createRepository(this, prop);
197
+ }
198
+ });
189
199
  }
190
200
  initObject(table, object) {
191
201
  const o = {};
@@ -1,11 +1,10 @@
1
- import { XataRecord } from '..';
2
1
  import { StringKeys, UnionToIntersection, Values } from '../util/types';
3
2
  import { Query } from './query';
3
+ import { BaseData, Identifiable, XataRecord } from './record';
4
4
  declare type Queries<T> = {
5
- [key in keyof T as T[key] extends Query<any> ? key : never]: T[key];
5
+ [key in keyof T as T[key] extends Query<any, any> ? key : never]: T[key];
6
6
  };
7
- declare type InternalProperties = keyof XataRecord;
8
- export declare type Selectable<T extends XataRecord> = Omit<T, InternalProperties>;
7
+ export declare type Selectable<T extends BaseData> = T & Partial<Identifiable>;
9
8
  export declare type SelectableColumn<O> = '*' | (O extends Array<unknown> ? never : O extends Record<string, any> ? '*' | Values<{
10
9
  [K in StringKeys<O>]: O[K] extends Record<string, any> ? `${K}.${SelectableColumn<O[K]>}` : K;
11
10
  }> : '');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xata.io/client",
3
- "version": "0.3.0",
3
+ "version": "0.5.1",
4
4
  "description": "Xata.io SDK for TypeScript and JavaScript",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -20,5 +20,5 @@
20
20
  "url": "https://github.com/xataio/client-ts/issues"
21
21
  },
22
22
  "homepage": "https://github.com/xataio/client-ts/blob/main/client/README.md",
23
- "gitHead": "68cefbad5825d10c1f15efd39766280d3b863a87"
23
+ "gitHead": "09892c40a01ece59c802844310aac17aba7a281c"
24
24
  }