@xata.io/client
Advanced tools
Comparing version 0.0.0-alpha.b8b17fa to 0.0.0-alpha.b9ad17d
@@ -7,3 +7,3 @@ import type * as Types from './components'; | ||
export interface XataApiClientOptions { | ||
fetchImpl: FetchImpl; | ||
fetch: FetchImpl; | ||
apiKey: string; | ||
@@ -58,3 +58,3 @@ host?: HostProvider; | ||
getBranchDetails(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName): Promise<Schemas.DBBranch>; | ||
createBranch(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, from?: string, options?: Types.CreateBranchRequestBody): Promise<undefined>; | ||
createBranch(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, from?: string, options?: Types.CreateBranchRequestBody): Promise<void>; | ||
deleteBranch(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName): Promise<void>; | ||
@@ -61,0 +61,0 @@ updateBranchMetadata(workspace: Schemas.WorkspaceID, database: Schemas.DBName, branch: Schemas.BranchName, metadata?: Schemas.BranchMetadata): Promise<void>; |
@@ -22,3 +22,3 @@ "use strict"; | ||
_XataApiClient_extraProps.set(this, void 0); | ||
const fetchImpl = typeof fetch !== 'undefined' ? fetch : options.fetchImpl; | ||
const fetchImpl = typeof fetch !== 'undefined' ? fetch : options.fetch; | ||
if (!fetchImpl) { | ||
@@ -25,0 +25,0 @@ /** @todo add a link after docs exist */ |
@@ -23,14 +23,11 @@ "use strict"; | ||
const url = typeof workspacesApiUrl === 'string' ? `${workspacesApiUrl}${path}` : workspacesApiUrl(path, pathParams); | ||
// Node.js on localhost won't resolve localhost subdomains unless mapped in /etc/hosts | ||
// So, instead, we use localhost without subdomains, but will add a Host header | ||
if (typeof window === 'undefined' && url.includes('localhost:')) { | ||
return url.replace('{workspaceId}.', ''); | ||
} | ||
return url.replace('{workspaceId}', pathParams.workspace); | ||
} | ||
function hostHeaderForWorkspace(url) { | ||
// The host header is needed by Node.js on localhost. | ||
// It is ignored by fetch() in the frontend | ||
function hostHeader(url) { | ||
var _a; | ||
const pattern = /.*:\/\/(?<host>[^/]+).*/; | ||
const { groups } = (_a = pattern.exec(url)) !== null && _a !== void 0 ? _a : {}; | ||
return groups === null || groups === void 0 ? void 0 : groups.host; | ||
return (groups === null || groups === void 0 ? void 0 : groups.host) ? { Host: groups.host } : {}; | ||
} | ||
@@ -40,7 +37,10 @@ function fetch({ url: path, method, body, headers, pathParams, queryParams, fetchImpl, apiKey, apiUrl, workspacesApiUrl }) { | ||
const baseUrl = buildBaseUrl({ path, workspacesApiUrl, pathParams, apiUrl }); | ||
const url = resolveUrl(baseUrl, queryParams, pathParams); | ||
const fullUrl = resolveUrl(baseUrl, queryParams, pathParams); | ||
// Node.js on localhost won't resolve localhost subdomains unless mapped in /etc/hosts | ||
// So, instead, we use localhost without subdomains, but will add a Host header | ||
const url = fullUrl.includes('localhost') ? fullUrl.replace(/^[^.]+\./, 'http://') : fullUrl; | ||
const response = yield fetchImpl(url, { | ||
method: method.toUpperCase(), | ||
body: body ? JSON.stringify(body) : undefined, | ||
headers: Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), { Authorization: `Bearer ${apiKey}` }), ((pathParams === null || pathParams === void 0 ? void 0 : pathParams.workspace) ? { Host: hostHeaderForWorkspace(url) } : {})) | ||
headers: Object.assign(Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), hostHeader(fullUrl)), { Authorization: `Bearer ${apiKey}` }) | ||
}); | ||
@@ -47,0 +47,0 @@ // No content |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -6,0 +10,0 @@ if (k2 === undefined) k2 = k; |
@@ -1,57 +0,1 @@ | ||
import { FetchImpl } from './api/fetcher'; | ||
import { Page } from './schema/pagination'; | ||
import { Query, QueryOptions } from './schema/query'; | ||
import { Selectable, SelectableColumn, Select } from './schema/selection'; | ||
export interface XataRecord { | ||
id: string; | ||
xata: { | ||
version: number; | ||
}; | ||
read(): Promise<this>; | ||
update(data: Selectable<this>): Promise<this>; | ||
delete(): Promise<void>; | ||
} | ||
export declare abstract class Repository<T extends XataRecord> extends Query<T> { | ||
abstract create(object: Selectable<T>): Promise<T>; | ||
abstract createMany(objects: Selectable<T>[]): Promise<T[]>; | ||
abstract read(id: string): Promise<T | null>; | ||
abstract update(id: string, object: Partial<T>): Promise<T>; | ||
abstract delete(id: string): void; | ||
abstract query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>; | ||
} | ||
export declare class RestRepository<T extends XataRecord> extends Repository<T> { | ||
#private; | ||
constructor(client: BaseClient<any>, table: string); | ||
create(object: T): Promise<T>; | ||
createMany(objects: T[]): Promise<T[]>; | ||
read(recordId: string): Promise<T | null>; | ||
update(recordId: string, object: Partial<T>): Promise<T>; | ||
delete(recordId: string): Promise<void>; | ||
query<R extends XataRecord, Options extends QueryOptions<T>>(query: Query<T, R>, options: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>; | ||
} | ||
interface RepositoryFactory { | ||
createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>; | ||
} | ||
export declare class RestRespositoryFactory implements RepositoryFactory { | ||
createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>; | ||
} | ||
declare type BranchStrategyValue = string | undefined | null; | ||
declare type BranchStrategyBuilder = () => BranchStrategyValue | Promise<BranchStrategyValue>; | ||
declare type BranchStrategy = BranchStrategyValue | BranchStrategyBuilder; | ||
declare type BranchStrategyOption = NonNullable<BranchStrategy | BranchStrategy[]>; | ||
export declare type XataClientOptions = { | ||
fetch?: FetchImpl; | ||
databaseURL?: string; | ||
branch: BranchStrategyOption; | ||
apiKey: string; | ||
repositoryFactory?: RepositoryFactory; | ||
}; | ||
export declare class BaseClient<D extends Record<string, Repository<any>>> { | ||
#private; | ||
options: XataClientOptions; | ||
db: D; | ||
constructor(options: XataClientOptions, links: Links); | ||
initObject<T>(table: string, object: object): T; | ||
getBranch(): Promise<string>; | ||
} | ||
export declare class XataError extends Error { | ||
@@ -61,4 +5,3 @@ readonly status: number; | ||
} | ||
export declare type Links = Record<string, Array<string[]>>; | ||
export * from './api'; | ||
export * from './schema'; |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -12,226 +16,4 @@ if (k2 === undefined) k2 = k; | ||
}; | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { | ||
if (kind === "m") throw new TypeError("Private method is not writable"); | ||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); | ||
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"); | ||
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; | ||
}; | ||
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { | ||
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); | ||
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"); | ||
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); | ||
}; | ||
var __asyncValues = (this && this.__asyncValues) || function (o) { | ||
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); | ||
var m = o[Symbol.asyncIterator], i; | ||
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); | ||
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); }); }; } | ||
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } | ||
}; | ||
var _RestRepository_instances, _RestRepository_client, _RestRepository_fetch, _RestRepository_table, _RestRepository_getFetchProps, _BaseClient_links, _BaseClient_branch; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.XataError = exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0; | ||
const api_1 = require("./api"); | ||
const filters_1 = require("./schema/filters"); | ||
const pagination_1 = require("./schema/pagination"); | ||
const query_1 = require("./schema/query"); | ||
class Repository extends query_1.Query { | ||
} | ||
exports.Repository = Repository; | ||
class RestRepository extends Repository { | ||
constructor(client, table) { | ||
super(null, table, {}); | ||
_RestRepository_instances.add(this); | ||
_RestRepository_client.set(this, void 0); | ||
_RestRepository_fetch.set(this, void 0); | ||
_RestRepository_table.set(this, void 0); | ||
__classPrivateFieldSet(this, _RestRepository_client, client, "f"); | ||
__classPrivateFieldSet(this, _RestRepository_table, table, "f"); | ||
// TODO: Remove when integrating with API client | ||
const fetchImpl = typeof fetch !== 'undefined' ? fetch : __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch; | ||
if (!fetchImpl) { | ||
throw new Error(`The \`fetch\` option passed to the Xata client is resolving to a falsy value and may not be correctly imported.`); | ||
} | ||
__classPrivateFieldSet(this, _RestRepository_fetch, fetchImpl, "f"); | ||
} | ||
create(object) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this); | ||
const record = transformObjectLinks(object); | ||
const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: record }, fetchProps)); | ||
const finalObject = yield this.read(response.id); | ||
if (!finalObject) { | ||
throw new Error('The server failed to save the record'); | ||
} | ||
return finalObject; | ||
}); | ||
} | ||
createMany(objects) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this); | ||
const records = objects.map((object) => transformObjectLinks(object)); | ||
const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body: { records } }, fetchProps)); | ||
// TODO: Use filer.$any() to get all the records | ||
const finalObjects = yield Promise.all(response.recordIDs.map((id) => this.read(id))); | ||
if (finalObjects.some((object) => !object)) { | ||
throw new Error('The server failed to save the record'); | ||
} | ||
return finalObjects; | ||
}); | ||
} | ||
read(recordId) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this); | ||
const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps)); | ||
return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response); | ||
}); | ||
} | ||
update(recordId, object) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this); | ||
const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId }, body: object }, fetchProps)); | ||
// TODO: Review this, not sure we are properly initializing the object | ||
return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response); | ||
}); | ||
} | ||
delete(recordId) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this); | ||
yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f"), recordId } }, fetchProps)); | ||
}); | ||
} | ||
query(query, options) { | ||
var _a, _b, _c; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const data = query.getData(); | ||
const body = { | ||
filter: Object.values(data.filter).some(Boolean) ? data.filter : undefined, | ||
sort: (_a = (0, filters_1.buildSortFilter)(options === null || options === void 0 ? void 0 : options.sort)) !== null && _a !== void 0 ? _a : data.sort, | ||
page: (_b = options === null || options === void 0 ? void 0 : options.page) !== null && _b !== void 0 ? _b : data.page, | ||
columns: (_c = options === null || options === void 0 ? void 0 : options.columns) !== null && _c !== void 0 ? _c : data.columns | ||
}; | ||
const fetchProps = yield __classPrivateFieldGet(this, _RestRepository_instances, "m", _RestRepository_getFetchProps).call(this); | ||
const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace: '{workspaceId}', dbBranchName: '{dbBranch}', tableName: __classPrivateFieldGet(this, _RestRepository_table, "f") }, body }, fetchProps)); | ||
const records = objects.map((record) => __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), record)); | ||
// TODO: We should properly type this any | ||
return new pagination_1.Page(query, meta, records); | ||
}); | ||
} | ||
} | ||
exports.RestRepository = RestRepository; | ||
_RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap(), _RestRepository_instances = new WeakSet(), _RestRepository_getFetchProps = function _RestRepository_getFetchProps() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch(); | ||
return { | ||
fetchImpl: __classPrivateFieldGet(this, _RestRepository_fetch, "f"), | ||
apiKey: __classPrivateFieldGet(this, _RestRepository_client, "f").options.apiKey, | ||
apiUrl: '', | ||
// Instead of using workspace and dbBranch, we inject a probably CNAME'd URL | ||
workspacesApiUrl: (path, params) => { | ||
var _a, _b; | ||
const baseUrl = (_a = __classPrivateFieldGet(this, _RestRepository_client, "f").options.databaseURL) !== null && _a !== void 0 ? _a : ''; | ||
const hasBranch = (_b = params.dbBranchName) !== null && _b !== void 0 ? _b : params.branch; | ||
const newPath = path.replace(/^\/db\/[^/]+/, hasBranch ? `:${branch}` : ''); | ||
return baseUrl + newPath; | ||
} | ||
}; | ||
}); | ||
}; | ||
class RestRespositoryFactory { | ||
createRepository(client, table) { | ||
return new RestRepository(client, table); | ||
} | ||
} | ||
exports.RestRespositoryFactory = RestRespositoryFactory; | ||
class BaseClient { | ||
constructor(options, links) { | ||
_BaseClient_links.set(this, void 0); | ||
_BaseClient_branch.set(this, void 0); | ||
if (!options.databaseURL || !options.apiKey || !options.branch) { | ||
throw new Error('Options databaseURL, apiKey and branch are required'); | ||
} | ||
this.options = options; | ||
__classPrivateFieldSet(this, _BaseClient_links, links, "f"); | ||
} | ||
initObject(table, object) { | ||
const o = {}; | ||
Object.assign(o, object); | ||
const tableLinks = __classPrivateFieldGet(this, _BaseClient_links, "f")[table] || []; | ||
for (const link of tableLinks) { | ||
const [field, linkTable] = link; | ||
const value = o[field]; | ||
if (value && typeof value === 'object') { | ||
const { id } = value; | ||
if (Object.keys(value).find((col) => col === 'id')) { | ||
o[field] = this.initObject(linkTable, value); | ||
} | ||
else if (id) { | ||
o[field] = { | ||
id, | ||
get: () => { | ||
this.db[linkTable].read(id); | ||
} | ||
}; | ||
} | ||
} | ||
} | ||
const db = this.db; | ||
o.read = function () { | ||
return db[table].read(o['id']); | ||
}; | ||
o.update = function (data) { | ||
return db[table].update(o['id'], data); | ||
}; | ||
o.delete = function () { | ||
return db[table].delete(o['id']); | ||
}; | ||
for (const prop of ['read', 'update', 'delete']) { | ||
Object.defineProperty(o, prop, { enumerable: false }); | ||
} | ||
// TODO: links and rev links | ||
Object.freeze(o); | ||
return o; | ||
} | ||
getBranch() { | ||
var e_1, _a; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (__classPrivateFieldGet(this, _BaseClient_branch, "f")) | ||
return __classPrivateFieldGet(this, _BaseClient_branch, "f"); | ||
const { branch: param } = this.options; | ||
const strategies = Array.isArray(param) ? [...param] : [param]; | ||
const evaluateBranch = (strategy) => __awaiter(this, void 0, void 0, function* () { | ||
return isBranchStrategyBuilder(strategy) ? yield strategy() : strategy; | ||
}); | ||
try { | ||
for (var strategies_1 = __asyncValues(strategies), strategies_1_1; strategies_1_1 = yield strategies_1.next(), !strategies_1_1.done;) { | ||
const strategy = strategies_1_1.value; | ||
const branch = yield evaluateBranch(strategy); | ||
if (branch) { | ||
__classPrivateFieldSet(this, _BaseClient_branch, branch, "f"); | ||
return branch; | ||
} | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (strategies_1_1 && !strategies_1_1.done && (_a = strategies_1.return)) yield _a.call(strategies_1); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
throw new Error('Unable to resolve branch value'); | ||
}); | ||
} | ||
} | ||
exports.BaseClient = BaseClient; | ||
_BaseClient_links = new WeakMap(), _BaseClient_branch = new WeakMap(); | ||
exports.XataError = void 0; | ||
class XataError extends Error { | ||
@@ -244,15 +26,3 @@ constructor(message, status) { | ||
exports.XataError = XataError; | ||
const isBranchStrategyBuilder = (strategy) => { | ||
return typeof strategy === 'function'; | ||
}; | ||
// TODO: We can find a better implementation for links | ||
const transformObjectLinks = (object) => { | ||
return Object.entries(object).reduce((acc, [key, value]) => { | ||
if (value && typeof value === 'object' && typeof value.id === 'string') { | ||
return Object.assign(Object.assign({}, acc), { [key]: value.id }); | ||
} | ||
return Object.assign(Object.assign({}, acc), { [key]: value }); | ||
}, {}); | ||
}; | ||
__exportStar(require("./api"), exports); | ||
__exportStar(require("./schema"), exports); |
export * from './operators'; | ||
export type { XataRecord } from './record'; | ||
export { Repository, RestRepository, RestRespositoryFactory, BaseClient } from './repository'; | ||
export type { XataClientOptions } from './repository'; | ||
export { Query } from './query'; |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -13,2 +17,10 @@ if (k2 === undefined) k2 = k; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Query = exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0; | ||
__exportStar(require("./operators"), exports); | ||
var repository_1 = require("./repository"); | ||
Object.defineProperty(exports, "Repository", { enumerable: true, get: function () { return repository_1.Repository; } }); | ||
Object.defineProperty(exports, "RestRepository", { enumerable: true, get: function () { return repository_1.RestRepository; } }); | ||
Object.defineProperty(exports, "RestRespositoryFactory", { enumerable: true, get: function () { return repository_1.RestRespositoryFactory; } }); | ||
Object.defineProperty(exports, "BaseClient", { enumerable: true, get: function () { return repository_1.BaseClient; } }); | ||
var query_1 = require("./query"); | ||
Object.defineProperty(exports, "Query", { enumerable: true, get: function () { return query_1.Query; } }); |
@@ -9,3 +9,12 @@ import { XataRecord } from '..'; | ||
}; | ||
export declare class Page<T extends XataRecord, R extends XataRecord> { | ||
export interface Paginable<T extends XataRecord, R extends XataRecord = T> { | ||
meta: PaginationQueryMeta; | ||
records: R[]; | ||
nextPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
previousPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
firstPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
lastPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
hasNextPage(): boolean; | ||
} | ||
export declare class Page<T extends XataRecord, R extends XataRecord> implements Paginable<T, R> { | ||
#private; | ||
@@ -12,0 +21,0 @@ readonly meta: PaginationQueryMeta; |
import { XataRecord, Repository } from '..'; | ||
import { FilterExpression, SortExpression, PageConfig, ColumnsFilter } from '../api/schemas'; | ||
import { DeepConstraint, FilterConstraints, SortDirection, SortFilter } from './filters'; | ||
import { PaginationOptions, Page } from './pagination'; | ||
import { PaginationOptions, Page, Paginable, PaginationQueryMeta } from './pagination'; | ||
import { Selectable, SelectableColumn, Select } from './selection'; | ||
export declare type QueryOptions<T> = { | ||
export declare type QueryOptions<T extends XataRecord> = { | ||
page?: PaginationOptions; | ||
@@ -11,3 +11,3 @@ columns?: Extract<keyof Selectable<T>, string>[]; | ||
}; | ||
export declare type QueryTableData = { | ||
export declare type QueryTableOptions = { | ||
filter: FilterExpression; | ||
@@ -18,6 +18,8 @@ sort?: SortExpression; | ||
}; | ||
export declare class Query<T extends XataRecord, R extends XataRecord = T> { | ||
export declare class Query<T extends XataRecord, R extends XataRecord = T> implements Paginable<T, R> { | ||
#private; | ||
constructor(repository: Repository<T> | null, table: string, data: Partial<QueryTableData>, parent?: Partial<QueryTableData>); | ||
getData(): QueryTableData; | ||
readonly meta: PaginationQueryMeta; | ||
readonly records: R[]; | ||
constructor(repository: Repository<T> | null, table: string, data: Partial<QueryTableOptions>, parent?: Partial<QueryTableOptions>); | ||
getQueryOptions(): QueryTableOptions; | ||
any(...queries: Query<T, R>[]): Query<T, R>; | ||
@@ -28,10 +30,16 @@ all(...queries: Query<T, R>[]): Query<T, R>; | ||
filter(constraints: FilterConstraints<T>): Query<T, R>; | ||
filter<F extends keyof T>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>; | ||
filter<F extends keyof Selectable<T>>(column: F, value: FilterConstraints<T[F]> | DeepConstraint<T[F]>): Query<T, R>; | ||
sort<F extends keyof T>(column: F, direction: SortDirection): Query<T, R>; | ||
select<K extends SelectableColumn<T>>(columns: K[]): Query<T, Select<T, K>>; | ||
getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R>>; | ||
getPaginated<Options extends QueryOptions<T>>(options?: Options): Promise<Page<T, typeof options extends { | ||
columns: SelectableColumn<T>[]; | ||
} ? Select<T, typeof options['columns'][number]> : R>>; | ||
[Symbol.asyncIterator](): AsyncIterableIterator<R>; | ||
getIterator(chunk: number, options?: Omit<QueryOptions<T>, 'page'>): AsyncGenerator<R[]>; | ||
getMany<Options extends QueryOptions<T>>(options?: Options): Promise<(typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R)[]>; | ||
getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<(typeof options['columns'] extends SelectableColumn<T>[] ? Select<T, typeof options['columns'][number]> : R) | null>; | ||
getMany<Options extends QueryOptions<T>>(options?: Options): Promise<(typeof options extends { | ||
columns: SelectableColumn<T>[]; | ||
} ? Select<T, typeof options['columns'][number]> : R)[]>; | ||
getOne<Options extends Omit<QueryOptions<T>, 'page'>>(options?: Options): Promise<(typeof options extends { | ||
columns: SelectableColumn<T>[]; | ||
} ? Select<T, typeof options['columns'][number]> : R) | null>; | ||
/**async deleteAll(): Promise<number> { | ||
@@ -42,4 +50,6 @@ // TODO: Return number of affected rows | ||
nextPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
previousPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
firstPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
lastPage(size?: number, offset?: number): Promise<Page<T, R>>; | ||
hasNextPage(): boolean; | ||
} |
@@ -51,2 +51,5 @@ "use strict"; | ||
_Query_data.set(this, { filter: {} }); | ||
// Implements pagination | ||
this.meta = { page: { cursor: 'start', more: true } }; | ||
this.records = []; | ||
__classPrivateFieldSet(this, _Query_table, table, "f"); | ||
@@ -74,19 +77,19 @@ if (repository) { | ||
} | ||
getData() { | ||
getQueryOptions() { | ||
return __classPrivateFieldGet(this, _Query_data, "f"); | ||
} | ||
any(...queries) { | ||
const $any = (0, lang_1.compact)(queries.map((query) => query.getData().filter.$any)).flat(); | ||
const $any = queries.map((query) => query.getQueryOptions().filter); | ||
return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $any } }, __classPrivateFieldGet(this, _Query_data, "f")); | ||
} | ||
all(...queries) { | ||
const $all = (0, lang_1.compact)(queries.map((query) => query.getData().filter.$all)).flat(); | ||
const $all = queries.map((query) => query.getQueryOptions().filter); | ||
return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $all } }, __classPrivateFieldGet(this, _Query_data, "f")); | ||
} | ||
not(...queries) { | ||
const $not = (0, lang_1.compact)(queries.map((query) => query.getData().filter.$not)).flat(); | ||
const $not = queries.map((query) => query.getQueryOptions().filter); | ||
return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $not } }, __classPrivateFieldGet(this, _Query_data, "f")); | ||
} | ||
none(...queries) { | ||
const $none = (0, lang_1.compact)(queries.map((query) => query.getData().filter.$none)).flat(); | ||
const $none = queries.map((query) => query.getQueryOptions().filter); | ||
return new Query(__classPrivateFieldGet(this, _Query_repository, "f"), __classPrivateFieldGet(this, _Query_table, "f"), { filter: { $none } }, __classPrivateFieldGet(this, _Query_data, "f")); | ||
@@ -115,5 +118,3 @@ } | ||
getPaginated(options = {}) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return __classPrivateFieldGet(this, _Query_repository, "f").query(this, options); | ||
}); | ||
return __classPrivateFieldGet(this, _Query_repository, "f").query(this, options); | ||
} | ||
@@ -167,17 +168,17 @@ [(_Query_table = new WeakMap(), _Query_repository = new WeakMap(), _Query_data = new WeakMap(), Symbol.asyncIterator)]() { | ||
nextPage(size, offset) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.firstPage(size, offset); | ||
}); | ||
return this.firstPage(size, offset); | ||
} | ||
previousPage(size, offset) { | ||
return this.firstPage(size, offset); | ||
} | ||
firstPage(size, offset) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.getPaginated({ page: { size, offset } }); | ||
}); | ||
return this.getPaginated({ page: { size, offset } }); | ||
} | ||
lastPage(size, offset) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return this.getPaginated({ page: { size, offset, before: 'end' } }); | ||
}); | ||
return this.getPaginated({ page: { size, offset, before: 'end' } }); | ||
} | ||
hasNextPage() { | ||
return this.meta.page.more; | ||
} | ||
} | ||
exports.Query = Query; |
import { XataRecord } from '..'; | ||
import { PartialBy } from '../util/lang'; | ||
import { StringKeys, UnionToIntersection, Values } from '../util/types'; | ||
@@ -7,9 +8,4 @@ import { Query } from './query'; | ||
}; | ||
declare type OmitQueries<T> = { | ||
[key in keyof T as T[key] extends Query<any> ? never : key]: T[key]; | ||
}; | ||
declare type OmitMethods<T> = { | ||
[key in keyof T as T[key] extends Function ? never : key]: T[key]; | ||
}; | ||
export declare type Selectable<T> = Omit<OmitQueries<OmitMethods<T>>, 'id' | 'xata'>; | ||
declare type InternalProperties = keyof Omit<XataRecord, 'id'>; | ||
export declare type Selectable<T extends XataRecord> = Omit<PartialBy<T, 'id'>, InternalProperties>; | ||
export declare type SelectableColumn<O> = '*' | (O extends Array<unknown> ? never : O extends Record<string, any> ? '*' | Values<{ | ||
@@ -16,0 +12,0 @@ [K in StringKeys<O>]: O[K] extends Record<string, any> ? `${K}.${SelectableColumn<O[K]>}` : K; |
export declare function compact<T>(arr: Array<T | null | undefined>): T[]; | ||
export declare type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; |
{ | ||
"name": "@xata.io/client", | ||
"version": "0.0.0-alpha.b8b17fa", | ||
"version": "0.0.0-alpha.b9ad17d", | ||
"description": "Xata.io SDK for TypeScript and JavaScript", | ||
"type": "module", | ||
"main": "./dist/index.js", | ||
@@ -23,3 +24,3 @@ "types": "./dist/index.d.ts", | ||
"homepage": "https://github.com/xataio/client-ts/blob/main/client/README.md", | ||
"gitHead": "b8b17fa338fdbdc560de1ef3cc5810581e493437" | ||
"gitHead": "b9ad17d66d4762fb161e71167a283232507f779e" | ||
} |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
174701
41
4137
5
Yes