@xata.io/client 0.7.1 → 0.8.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/.eslintrc.cjs CHANGED
@@ -3,7 +3,7 @@ module.exports = {
3
3
  parserOptions: {
4
4
  ecmaVersion: 2020,
5
5
  sourceType: 'module',
6
- project: 'client/tsconfig.json'
6
+ project: 'packages/client/tsconfig.json'
7
7
  },
8
8
  rules: {
9
9
  '@typescript-eslint/no-explicit-any': 'off',
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # @xata.io/client
2
2
 
3
+ ## 0.8.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 5110261: Fix execution from the browser
8
+ - aa3d7e7: Allow sending sort as in the API
9
+ - 0047193: Add new plugin system for the SDK
10
+ - 43856a5: Add discriminated union search
11
+
12
+ ## 0.8.0
13
+
14
+ ### Patch Changes
15
+
16
+ - bde908e: Refactor client builder
17
+ - ea3eef8: Make records returned by the API readonly
18
+
19
+ ## 0.7.2
20
+
21
+ ### Patch Changes
22
+
23
+ - 4803b6f: Memoize ApiClient namespaces
24
+ - 1f268d7: Add search in XataClient
25
+ - d58c3d9: Hide private helper utilities
26
+ - f3b731b: Expose branch resolution API
27
+
3
28
  ## 0.7.1
4
29
 
5
30
  ### Patch Changes
@@ -10,10 +10,10 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  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");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _XataApiClient_extraProps;
13
+ var _XataApiClient_extraProps, _XataApiClient_namespaces;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.XataApiClient = void 0;
16
- const config_1 = require("../schema/config");
16
+ const config_1 = require("../util/config");
17
17
  const fetch_1 = require("../util/fetch");
18
18
  const components_1 = require("./components");
19
19
  const providers_1 = require("./providers");
@@ -21,6 +21,7 @@ class XataApiClient {
21
21
  constructor(options) {
22
22
  var _a, _b;
23
23
  _XataApiClient_extraProps.set(this, void 0);
24
+ _XataApiClient_namespaces.set(this, {});
24
25
  const provider = (_a = options.host) !== null && _a !== void 0 ? _a : 'production';
25
26
  const apiKey = (_b = options === null || options === void 0 ? void 0 : options.apiKey) !== null && _b !== void 0 ? _b : (0, config_1.getAPIKey)();
26
27
  if (!apiKey) {
@@ -34,26 +35,38 @@ class XataApiClient {
34
35
  }, "f");
35
36
  }
36
37
  get user() {
37
- return new UserApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
38
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").user)
39
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").user = new UserApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
40
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").user;
38
41
  }
39
42
  get workspaces() {
40
- return new WorkspaceApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
43
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").workspaces)
44
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").workspaces = new WorkspaceApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
45
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").workspaces;
41
46
  }
42
47
  get databases() {
43
- return new DatabaseApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
48
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").databases)
49
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").databases = new DatabaseApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
50
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").databases;
44
51
  }
45
52
  get branches() {
46
- return new BranchApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
53
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").branches)
54
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").branches = new BranchApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
55
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").branches;
47
56
  }
48
57
  get tables() {
49
- return new TableApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
58
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").tables)
59
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").tables = new TableApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
60
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").tables;
50
61
  }
51
62
  get records() {
52
- return new RecordsApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
63
+ if (!__classPrivateFieldGet(this, _XataApiClient_namespaces, "f").records)
64
+ __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").records = new RecordsApi(__classPrivateFieldGet(this, _XataApiClient_extraProps, "f"));
65
+ return __classPrivateFieldGet(this, _XataApiClient_namespaces, "f").records;
53
66
  }
54
67
  }
55
68
  exports.XataApiClient = XataApiClient;
56
- _XataApiClient_extraProps = new WeakMap();
69
+ _XataApiClient_extraProps = new WeakMap(), _XataApiClient_namespaces = new WeakMap();
57
70
  class UserApi {
58
71
  constructor(extraProps) {
59
72
  this.extraProps = extraProps;
@@ -1,7 +1,13 @@
1
+ import { XataPlugin, XataPluginOptions } from '../plugins';
2
+ import { XataApiClient } from './client';
1
3
  import { operationsByTag } from './components';
2
4
  import type * as Responses from './responses';
3
5
  import type * as Schemas from './schemas';
4
6
  export * from './client';
5
7
  export * from './components';
8
+ export type { FetcherExtraProps, FetchImpl } from './fetcher';
6
9
  export { operationsByTag as Operations };
7
10
  export type { Responses, Schemas };
11
+ export declare class XataApiPlugin implements XataPlugin {
12
+ build(options: XataPluginOptions): Promise<XataApiClient>;
13
+ }
package/dist/api/index.js CHANGED
@@ -13,9 +13,28 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
13
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
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
+ return new (P || (P = Promise))(function (resolve, reject) {
19
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23
+ });
24
+ };
16
25
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.Operations = void 0;
26
+ exports.XataApiPlugin = exports.Operations = void 0;
27
+ const client_1 = require("./client");
18
28
  const components_1 = require("./components");
19
29
  Object.defineProperty(exports, "Operations", { enumerable: true, get: function () { return components_1.operationsByTag; } });
20
30
  __exportStar(require("./client"), exports);
21
31
  __exportStar(require("./components"), exports);
32
+ class XataApiPlugin {
33
+ build(options) {
34
+ return __awaiter(this, void 0, void 0, function* () {
35
+ const { fetchImpl, apiKey } = yield options.getFetchProps();
36
+ return new client_1.XataApiClient({ fetch: fetchImpl, apiKey });
37
+ });
38
+ }
39
+ }
40
+ exports.XataApiPlugin = XataApiPlugin;
@@ -0,0 +1,27 @@
1
+ import { FetchImpl } from './api/fetcher';
2
+ import { XataPlugin } from './plugins';
3
+ import { SchemaPlugin } from './schema';
4
+ import { BaseData } from './schema/record';
5
+ import { LinkDictionary } from './schema/repository';
6
+ import { SearchPlugin } from './search';
7
+ import { BranchStrategyOption } from './util/branches';
8
+ import { StringKeys } from './util/types';
9
+ export declare type BaseClientOptions = {
10
+ fetch?: FetchImpl;
11
+ apiKey?: string;
12
+ databaseURL?: string;
13
+ branch?: BranchStrategyOption;
14
+ };
15
+ export declare const buildClient: <Plugins extends Record<string, XataPlugin> = {}>(plugins?: Plugins | undefined) => ClientConstructor<Plugins>;
16
+ export interface ClientConstructor<Plugins extends Record<string, XataPlugin>> {
17
+ new <Schemas extends Record<string, BaseData>>(options?: Partial<BaseClientOptions>, links?: LinkDictionary): Omit<{
18
+ db: Awaited<ReturnType<SchemaPlugin<Schemas>['build']>>;
19
+ search: Awaited<ReturnType<SearchPlugin<Schemas>['build']>>;
20
+ }, keyof Plugins> & {
21
+ [Key in StringKeys<NonNullable<Plugins>>]: Awaited<ReturnType<NonNullable<Plugins>[Key]['build']>>;
22
+ };
23
+ }
24
+ declare const BaseClient_base: ClientConstructor<{}>;
25
+ export declare class BaseClient extends BaseClient_base<Record<string, any>> {
26
+ }
27
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
12
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13
+ 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");
14
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15
+ };
16
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
17
+ if (kind === "m") throw new TypeError("Private method is not writable");
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
19
+ 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");
20
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
21
+ };
22
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
23
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
24
+ var m = o[Symbol.asyncIterator], i;
25
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
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
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.BaseClient = exports.buildClient = void 0;
31
+ const schema_1 = require("./schema");
32
+ const search_1 = require("./search");
33
+ const branches_1 = require("./util/branches");
34
+ const config_1 = require("./util/config");
35
+ const fetch_1 = require("./util/fetch");
36
+ const buildClient = (plugins) => {
37
+ var _instances, _branch, _parseOptions, _getFetchProps, _evaluateBranch, _a;
38
+ return _a = class {
39
+ constructor(options = {}, links) {
40
+ _instances.add(this);
41
+ _branch.set(this, void 0);
42
+ const safeOptions = __classPrivateFieldGet(this, _instances, "m", _parseOptions).call(this, options);
43
+ const namespaces = Object.assign({ db: new schema_1.SchemaPlugin(links), search: new search_1.SearchPlugin() }, plugins);
44
+ for (const [key, namespace] of Object.entries(namespaces)) {
45
+ if (!namespace)
46
+ continue;
47
+ const result = namespace.build({ getFetchProps: () => __classPrivateFieldGet(this, _instances, "m", _getFetchProps).call(this, safeOptions) });
48
+ if (result instanceof Promise) {
49
+ void result.then((namespace) => {
50
+ // @ts-ignore
51
+ this[key] = namespace;
52
+ });
53
+ }
54
+ else {
55
+ // @ts-ignore
56
+ this[key] = result;
57
+ }
58
+ }
59
+ }
60
+ },
61
+ _branch = new WeakMap(),
62
+ _instances = new WeakSet(),
63
+ _parseOptions = function _parseOptions(options) {
64
+ const fetch = (0, fetch_1.getFetchImplementation)(options === null || options === void 0 ? void 0 : options.fetch);
65
+ const databaseURL = (options === null || options === void 0 ? void 0 : options.databaseURL) || (0, config_1.getDatabaseURL)();
66
+ const apiKey = (options === null || options === void 0 ? void 0 : options.apiKey) || (0, config_1.getAPIKey)();
67
+ const branch = () => __awaiter(this, void 0, void 0, function* () {
68
+ return (options === null || options === void 0 ? void 0 : options.branch)
69
+ ? yield __classPrivateFieldGet(this, _instances, "m", _evaluateBranch).call(this, options.branch)
70
+ : yield (0, config_1.getCurrentBranchName)({ apiKey, databaseURL, fetchImpl: options === null || options === void 0 ? void 0 : options.fetch });
71
+ });
72
+ if (!databaseURL || !apiKey) {
73
+ throw new Error('Options databaseURL and apiKey are required');
74
+ }
75
+ return { fetch, databaseURL, apiKey, branch };
76
+ },
77
+ _getFetchProps = function _getFetchProps({ fetch, apiKey, databaseURL, branch }) {
78
+ return __awaiter(this, void 0, void 0, function* () {
79
+ const branchValue = yield __classPrivateFieldGet(this, _instances, "m", _evaluateBranch).call(this, branch);
80
+ if (!branchValue)
81
+ throw new Error('Unable to resolve branch value');
82
+ return {
83
+ fetchImpl: fetch,
84
+ apiKey,
85
+ apiUrl: '',
86
+ // Instead of using workspace and dbBranch, we inject a probably CNAME'd URL
87
+ workspacesApiUrl: (path, params) => {
88
+ var _a;
89
+ const hasBranch = (_a = params.dbBranchName) !== null && _a !== void 0 ? _a : params.branch;
90
+ const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branchValue}` : '');
91
+ return databaseURL + newPath;
92
+ }
93
+ };
94
+ });
95
+ },
96
+ _evaluateBranch = function _evaluateBranch(param) {
97
+ var e_1, _a;
98
+ return __awaiter(this, void 0, void 0, function* () {
99
+ if (__classPrivateFieldGet(this, _branch, "f"))
100
+ return __classPrivateFieldGet(this, _branch, "f");
101
+ if (!param)
102
+ return undefined;
103
+ const strategies = Array.isArray(param) ? [...param] : [param];
104
+ const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () {
105
+ return (0, branches_1.isBranchStrategyBuilder)(strategy) ? yield strategy() : strategy;
106
+ });
107
+ try {
108
+ for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) {
109
+ const strategy = strategies_1_1.value;
110
+ const branch = yield evaluateBranch(strategy);
111
+ if (branch) {
112
+ __classPrivateFieldSet(this, _branch, branch, "f");
113
+ return branch;
114
+ }
115
+ }
116
+ }
117
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
118
+ finally {
119
+ try {
120
+ if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1);
121
+ }
122
+ finally { if (e_1) throw e_1.error; }
123
+ }
124
+ });
125
+ },
126
+ _a;
127
+ };
128
+ exports.buildClient = buildClient;
129
+ class BaseClient extends (0, exports.buildClient)() {
130
+ }
131
+ exports.BaseClient = BaseClient;
package/dist/index.d.ts CHANGED
@@ -3,4 +3,8 @@ export declare class XataError extends Error {
3
3
  constructor(message: string, status: number);
4
4
  }
5
5
  export * from './api';
6
+ export * from './plugins';
7
+ export * from './client';
6
8
  export * from './schema';
9
+ export * from './search';
10
+ export * from './util/config';
package/dist/index.js CHANGED
@@ -23,4 +23,8 @@ class XataError extends Error {
23
23
  }
24
24
  exports.XataError = XataError;
25
25
  __exportStar(require("./api"), exports);
26
+ __exportStar(require("./plugins"), exports);
27
+ __exportStar(require("./client"), exports);
26
28
  __exportStar(require("./schema"), exports);
29
+ __exportStar(require("./search"), exports);
30
+ __exportStar(require("./util/config"), exports);
@@ -0,0 +1,7 @@
1
+ import { FetcherExtraProps } from './api/fetcher';
2
+ export declare abstract class XataPlugin {
3
+ abstract build(options: XataPluginOptions): unknown | Promise<unknown>;
4
+ }
5
+ export declare type XataPluginOptions = {
6
+ getFetchProps: () => Promise<FetcherExtraProps>;
7
+ };
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.XataPlugin = void 0;
4
+ class XataPlugin {
5
+ }
6
+ exports.XataPlugin = XataPlugin;
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ /* eslint-disable @typescript-eslint/no-unused-vars */
4
+ const vitest_1 = require("vitest");
3
5
  // Single column with implicit is
4
6
  const singleColumnWithImplicitIs = { name: 'r2' };
5
7
  // Single column with explicit is
@@ -170,6 +172,6 @@ const filterWithInvalidNestedObjectPropertyType = { settings: { plan: 42 } };
170
172
  // Filter with invalid property $is type
171
173
  // @ts-expect-error
172
174
  const filterWithInvalidOperator = { name: { $is: 42 } };
173
- test('fake test', () => {
175
+ (0, vitest_1.test)('fake test', () => {
174
176
  // This is a fake test to make sure that the type definitions in this file are working
175
177
  });
@@ -1,7 +1,23 @@
1
+ import { XataPlugin, XataPluginOptions } from '../plugins';
2
+ import { BaseData } from './record';
3
+ import { LinkDictionary, Repository } from './repository';
1
4
  export * from './operators';
2
5
  export * from './pagination';
3
6
  export { Query } from './query';
4
7
  export { isIdentifiable, isXataRecord } from './record';
5
- export type { Identifiable, XataRecord } from './record';
6
- export { BaseClient, Repository, RestRepository, RestRespositoryFactory } from './repository';
7
- export type { XataClientOptions } from './repository';
8
+ export type { BaseData, EditableData, Identifiable, XataRecord } from './record';
9
+ export { Repository, RestRepository } from './repository';
10
+ export type { LinkDictionary } from './repository';
11
+ export * from './selection';
12
+ export declare type SchemaDefinition = {
13
+ table: string;
14
+ links?: LinkDictionary;
15
+ };
16
+ export declare type SchemaPluginResult<Schemas extends Record<string, BaseData>> = {
17
+ [Key in keyof Schemas]: Repository<Schemas[Key]>;
18
+ };
19
+ export declare class SchemaPlugin<Schemas extends Record<string, BaseData>> extends XataPlugin {
20
+ private links?;
21
+ constructor(links?: LinkDictionary | undefined);
22
+ build(options: XataPluginOptions): SchemaPluginResult<Schemas>;
23
+ }
@@ -14,7 +14,10 @@ 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.RestRespositoryFactory = exports.RestRepository = exports.Repository = exports.BaseClient = exports.isXataRecord = exports.isIdentifiable = exports.Query = void 0;
17
+ exports.SchemaPlugin = exports.RestRepository = exports.Repository = exports.isXataRecord = exports.isIdentifiable = exports.Query = void 0;
18
+ const plugins_1 = require("../plugins");
19
+ const lang_1 = require("../util/lang");
20
+ const repository_1 = require("./repository");
18
21
  __exportStar(require("./operators"), exports);
19
22
  __exportStar(require("./pagination"), exports);
20
23
  var query_1 = require("./query");
@@ -22,8 +25,26 @@ Object.defineProperty(exports, "Query", { enumerable: true, get: function () { r
22
25
  var record_1 = require("./record");
23
26
  Object.defineProperty(exports, "isIdentifiable", { enumerable: true, get: function () { return record_1.isIdentifiable; } });
24
27
  Object.defineProperty(exports, "isXataRecord", { enumerable: true, get: function () { return record_1.isXataRecord; } });
25
- var repository_1 = require("./repository");
26
- Object.defineProperty(exports, "BaseClient", { enumerable: true, get: function () { return repository_1.BaseClient; } });
27
- Object.defineProperty(exports, "Repository", { enumerable: true, get: function () { return repository_1.Repository; } });
28
- Object.defineProperty(exports, "RestRepository", { enumerable: true, get: function () { return repository_1.RestRepository; } });
29
- Object.defineProperty(exports, "RestRespositoryFactory", { enumerable: true, get: function () { return repository_1.RestRespositoryFactory; } });
28
+ var repository_2 = require("./repository");
29
+ Object.defineProperty(exports, "Repository", { enumerable: true, get: function () { return repository_2.Repository; } });
30
+ Object.defineProperty(exports, "RestRepository", { enumerable: true, get: function () { return repository_2.RestRepository; } });
31
+ __exportStar(require("./selection"), exports);
32
+ class SchemaPlugin extends plugins_1.XataPlugin {
33
+ constructor(links) {
34
+ super();
35
+ this.links = links;
36
+ }
37
+ build(options) {
38
+ const { getFetchProps } = options;
39
+ const links = this.links;
40
+ const db = new Proxy({}, {
41
+ get: (_target, table) => {
42
+ if (!(0, lang_1.isString)(table))
43
+ throw new Error('Invalid table name');
44
+ return new repository_1.RestRepository({ db, getFetchProps, table, links });
45
+ }
46
+ });
47
+ return db;
48
+ }
49
+ }
50
+ exports.SchemaPlugin = SchemaPlugin;
@@ -27,14 +27,14 @@ export interface XataRecord extends Identifiable {
27
27
  /**
28
28
  * Retrieves a refreshed copy of the current record from the database.
29
29
  */
30
- read(): Promise<SelectedPick<this, ['*']> | null>;
30
+ read(): Promise<Readonly<SelectedPick<this, ['*']>> | null>;
31
31
  /**
32
32
  * Performs a partial update of the current record. On success a new object is
33
33
  * returned and the current object is not mutated.
34
34
  * @param data The columns and their values that have to be updated.
35
35
  * @returns A new record containing the latest values for all the columns of the current record.
36
36
  */
37
- update(data: Partial<EditableData<Omit<this, keyof XataRecord>>>): Promise<SelectedPick<this, ['*']>>;
37
+ update(partialUpdate: Partial<EditableData<Omit<this, keyof XataRecord>>>): Promise<Readonly<SelectedPick<this, ['*']>>>;
38
38
  /**
39
39
  * Performs a deletion of the current record in the database.
40
40
  *
@@ -46,14 +46,14 @@ export declare type Link<Record extends XataRecord> = Omit<XataRecord, 'read' |
46
46
  /**
47
47
  * Retrieves a refreshed copy of the current record from the database.
48
48
  */
49
- read(): Promise<SelectedPick<Record, ['*']> | null>;
49
+ read(): Promise<Readonly<SelectedPick<Record, ['*']>> | null>;
50
50
  /**
51
51
  * Performs a partial update of the current record. On success a new object is
52
52
  * returned and the current object is not mutated.
53
53
  * @param data The columns and their values that have to be updated.
54
54
  * @returns A new record containing the latest values for all the columns of the current record.
55
55
  */
56
- update(data: Partial<EditableData<Omit<Record, keyof XataRecord>>>): Promise<SelectedPick<Record, ['*']>>;
56
+ update(partialUpdate: Partial<EditableData<Omit<Record, keyof XataRecord>>>): Promise<Readonly<SelectedPick<Record, ['*']>>>;
57
57
  };
58
58
  export declare function isIdentifiable(x: any): x is Identifiable & Record<string, unknown>;
59
59
  export declare function isXataRecord(x: any): x is XataRecord & Record<string, unknown>;
@@ -1,59 +1,62 @@
1
- import { FetchImpl } from '../api/fetcher';
1
+ import { SchemaPluginResult } from '.';
2
+ import { FetcherExtraProps } from '../api/fetcher';
3
+ import { Dictionary } from '../util/types';
2
4
  import { Page } from './pagination';
3
5
  import { Query } from './query';
4
6
  import { BaseData, EditableData, Identifiable, XataRecord } from './record';
5
7
  import { SelectedPick } from './selection';
6
- export declare type Links = Record<string, Array<string[]>>;
8
+ declare type TableLink = string[];
9
+ export declare type LinkDictionary = Dictionary<TableLink[]>;
7
10
  /**
8
11
  * Common interface for performing operations on a table.
9
12
  */
10
- export declare abstract class Repository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record, SelectedPick<Record, ['*']>> {
11
- abstract create(object: EditableData<Data> & Partial<Identifiable>): Promise<SelectedPick<Record, ['*']>>;
13
+ export declare abstract class Repository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record, Readonly<SelectedPick<Record, ['*']>>> {
14
+ abstract create(object: EditableData<Data> & Partial<Identifiable>): Promise<Readonly<SelectedPick<Record, ['*']>>>;
12
15
  /**
13
16
  * Creates a single record in the table with a unique id.
14
17
  * @param id The unique id.
15
18
  * @param object Object containing the column names with their values to be stored in the table.
16
19
  * @returns The full persisted record.
17
20
  */
18
- abstract create(id: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
21
+ abstract create(id: string, object: EditableData<Data>): Promise<Readonly<SelectedPick<Record, ['*']>>>;
19
22
  /**
20
23
  * Creates multiple records in the table.
21
24
  * @param objects Array of objects with the column names and the values to be stored in the table.
22
25
  * @returns Array of the persisted records.
23
26
  */
24
- abstract create(objects: Array<EditableData<Data> & Partial<Identifiable>>): Promise<SelectedPick<Record, ['*']>[]>;
27
+ abstract create(objects: Array<EditableData<Data> & Partial<Identifiable>>): Promise<Readonly<SelectedPick<Record, ['*']>>[]>;
25
28
  /**
26
29
  * Queries a single record from the table given its unique id.
27
30
  * @param id The unique id.
28
31
  * @returns The persisted record for the given id or null if the record could not be found.
29
32
  */
30
- abstract read(id: string): Promise<SelectedPick<Record, ['*']> | null>;
33
+ abstract read(id: string): Promise<Readonly<SelectedPick<Record, ['*']> | null>>;
31
34
  /**
32
35
  * Partially update a single record.
33
36
  * @param object An object with its id and the columns to be updated.
34
37
  * @returns The full persisted record.
35
38
  */
36
- abstract update(object: Partial<EditableData<Data>> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
39
+ abstract update(object: Partial<EditableData<Data>> & Identifiable): Promise<Readonly<SelectedPick<Record, ['*']>>>;
37
40
  /**
38
41
  * Partially update a single record given its unique id.
39
42
  * @param id The unique id.
40
43
  * @param object The column names and their values that have to be updated.
41
44
  * @returns The full persisted record.
42
45
  */
43
- abstract update(id: string, object: Partial<EditableData<Data>>): Promise<SelectedPick<Record, ['*']>>;
46
+ abstract update(id: string, object: Partial<EditableData<Data>>): Promise<Readonly<SelectedPick<Record, ['*']>>>;
44
47
  /**
45
48
  * Partially updates multiple records.
46
49
  * @param objects An array of objects with their ids and columns to be updated.
47
50
  * @returns Array of the persisted records.
48
51
  */
49
- abstract update(objects: Array<Partial<EditableData<Data>> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
52
+ abstract update(objects: Array<Partial<EditableData<Data>> & Identifiable>): Promise<Readonly<SelectedPick<Record, ['*']>>[]>;
50
53
  /**
51
54
  * Creates or updates a single record. If a record exists with the given id,
52
55
  * it will be update, otherwise a new record will be created.
53
56
  * @param object Object containing the column names with their values to be persisted in the table.
54
57
  * @returns The full persisted record.
55
58
  */
56
- abstract createOrUpdate(object: EditableData<Data> & Identifiable): Promise<SelectedPick<Record, ['*']>>;
59
+ abstract createOrUpdate(object: EditableData<Data> & Identifiable): Promise<Readonly<SelectedPick<Record, ['*']>>>;
57
60
  /**
58
61
  * Creates or updates a single record. If a record exists with the given id,
59
62
  * it will be update, otherwise a new record will be created.
@@ -61,14 +64,14 @@ export declare abstract class Repository<Data extends BaseData, Record extends X
61
64
  * @param object The column names and the values to be persisted.
62
65
  * @returns The full persisted record.
63
66
  */
64
- abstract createOrUpdate(id: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
67
+ abstract createOrUpdate(id: string, object: EditableData<Data>): Promise<Readonly<SelectedPick<Record, ['*']>>>;
65
68
  /**
66
69
  * Creates or updates a single record. If a record exists with the given id,
67
70
  * it will be update, otherwise a new record will be created.
68
71
  * @param objects Array of objects with the column names and the values to be stored in the table.
69
72
  * @returns Array of the persisted records.
70
73
  */
71
- abstract createOrUpdate(objects: Array<EditableData<Data> & Identifiable>): Promise<SelectedPick<Record, ['*']>[]>;
74
+ abstract createOrUpdate(objects: Array<EditableData<Data> & Identifiable>): Promise<Readonly<SelectedPick<Record, ['*']>>[]>;
72
75
  /**
73
76
  * Deletes a record given its unique id.
74
77
  * @param id The unique id.
@@ -93,11 +96,26 @@ export declare abstract class Repository<Data extends BaseData, Record extends X
93
96
  * @throws If the record could not be found or there was an error while performing the deletion.
94
97
  */
95
98
  abstract delete(ids: Identifiable[]): Promise<void>;
99
+ /**
100
+ * Search for records in the table.
101
+ * @param query The query to search for.
102
+ * @param options The options to search with (like: fuzziness)
103
+ * @returns The found records.
104
+ */
105
+ abstract search(query: string, options?: {
106
+ fuzziness?: number;
107
+ }): Promise<SelectedPick<Record, ['*']>[]>;
96
108
  abstract query<Result extends XataRecord>(query: Query<Record, Result>): Promise<Page<Record, Result>>;
97
109
  }
98
- export declare class RestRepository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record, SelectedPick<Record, ['*']>> {
110
+ export declare class RestRepository<Data extends BaseData, Record extends XataRecord = Data & XataRecord> extends Query<Record, SelectedPick<Record, ['*']>> implements Repository<Data, Record> {
99
111
  #private;
100
- constructor(client: BaseClient<any>, table: string);
112
+ db: SchemaPluginResult<any>;
113
+ constructor(options: {
114
+ table: string;
115
+ links?: LinkDictionary;
116
+ getFetchProps: () => Promise<FetcherExtraProps>;
117
+ db: SchemaPluginResult<any>;
118
+ });
101
119
  create(object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
102
120
  create(recordId: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
103
121
  create(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
@@ -109,40 +127,9 @@ export declare class RestRepository<Data extends BaseData, Record extends XataRe
109
127
  createOrUpdate(recordId: string, object: EditableData<Data>): Promise<SelectedPick<Record, ['*']>>;
110
128
  createOrUpdate(objects: EditableData<Data>[]): Promise<SelectedPick<Record, ['*']>[]>;
111
129
  delete(recordId: string | Identifiable | Array<string | Identifiable>): Promise<void>;
130
+ search(query: string, options?: {
131
+ fuzziness?: number;
132
+ }): Promise<SelectedPick<Record, ['*']>[]>;
112
133
  query<Result extends XataRecord>(query: Query<Record, Result>): Promise<Page<Record, Result>>;
113
134
  }
114
- interface RepositoryFactory {
115
- createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data & XataRecord>;
116
- }
117
- export declare class RestRespositoryFactory implements RepositoryFactory {
118
- createRepository<Data extends BaseData>(client: BaseClient<any>, table: string): Repository<Data & XataRecord>;
119
- }
120
- declare type BranchStrategyValue = string | undefined | null;
121
- declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>;
122
- declare type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder;
123
- declare type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>;
124
- export declare type XataClientOptions = {
125
- /**
126
- * Fetch implementation. This option is only required if the runtime does not include a fetch implementation
127
- * available in the global scope. If you are running your code on Deno or Cloudflare workers for example,
128
- * you won't need to provide a specific fetch implementation. But for most versions of Node.js you'll need
129
- * to provide one. Such as cross-fetch, node-fetch or isomorphic-fetch.
130
- */
131
- fetch?: FetchImpl;
132
- databaseURL?: string;
133
- branch?: BranchStrategyOption;
134
- /**
135
- * API key to be used. You can create one in your account settings at https://app.xata.io/settings.
136
- */
137
- apiKey?: string;
138
- repositoryFactory?: RepositoryFactory;
139
- };
140
- export declare class BaseClient<D extends Record<string, Repository<any>> = Record<string, Repository<any>>> {
141
- #private;
142
- options: XataClientOptions;
143
- db: D;
144
- constructor(options?: XataClientOptions, links?: Links);
145
- initObject<T>(table: string, object: object): T;
146
- getBranch(): Promise<string>;
147
- }
148
135
  export {};