Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@xata.io/client

Package Overview
Dependencies
Maintainers
4
Versions
4350
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@xata.io/client - npm Package Compare versions

Comparing version 0.0.0-alpha.2b59725 to 0.0.0-alpha.2d799cf

dist/api/client.d.ts

52

dist/index.d.ts

@@ -0,1 +1,2 @@

import { FetcherExtraProps, FetchImpl } from './api/fetcher';
export interface XataRecord {

@@ -84,6 +85,6 @@ id: string;

records: R[];
nextPage(options?: OffsetNavigationOptions): Promise<Page<T, R>>;
previousPage(options?: OffsetNavigationOptions): Promise<Page<T, R>>;
firstPage(options?: OffsetNavigationOptions): Promise<Page<T, R>>;
lastPage(options?: OffsetNavigationOptions): Promise<Page<T, 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;

@@ -96,6 +97,6 @@ }

constructor(query: Query<T, R>, meta: QueryMeta, records?: R[]);
nextPage(options?: OffsetNavigationOptions): Promise<Page<T, R>>;
previousPage(options?: OffsetNavigationOptions): Promise<Page<T, R>>;
firstPage(options?: OffsetNavigationOptions): Promise<Page<T, R>>;
lastPage(options?: OffsetNavigationOptions): Promise<Page<T, 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;

@@ -123,2 +124,4 @@ }

getPaginated(options?: BulkQueryOptions<T>): Promise<Page<T, R>>;
[Symbol.asyncIterator](): AsyncIterableIterator<R>;
getIterator(chunk: number, options?: Omit<BulkQueryOptions<T>, 'page'>): AsyncGenerator<R[]>;
getMany(options?: BulkQueryOptions<T>): Promise<R[]>;

@@ -128,9 +131,12 @@ getOne(options?: Omit<BulkQueryOptions<T>, 'page'>): Promise<R | null>;

include(columns: Include<T>): this;
nextPage(options?: OffsetNavigationOptions): Promise<Page<T, R>>;
previousPage(options?: OffsetNavigationOptions): Promise<Page<T, R>>;
firstPage(options?: OffsetNavigationOptions): Promise<Page<T, R>>;
lastPage(options?: OffsetNavigationOptions): Promise<Page<T, 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 abstract class Repository<T> extends Query<T, Selectable<T>> {
abstract client: BaseClient<any>;
abstract fetch: FetchImpl;
abstract fetchProps: FetcherExtraProps;
select<K extends keyof Selectable<T>>(...columns: K[]): Query<T, Select<T, K>>;

@@ -142,16 +148,14 @@ abstract create(object: Selectable<T>): Promise<T>;

abstract delete(id: string): void;
abstract executeQuery<R>(query: Query<T, R>, options?: BulkQueryOptions<T>): Promise<Page<T, R>>;
}
export declare class RestRepository<T> extends Repository<T> {
client: BaseClient<any>;
fetch: any;
fetch: FetchImpl;
constructor(client: BaseClient<any>, table: string);
request<T>(method: string, path: string, body?: unknown): Promise<T | undefined>;
get fetchProps(): FetcherExtraProps;
select<K extends keyof T>(...columns: K[]): Query<T, Select<T, K>>;
create(object: T): Promise<T>;
createMany(records: T[]): Promise<T[]>;
read(id: string): Promise<T | null>;
update(id: string, object: Partial<T>): Promise<T>;
delete(id: string): Promise<void>;
executeQuery<R>(query: Query<T, R>, options?: BulkQueryOptions<T>): Promise<Page<T, R>>;
createMany(objects: T[]): Promise<T[]>;
read(recordId: string): Promise<T | null>;
update(recordId: string, object: Partial<T>): Promise<T>;
delete(recordId: string): Promise<void>;
}

@@ -169,4 +173,4 @@ interface RepositoryFactory {

export declare type XataClientOptions = {
fetch?: unknown;
databaseURL: string;
fetch?: FetchImpl;
databaseURL?: string;
branch: BranchStrategyOption;

@@ -183,2 +187,4 @@ apiKey: string;

initObject<T>(table: string, object: object): T;
getWorkspaceId(): Promise<string>;
getDatabaseId(): Promise<string>;
getBranch(): Promise<string>;

@@ -191,2 +197,2 @@ }

export declare type Links = Record<string, Array<string[]>>;
export {};
export * from './api';
"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]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -18,4 +28,18 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.XataError = exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = exports.Query = exports.includesAll = exports.includesPattern = exports.includesSubstring = exports.includes = exports.contains = exports.isNot = exports.is = exports.pattern = exports.endsWith = exports.startsWith = exports.notExists = exports.exists = exports.le = exports.lte = exports.lt = exports.gte = exports.ge = exports.gt = void 0;
const api_1 = require("./api");
const errors_1 = require("./util/errors");
const gt = (value) => ({ $gt: value });

@@ -64,23 +88,19 @@ exports.gt = gt;

}
nextPage(options = {}) {
nextPage(size, offset) {
return __awaiter(this, void 0, void 0, function* () {
const { size, offset } = options;
return this.query.getPaginated({ page: { size, offset, after: this.meta.page.cursor } });
});
}
previousPage(options = {}) {
previousPage(size, offset) {
return __awaiter(this, void 0, void 0, function* () {
const { size, offset } = options;
return this.query.getPaginated({ page: { size, offset, before: this.meta.page.cursor } });
});
}
firstPage(options = {}) {
firstPage(size, offset) {
return __awaiter(this, void 0, void 0, function* () {
const { size, offset } = options;
return this.query.getPaginated({ page: { size, offset, first: this.meta.page.cursor } });
});
}
lastPage(options = {}) {
lastPage(size, offset) {
return __awaiter(this, void 0, void 0, function* () {
const { size, offset } = options;
return this.query.getPaginated({ page: { size, offset, last: this.meta.page.cursor } });

@@ -174,5 +194,51 @@ });

return __awaiter(this, void 0, void 0, function* () {
return this.repository.executeQuery(this, options);
const filter = {
$any: this.$any,
$all: this.$all,
$not: this.$not,
$none: this.$none
};
const workspace = yield this.repository.client.getWorkspaceId();
const database = yield this.repository.client.getDatabaseId();
const branch = yield this.repository.client.getBranch();
const { meta, records: objects } = yield (0, api_1.queryTable)(Object.assign({ pathParams: { workspace, dbBranchName: branch, tableName: this.table }, body: {
//@ts-ignore TODO: Review
filter: compactObject(filter),
sort: this.$sort,
page: options === null || options === void 0 ? void 0 : options.page
} }, this.repository.fetchProps));
const records = objects.map((record) => this.repository.client.initObject(this.table, record));
return new Page(this, meta, records);
});
}
[Symbol.asyncIterator]() {
return __asyncGenerator(this, arguments, function* _a() {
var e_1, _b;
try {
for (var _c = __asyncValues(this.getIterator(1)), _d; _d = yield __await(_c.next()), !_d.done;) {
const [record] = _d.value;
yield yield __await(record);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_b = _c.return)) yield __await(_b.call(_c));
}
finally { if (e_1) throw e_1.error; }
}
});
}
getIterator(chunk, options = {}) {
return __asyncGenerator(this, arguments, function* getIterator_1() {
let offset = 0;
let end = false;
while (!end) {
const { records, meta } = yield __await(this.getPaginated(Object.assign(Object.assign({}, options), { page: { size: chunk, offset } })));
yield yield __await(records);
offset += chunk;
end = !meta.page.more;
}
});
}
getMany(options) {

@@ -200,22 +266,20 @@ return __awaiter(this, void 0, void 0, function* () {

}
nextPage(options = {}) {
nextPage(size, offset) {
return __awaiter(this, void 0, void 0, function* () {
return this.firstPage(options);
return this.firstPage(size, offset);
});
}
previousPage(options = {}) {
previousPage(size, offset) {
return __awaiter(this, void 0, void 0, function* () {
return this.firstPage(options);
return this.firstPage(size, offset);
});
}
firstPage(options = {}) {
firstPage(size, offset) {
return __awaiter(this, void 0, void 0, function* () {
const { size } = options;
return this.getPaginated({ page: { size, offset: 0 } });
return this.getPaginated({ page: { size, offset } });
});
}
lastPage(options = {}) {
lastPage(size, offset) {
return __awaiter(this, void 0, void 0, function* () {
const { size } = options;
return this.getPaginated({ page: { size, before: 'end' } });
return this.getPaginated({ page: { size, offset, before: 'end' } });
});

@@ -238,22 +302,6 @@ }

this.client = client;
const { fetch } = client.options;
if (fetch) {
this.fetch = fetch;
}
else if (typeof window === 'object') {
this.fetch = window.fetch;
}
else if (typeof require === 'function') {
try {
this.fetch = require('node-fetch');
}
catch (err) {
try {
this.fetch = require('cross-fetch');
}
catch (err) {
throw new Error('No fetch implementation found. Please provide one in the constructor');
}
}
}
const fetchImpl = typeof fetch !== 'undefined' ? fetch : this.client.options.fetch;
if (!fetchImpl)
throw new Error(errors_1.errors.noFetchImplementation);
this.fetch = fetchImpl;
Object.defineProperty(this, 'client', { enumerable: false });

@@ -263,35 +311,15 @@ Object.defineProperty(this, 'fetch', { enumerable: false });

}
request(method, path, body) {
return __awaiter(this, void 0, void 0, function* () {
const { databaseURL, apiKey } = this.client.options;
const branch = yield this.client.getBranch();
const resp = yield this.fetch(`${databaseURL}:${branch}${path}`, {
method,
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`
},
body: JSON.stringify(body)
});
if (!resp.ok) {
try {
const json = yield resp.json();
const message = json.message;
if (typeof message === 'string') {
throw new XataError(message, resp.status);
}
}
catch (err) {
if (err instanceof XataError)
throw err;
// Ignore errors for other reasons.
// For example if the response's body cannot be parsed as JSON
}
throw new XataError(resp.statusText, resp.status);
get fetchProps() {
return {
fetchImpl: this.fetch,
apiKey: this.client.options.apiKey,
apiUrl: '',
workspacesApiUrl: (path, params) => {
var _a, _b;
const baseUrl = (_a = this.client.options.databaseURL) !== null && _a !== void 0 ? _a : '';
const branch = (_b = params.dbBranchName) !== null && _b !== void 0 ? _b : params.branch;
const newPath = path.replace(/^\/db\/[^/]+/, branch ? `:${branch}` : '');
return baseUrl + newPath;
}
if (resp.status === 204)
return undefined;
return resp.json();
});
};
}

@@ -303,49 +331,40 @@ select(...columns) {

return __awaiter(this, void 0, void 0, function* () {
const body = Object.assign({}, object);
for (const key of Object.keys(body)) {
const value = body[key];
if (value && typeof value === 'object' && typeof value.id === 'string') {
body[key] = value.id;
}
const workspace = yield this.client.getWorkspaceId();
const branch = yield this.client.getBranch();
const record = transformObjectLinks(object);
const response = yield (0, api_1.insertRecord)(Object.assign({ pathParams: { workspace, dbBranchName: branch, tableName: this.table }, body: record }, this.repository.fetchProps));
const finalObject = yield this.read(response.id);
if (!finalObject) {
throw new Error('The server failed to save the record');
}
const response = yield this.request('POST', `/tables/${this.table}/data`, body);
if (!response) {
throw new Error("The server didn't return any data for the query");
}
// TODO: Review this, not sure we are properly initializing the object
return this.client.initObject(this.table, response);
return finalObject;
});
}
createMany(records) {
createMany(objects) {
return __awaiter(this, void 0, void 0, function* () {
// TODO: Review the id of the records
const response = yield this.request('POST', `/tables/${this.table}/bulk`, { records });
if (!response) {
throw new Error("The server didn't return any data for the query");
const workspace = yield this.client.getWorkspaceId();
const branch = yield this.client.getBranch();
const records = objects.map((object) => transformObjectLinks(object));
const response = yield (0, api_1.bulkInsertTableRecords)(Object.assign({ pathParams: { workspace, dbBranchName: branch, tableName: this.table }, body: { records } }, this.repository.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');
}
// TODO: Review this, not sure we are properly initializing the object
return response.recordIDs.map((record) => this.client.initObject(this.table, { id: record }));
return finalObjects;
});
}
read(id) {
read(recordId) {
return __awaiter(this, void 0, void 0, function* () {
try {
const response = yield this.request('GET', `/tables/${this.table}/data/${id}`);
if (!response)
return null;
return this.client.initObject(this.table, response);
}
catch (err) {
if (err.status === 404)
return null;
throw err;
}
const workspace = yield this.client.getWorkspaceId();
const branch = yield this.client.getBranch();
const response = yield (0, api_1.getRecord)(Object.assign({ pathParams: { workspace, dbBranchName: branch, tableName: this.table, recordId } }, this.repository.fetchProps));
return this.client.initObject(this.table, response);
});
}
update(id, object) {
update(recordId, object) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield this.request('PUT', `/tables/${this.table}/data/${id}`, object);
if (!response) {
throw new Error("The server didn't return any data for the query");
}
const workspace = yield this.client.getWorkspaceId();
const branch = yield this.client.getBranch();
const response = yield (0, api_1.insertRecordWithID)(Object.assign({ pathParams: { workspace, dbBranchName: branch, tableName: this.table, recordId }, body: object }, this.repository.fetchProps));
// TODO: Review this, not sure we are properly initializing the object

@@ -355,30 +374,9 @@ return this.client.initObject(this.table, response);

}
delete(id) {
delete(recordId) {
return __awaiter(this, void 0, void 0, function* () {
// TODO: Return boolean?
yield this.request('DELETE', `/tables/${this.table}/data/${id}`);
const workspace = yield this.client.getWorkspaceId();
const branch = yield this.client.getBranch();
yield (0, api_1.deleteRecord)(Object.assign({ pathParams: { workspace, dbBranchName: branch, tableName: this.table, recordId } }, this.repository.fetchProps));
});
}
executeQuery(query, options) {
return __awaiter(this, void 0, void 0, function* () {
const filter = {
$any: query.$any,
$all: query.$all,
$not: query.$not,
$none: query.$none
};
const body = {
filter: Object.values(filter).some(Boolean) ? filter : undefined,
sort: query.$sort,
page: options === null || options === void 0 ? void 0 : options.page
};
const response = yield this.request('POST', `/tables/${this.table}/query`, body);
if (!response) {
throw new Error("The server didn't return any data for the query");
}
const { meta, records: objects } = response;
const records = objects.map((record) => this.client.initObject(this.table, record));
return new Page(query, meta, records);
});
}
}

@@ -439,4 +437,28 @@ exports.RestRepository = RestRepository;

}
getWorkspaceId() {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
// TODO: FIXME: How do we handle CNAME use-case? workspaceUrl/db/db:branch. We need to inject branch
const workspaceAndDatabaseRegex = /^(?:https?:\/\/)?([^.]+).*\/db\/([^/]+)$/;
const workspace = (_b = workspaceAndDatabaseRegex.exec((_a = this.options.databaseURL) !== null && _a !== void 0 ? _a : '')) === null || _b === void 0 ? void 0 : _b[1];
if (!workspace) {
throw new Error('XATA_DATABASE_URL does not have a valid workspace');
}
return workspace;
});
}
getDatabaseId() {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
// TODO: FIXME: How do we handle CNAME use-case? workspaceUrl/db/db:branch. We need to inject branch
const workspaceAndDatabaseRegex = /^(?:https?:\/\/)?([^.]+).*\/db\/([^/]+)$/;
const database = (_b = workspaceAndDatabaseRegex.exec((_a = this.options.databaseURL) !== null && _a !== void 0 ? _a : '')) === null || _b === void 0 ? void 0 : _b[2];
if (!database) {
throw new Error('XATA_DATABASE_URL does not have a valid workspace');
}
return database;
});
}
getBranch() {
var e_1, _a;
var e_2, _a;
return __awaiter(this, void 0, void 0, function* () {

@@ -460,3 +482,3 @@ if (this.branch)

}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {

@@ -466,3 +488,3 @@ try {

}
finally { if (e_1) throw e_1.error; }
finally { if (e_2) throw e_2.error; }
}

@@ -484,1 +506,19 @@ throw new Error('Unable to resolve branch value');

};
// 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 });
}, {});
};
function compactObject(object) {
return Object.entries(object).reduce((acc, [key, value]) => {
// @ts-ignore TODO: Review
if (value !== undefined)
acc[key] = value;
return acc;
}, {});
}
__exportStar(require("./api"), exports);
{
"name": "@xata.io/client",
"version": "0.0.0-alpha.2b59725",
"version": "0.0.0-alpha.2d799cf",
"description": "Xata.io SDK for TypeScript and JavaScript",

@@ -9,3 +9,3 @@ "main": "./dist/index.js",

"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc",
"build": "tsc -p tsconfig.build.json",
"prepack": "npm run build"

@@ -24,3 +24,3 @@ },

"homepage": "https://github.com/xataio/client-ts/blob/main/client/README.md",
"gitHead": "2b59725e5305b5f9b4e3f1caccdd17cd5b98a357"
"gitHead": "2d799cf42492da7c448581b11eeabdd6ba0f6db3"
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc