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
4351
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.1d9104e to 0.0.0-alpha.216c136

dist/schema/filters.d.ts

104

dist/index.d.ts

@@ -0,1 +1,4 @@

import { Page } from './schema/pagination';
import { Query, QueryOptions } from './schema/query';
import { Selectable, SelectableColumn, Select } from './schema/selection';
export interface XataRecord {

@@ -10,103 +13,26 @@ id: string;

}
export declare type Queries<T> = {
[key in keyof T as T[key] extends Query<infer A, infer B> ? key : never]: T[key];
};
export declare type OmitQueries<T> = {
[key in keyof T as T[key] extends Query<infer A, infer B> ? never : key]: T[key];
};
export declare type OmitLinks<T> = {
[key in keyof T as T[key] extends XataRecord ? never : key]: T[key];
};
export 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'>;
export declare type Select<T, K extends keyof T> = Pick<T, K> & Queries<T> & XataRecord;
export declare type Include<T> = {
[key in keyof T as T[key] extends XataRecord ? key : never]?: boolean | Array<keyof Selectable<T[key]>>;
};
declare type SortDirection = 'asc' | 'desc';
declare type Operator = '$gt' | '$lt' | '$ge' | '$le' | '$exists' | '$notExists' | '$endsWith' | '$startsWith' | '$pattern' | '$is' | '$isNot' | '$contains' | '$includes' | '$includesSubstring' | '$includesPattern' | '$includesAll';
declare type Constraint<T> = {
[key in Operator]?: T;
};
declare type DeepConstraint<T> = T extends Record<string, any> ? {
[key in keyof T]?: T[key] | DeepConstraint<T[key]>;
} : Constraint<T>;
declare type ComparableType = number | Date;
export declare const gt: <T extends ComparableType>(value: T) => Constraint<T>;
export declare const ge: <T extends ComparableType>(value: T) => Constraint<T>;
export declare const gte: <T extends ComparableType>(value: T) => Constraint<T>;
export declare const lt: <T extends ComparableType>(value: T) => Constraint<T>;
export declare const lte: <T extends ComparableType>(value: T) => Constraint<T>;
export declare const le: <T extends ComparableType>(value: T) => Constraint<T>;
export declare const exists: (column: string) => Constraint<string>;
export declare const notExists: (column: string) => Constraint<string>;
export declare const startsWith: (value: string) => Constraint<string>;
export declare const endsWith: (value: string) => Constraint<string>;
export declare const pattern: (value: string) => Constraint<string>;
export declare const is: <T>(value: T) => Constraint<T>;
export declare const isNot: <T>(value: T) => Constraint<T>;
export declare const contains: <T>(value: T) => Constraint<T>;
export declare const includes: (value: string) => Constraint<string>;
export declare const includesSubstring: (value: string) => Constraint<string>;
export declare const includesPattern: (value: string) => Constraint<string>;
export declare const includesAll: (value: string) => Constraint<string>;
declare type FilterConstraints<T> = {
[key in keyof T]?: T[key] extends Record<string, any> ? FilterConstraints<T[key]> : T[key] | DeepConstraint<T[key]>;
};
declare type BulkQueryOptions<T> = {
filter?: FilterConstraints<T>;
sort?: {
column: keyof T;
direction?: SortDirection;
} | keyof T;
};
declare type QueryOrConstraint<T, R> = Query<T, R> | Constraint<T>;
export declare class Query<T, R = T> {
table: string;
repository: Repository<T>;
readonly $any?: QueryOrConstraint<T, R>[];
readonly $all?: QueryOrConstraint<T, R>[];
readonly $not?: QueryOrConstraint<T, R>[];
readonly $none?: QueryOrConstraint<T, R>[];
readonly $sort?: Record<string, SortDirection>;
constructor(repository: Repository<T> | null, table: string, data: Partial<Query<T, R>>, parent?: Query<T, R>);
any(...queries: Query<T, R>[]): Query<T, R>;
all(...queries: Query<T, R>[]): Query<T, R>;
not(...queries: Query<T, R>[]): Query<T, R>;
none(...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>;
sort<F extends keyof T>(column: F, direction: SortDirection): Query<T, R>;
getMany(options?: BulkQueryOptions<T>): Promise<R[]>;
getOne(options?: BulkQueryOptions<T>): Promise<R | null>;
deleteAll(): Promise<number>;
include(columns: Include<T>): this;
}
export declare abstract class Repository<T> extends Query<T, Selectable<T>> {
select<K extends keyof Selectable<T>>(...columns: K[]): Query<T, Select<T, K>>;
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>(query: Query<T, R>): Promise<R[]>;
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 Repository<T> {
client: BaseClient<any>;
fetch: any;
export declare class RestRepository<T extends XataRecord> extends Repository<T> {
#private;
constructor(client: BaseClient<any>, table: string);
request(method: string, path: string, body?: unknown): Promise<any>;
select<K extends keyof T>(...columns: K[]): Query<T, Select<T, K>>;
request<T>(method: string, path: string, body?: unknown): Promise<T | undefined>;
create(object: T): Promise<T>;
createMany(objects: T[]): Promise<T[]>;
read(id: string): Promise<T | null>;
update(id: string, object: Partial<T>): Promise<T>;
delete(id: string): Promise<void>;
query<R>(query: Query<T, R>): Promise<R[]>;
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>(client: BaseClient<any>, table: string): Repository<T>;
createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
}
export declare class RestRespositoryFactory implements RepositoryFactory {
createRepository<T>(client: BaseClient<any>, table: string): Repository<T>;
createRepository<T extends XataRecord>(client: BaseClient<any>, table: string): Repository<T>;
}

@@ -119,3 +45,3 @@ declare type BranchStrategyValue = string | undefined | null;

fetch?: unknown;
databaseURL: string;
databaseURL?: string;
branch: BranchStrategyOption;

@@ -139,2 +65,2 @@ apiKey: string;

export declare type Links = Record<string, Array<string[]>>;
export {};
export * from './schema/operators';
"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) {

@@ -11,2 +21,13 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
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) {

@@ -19,147 +40,11 @@ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");

};
var _RestRepository_client, _RestRepository_fetch, _RestRepository_table;
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 gt = (value) => ({ $gt: value });
exports.gt = gt;
const ge = (value) => ({ $ge: value });
exports.ge = ge;
const gte = (value) => ({ $ge: value });
exports.gte = gte;
const lt = (value) => ({ $lt: value });
exports.lt = lt;
const lte = (value) => ({ $le: value });
exports.lte = lte;
const le = (value) => ({ $le: value });
exports.le = le;
const exists = (column) => ({ $exists: column });
exports.exists = exists;
const notExists = (column) => ({ $notExists: column });
exports.notExists = notExists;
const startsWith = (value) => ({ $startsWith: value });
exports.startsWith = startsWith;
const endsWith = (value) => ({ $endsWith: value });
exports.endsWith = endsWith;
const pattern = (value) => ({ $pattern: value });
exports.pattern = pattern;
const is = (value) => ({ $is: value });
exports.is = is;
const isNot = (value) => ({ $isNot: value });
exports.isNot = isNot;
const contains = (value) => ({ $contains: value });
exports.contains = contains;
// TODO: these can only be applied to columns of type "multiple"
const includes = (value) => ({ $includes: value });
exports.includes = includes;
const includesSubstring = (value) => ({ $includesSubstring: value });
exports.includesSubstring = includesSubstring;
const includesPattern = (value) => ({ $includesPattern: value });
exports.includesPattern = includesPattern;
const includesAll = (value) => ({ $includesAll: value });
exports.includesAll = includesAll;
class Query {
constructor(repository, table, data, parent) {
if (repository) {
this.repository = repository;
}
else {
this.repository = this;
}
this.table = table;
// For some reason Object.assign(this, parent) didn't work in this case
// so doing all this manually:
this.$any = parent === null || parent === void 0 ? void 0 : parent.$any;
this.$all = parent === null || parent === void 0 ? void 0 : parent.$all;
this.$not = parent === null || parent === void 0 ? void 0 : parent.$not;
this.$none = parent === null || parent === void 0 ? void 0 : parent.$none;
this.$sort = parent === null || parent === void 0 ? void 0 : parent.$sort;
Object.assign(this, data);
// These bindings are used to support deconstructing
// const { any, not, filter, sort } = xata.users.query()
this.any = this.any.bind(this);
this.all = this.all.bind(this);
this.not = this.not.bind(this);
this.filter = this.filter.bind(this);
this.sort = this.sort.bind(this);
this.none = this.none.bind(this);
Object.defineProperty(this, 'table', { enumerable: false });
Object.defineProperty(this, 'repository', { enumerable: false });
}
any(...queries) {
return new Query(this.repository, this.table, {
$any: (this.$any || []).concat(queries)
}, this);
}
all(...queries) {
return new Query(this.repository, this.table, {
$all: (this.$all || []).concat(queries)
}, this);
}
not(...queries) {
return new Query(this.repository, this.table, {
$not: (this.$not || []).concat(queries)
}, this);
}
none(...queries) {
return new Query(this.repository, this.table, {
$none: (this.$none || []).concat(queries)
}, this);
}
filter(a, b) {
if (arguments.length === 1) {
const constraints = a;
const queries = [];
for (const [column, constraint] of Object.entries(constraints)) {
queries.push({ [column]: constraint });
}
return new Query(this.repository, this.table, {
$all: (this.$all || []).concat(queries)
}, this);
}
else {
const column = a;
const value = b;
return new Query(this.repository, this.table, {
$all: (this.$all || []).concat({ [column]: value })
}, this);
}
}
sort(column, direction) {
const sort = Object.assign(Object.assign({}, this.$sort), { [column]: direction });
const q = new Query(this.repository, this.table, {
$sort: sort
}, this);
return q;
}
// TODO: pagination. Maybe implement different methods for different type of paginations
// and one to simply get the first records returned by the query with no pagination.
getMany(options) {
return __awaiter(this, void 0, void 0, function* () {
// TODO: use options
return this.repository.query(this);
});
}
getOne(options) {
return __awaiter(this, void 0, void 0, function* () {
// TODO: use options
const arr = yield this.getMany(); // TODO, limit to 1
return arr[0] || null;
});
}
deleteAll() {
return __awaiter(this, void 0, void 0, function* () {
// Return number of affected rows
return 0;
});
}
include(columns) {
// TODO
return this;
}
exports.XataError = exports.BaseClient = exports.RestRespositoryFactory = exports.RestRepository = exports.Repository = void 0;
const filters_1 = require("./schema/filters");
const pagination_1 = require("./schema/pagination");
const query_1 = require("./schema/query");
const errors_1 = require("./util/errors");
class Repository extends query_1.Query {
}
exports.Query = Query;
class Repository extends Query {
select(...columns) {
return new Query(this.repository, this.table, {});
}
}
exports.Repository = Repository;

@@ -169,32 +54,25 @@ class RestRepository extends Repository {

super(null, table, {});
this.client = client;
const { fetch } = client.options;
if (fetch) {
this.fetch = fetch;
_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");
const doWeHaveFetch = typeof fetch !== 'undefined';
const isInjectedFetchProblematic = !__classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch;
if (doWeHaveFetch) {
__classPrivateFieldSet(this, _RestRepository_fetch, fetch, "f");
}
else if (typeof window === 'object') {
this.fetch = window.fetch;
else if (isInjectedFetchProblematic) {
throw new Error(errors_1.errors.falsyFetchImplementation);
}
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');
}
}
else {
__classPrivateFieldSet(this, _RestRepository_fetch, __classPrivateFieldGet(this, _RestRepository_client, "f").options.fetch, "f");
}
Object.defineProperty(this, 'client', { enumerable: false });
Object.defineProperty(this, 'fetch', { enumerable: false });
Object.defineProperty(this, 'hostname', { 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}`, {
const { databaseURL, apiKey } = __classPrivateFieldGet(this, _RestRepository_client, "f").options;
const branch = yield __classPrivateFieldGet(this, _RestRepository_client, "f").getBranch();
const fetchImpl = __classPrivateFieldGet(this, _RestRepository_fetch, "f");
const resp = yield fetchImpl(`${databaseURL}:${branch}${path}`, {
method,

@@ -225,27 +103,42 @@ headers: {

if (resp.status === 204)
return;
return undefined;
return resp.json();
});
}
select(...columns) {
return new Query(this.repository, this.table, {});
}
create(object) {
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 record = transformObjectLinks(object);
const response = yield this.request('POST', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/data`, record);
if (!response) {
throw new Error("The server didn't return any data for the query");
}
const obj = yield this.request('POST', `/tables/${this.table}/data`, body);
return this.client.initObject(this.table, obj);
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 records = objects.map((object) => transformObjectLinks(object));
const response = yield this.request('POST', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/bulk`, { records });
if (!response) {
throw new Error("The server didn't return any data for the query");
}
// 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(id) {
return __awaiter(this, void 0, void 0, function* () {
try {
const obj = yield this.request('GET', `/tables/${this.table}/data/${id}`);
return this.client.initObject(this.table, obj);
const response = yield this.request('GET', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/data/${id}`);
if (!response)
return null;
return __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
}

@@ -261,4 +154,8 @@ catch (err) {

return __awaiter(this, void 0, void 0, function* () {
const obj = yield this.request('PUT', `/tables/${this.table}/data/${id}`, object);
return this.client.initObject(this.table, obj);
const response = yield this.request('PUT', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/data/${id}`, object);
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 __classPrivateFieldGet(this, _RestRepository_client, "f").initObject(__classPrivateFieldGet(this, _RestRepository_table, "f"), response);
});

@@ -268,19 +165,23 @@ }

return __awaiter(this, void 0, void 0, function* () {
yield this.request('DELETE', `/tables/${this.table}/data/${id}`);
yield this.request('DELETE', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/data/${id}`);
});
}
query(query) {
query(query, options) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
const filter = {
$any: query.$any,
$all: query.$all,
$not: query.$not,
$none: query.$none
};
const data = query.getData();
const body = {
filter: Object.values(filter).some(Boolean) ? filter : undefined,
sort: query.$sort
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 result = yield this.request('POST', `/tables/${this.table}/query`, body);
return result.records.map((record) => this.client.initObject(this.table, record));
const response = yield this.request('POST', `/tables/${__classPrivateFieldGet(this, _RestRepository_table, "f")}/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) => __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);
});

@@ -290,2 +191,3 @@ }

exports.RestRepository = RestRepository;
_RestRepository_client = new WeakMap(), _RestRepository_fetch = new WeakMap(), _RestRepository_table = new WeakMap();
class RestRespositoryFactory {

@@ -386,1 +288,11 @@ createRepository(client, table) {

};
// 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("./schema/operators"), exports);
{
"name": "@xata.io/client",
"version": "0.0.0-alpha.1d9104e",
"version": "0.0.0-alpha.216c136",
"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": "1d9104e153e3b5d54ad6a095f4f512bddf8057d8"
"gitHead": "216c1360e1eeb6ea696f05bbd64a0ba8638395aa"
}
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