@rushdb/javascript-sdk
Version:
RushDB Javascript SDK
423 lines (422 loc) • 21.1 kB
TypeScript
import type { HttpClient } from '../network/HttpClient.js';
import type { DBRecordCreationOptions, DBRecordTarget, Relation, RelationDetachOptions, RelationDirection, RelationOptions, RelationTarget } from '../sdk/record.js';
import { DBRecordInstance, DBRecordsArrayInstance } from '../sdk/record.js';
import type { SDKConfig } from '../sdk/types.js';
import type { FlatObject, InferSchemaTypesWrite, MaybeArray, OrderDirection, Property, PropertyDraft, PropertyValuesData, Schema, SearchQuery, Where } from '../types/index.js';
import type { ApiResponse } from './types.js';
import { createFetcher } from '../network/index.js';
import { Transaction } from '../sdk/transaction.js';
export declare class RestAPI {
fetcher: ReturnType<typeof createFetcher>;
options: SDKConfig['options'];
logger: SDKConfig['logger'];
constructor(token?: string, config?: SDKConfig & {
httpClient: HttpClient;
});
_extractTargetIds(target: RelationTarget, operation: string): Array<string>;
/**
* API methods for managing database records
*/
records: {
/**
* Attaches a relation between records
* @param source - The source record to create relation from
* @param target - The target record(s) to create relation to
* @param options - Optional relation configuration
* @param options.type - The type of relation to create
* @param options.direction - The direction of the relation
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response
*/
attach: ({ source, target, options }: {
source: DBRecordTarget;
target: RelationTarget;
options?: RelationOptions;
}, transaction?: Transaction | string) => Promise<ApiResponse<{
message: string;
}>>;
/**
* Detaches (removes) a relation between records
* @param source - The source record to remove relation from
* @param target - The target record(s) to remove relation to
* @param options - Optional detach configuration
* @param options.typeOrTypes - The type(s) of relations to remove
* @param options.direction - The direction of relations to remove
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response
*/
detach: ({ source, target, options }: {
source: DBRecordTarget;
target: RelationTarget;
options?: RelationDetachOptions;
}, transaction?: Transaction | string) => Promise<ApiResponse<{
message: string;
}>>;
/**
* Creates a new record in the database
* @param label - The label/type of the record
* @param data - The record data, either as a flat object or array of property drafts
* @param options - Optional write configuration
* @param transaction - Optional transaction for atomic operations
* @returns Promise resolving to the created DBRecordInstance
* @throws Error if data is not a flat object and createMany should be used instead
*/
create: <S extends Schema = any>({ label, data: rawData, options }: {
label: string;
data: InferSchemaTypesWrite<S> | Array<PropertyDraft>;
options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType">;
}, transaction?: Transaction | string) => Promise<DBRecordInstance<S>>;
/**
* Creates multiple flat records in a single operation.
* Use this only for CSV-like flat rows (no nested objects/arrays).
* For nested/complex JSON, use `records.importJson`.
*
* @param data - Object containing label, options and data array (of flat objects)
* @param data.label - The label/type for all records
* @param data.options - Optional write configuration
* @param data.data - Array of flat record data to create
* @param transaction - Optional transaction for atomic operations
* @returns Promise resolving to DBRecordsArrayInstance containing created records
* @throws Error if any record is not flat. Use `records.importJson` for nested JSON.
*/
createMany: <S extends Schema = any>(data: {
label: string;
data: Array<InferSchemaTypesWrite<S>>;
options?: DBRecordCreationOptions;
}, transaction?: Transaction | string) => Promise<DBRecordsArrayInstance<S>>;
/**
* Import nested or complex JSON payloads.
* Works in two modes:
* - With `label` provided
* - Without `label`: expects an object with a single top-level key used as the label, e.g. { ITEM: [...] }
*
* Throws if `label` is missing and the input does not conform to the single-key rule
* (e.g. { some: 'key', data: 1, nested: { level: 2 } }).
*
* @example
* // with label
* await db.records.importJson({ label: 'ITEM', data: [{...}, {...}] })
* // without label
* await db.records.importJson({ data: { ITEM: [{...}, {...}] } })
*/
importJson: <S extends Schema = any>(params: {
data: any;
label?: string;
options?: DBRecordCreationOptions;
}, transaction?: Transaction | string) => Promise<DBRecordsArrayInstance<S>>;
/**
* Imports records from CSV data.
* @param params - CSV import configuration
* @param params.label - Label applied to imported records
* @param params.data - Raw CSV string
* @param params.options - Import options (type inference etc.)
* @param params.parseConfig - CSV parsing configuration (subset allowed by server)
* @param params.parentId - Optional parent record id for hierarchical imports
*/
importCsv: <S extends Schema = any>(params: {
label: string;
data: string;
options?: DBRecordCreationOptions;
parseConfig?: {
delimiter?: string;
header?: boolean;
skipEmptyLines?: boolean | "greedy";
dynamicTyping?: boolean;
quoteChar?: string;
escapeChar?: string;
newline?: string;
};
parentId?: string;
}, transaction?: Transaction | string) => Promise<DBRecordsArrayInstance<S>>;
/**
* Deletes records matching the search query
* @param searchQuery - Query to identify records to delete
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response
* @throws EmptyTargetError if query is empty and force delete is not allowed
*/
delete: <S extends Schema = any>(searchQuery: SearchQuery<S>, transaction?: Transaction | string) => Promise<ApiResponse<{
message: string;
}>>;
/**
* Deletes record(s) by ID
* @param idOrIds - Single ID or array of IDs to delete
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response
*/
deleteById: (idOrIds: MaybeArray<string>, transaction?: Transaction | string) => Promise<ApiResponse<{
message: string;
}>>;
/**
* Exports records matching the search query to CSV format
* @param searchQuery - Query to identify records to export
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response containing CSV data
*/
export: <S extends Schema = any>(searchQuery: SearchQuery<S>, transaction?: Transaction | string) => Promise<ApiResponse<{
dateTime: string;
fileContent: string;
}>>;
/**
* Searches for records matching the query criteria
* @param searchQueryWithEntryPoint - Search query with optional entry point ID
* @param transaction - Optional transaction for atomic operations
* @returns Promise resolving to DBRecordsArrayInstance containing matched records
*/
find: <S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(searchQueryWithEntryPoint: Q & {
id?: string;
}, transaction?: Transaction | string) => Promise<DBRecordsArrayInstance<S, Q>>;
/**
* Retrieves record(s) by ID
* @param idOrIds - Single ID or array of IDs to retrieve
* @param transaction - Optional transaction for atomic operations
* @returns Promise resolving to DBRecordInstance or DBRecordsArrayInstance depending on input
*/
findById: <S extends Schema = Schema, Arg extends MaybeArray<string> = MaybeArray<string>, Result = Arg extends string[] ? DBRecordsArrayInstance<S, SearchQuery<S>> : DBRecordInstance<S, SearchQuery<S>>>(idOrIds: Arg, transaction?: Transaction | string) => Promise<Result>;
/**
* Finds a single record matching the search query
* @param searchQuery - Query to identify the record
* @param transaction - Optional transaction for atomic operations
* @returns Promise resolving to DBRecordInstance
*/
findOne: <S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(searchQuery: Q, transaction?: Transaction | string) => Promise<DBRecordInstance<S>>;
/**
* Finds a unique record matching the search query
* @param searchQuery - Query to identify the record
* @param transaction - Optional transaction for atomic operations
* @returns Promise resolving to DBRecordInstance
* @throws NonUniqueResultError if multiple records match the query
*/
findUniq: <S extends Schema = any, Q extends SearchQuery<S> = SearchQuery<S>>(searchQuery: Q, transaction?: Transaction | string) => Promise<DBRecordInstance<S, Q>>;
/**
* Sets (overwrites) record data
* @param target - The record to update
* @param label - The label/type of the record
* @param data - The new record data
* @param options - Optional write configuration
* @param transaction - Optional transaction for atomic operations
* @returns Promise resolving to updated DBRecordInstance
* @throws Error if data is not a flat object
*/
set: <S extends Schema = any>({ target, label, data: rawData, options }: {
target: DBRecordTarget;
label: string;
data: InferSchemaTypesWrite<S> | Array<PropertyDraft>;
options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType">;
}, transaction?: Transaction | string) => Promise<DBRecordInstance<S, SearchQuery<S>>>;
/**
* Updates record data (partial update)
* @param target - The record to update
* @param label - The label/type of the record
* @param data - The partial record data to update
* @param options - Optional write configuration
* @param transaction - Optional transaction for atomic operations
* @returns Promise resolving to updated DBRecordInstance
* @throws Error if data is not a flat object
*/
update: <S extends Schema = any>({ target, label, data: rawData, options }: {
target: DBRecordTarget;
label: string;
data: Partial<InferSchemaTypesWrite<S>> | Array<PropertyDraft>;
options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType">;
}, transaction?: Transaction | string) => Promise<DBRecordInstance<S, SearchQuery<S>>>;
/**
* Upserts a record: attempts to find an existing record matching mergeBy property values (and optional label)
* If found: mergeStrategy determines behavior.
* - 'rewrite': replaces all existing own properties with incoming (like set)
* - 'append': updates/adds provided properties, keeps others
* If not found: creates a new record.
* @param label - The label/type of the record
* @param data - Flat object or array of property drafts
* @param options.mergeBy - Property names to match on; If `[]`, all incoming keys are used for matching.
* @param options.mergeStrategy - 'rewrite' | 'append'
* @param transaction - Optional transaction for atomic operations
*/
upsert: <S extends Schema = any>({ label, data: rawData, options }: {
label?: string;
data: InferSchemaTypesWrite<S> | Array<PropertyDraft>;
options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType"> & {
mergeBy?: string[];
mergeStrategy?: "rewrite" | "append";
};
}, transaction?: Transaction | string) => Promise<DBRecordInstance<S>>;
};
/**
* API methods for managing relations between records
*/
relationships: {
/**
* Creates many relationships by matching source and target records by keys
* @param data - Configuration of source/target match and relation details
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response message
*/
createMany: (data: {
source: {
label: string;
key?: string;
where?: Where;
};
target: {
label: string;
key?: string;
where?: Where;
};
type?: string;
direction?: RelationDirection;
manyToMany?: boolean;
}, transaction?: Transaction | string) => Promise<ApiResponse<{
message: string;
}>>;
/**
* Deletes many relationships by matching source and target records by keys or by manyToMany filter
*/
deleteMany: (data: {
source: {
label: string;
key?: string;
where?: Where;
};
target: {
label: string;
key?: string;
where?: Where;
};
type?: string;
direction?: RelationDirection;
manyToMany?: boolean;
}, transaction?: Transaction | string) => Promise<ApiResponse<{
message: string;
}>>;
/**
* Searches for relations matching the query criteria
* @param searchQuery - Query to identify relations
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response containing matched relations
*/
find: <S extends Schema = any>(searchQuery: SearchQuery<S>, transaction?: Transaction | string) => Promise<ApiResponse<Relation[]>>;
};
/**
* API methods for managing properties in the database
*/
properties: {
/**
* Deletes a property by its ID
* @param id - The unique identifier of the property to delete
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response containing the deleted property
*/
delete: (id: string, transaction?: Transaction | string) => Promise<ApiResponse<Property>>;
/**
* Searches for properties based on the provided query
* @param searchQuery - Query parameters to filter properties
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response containing an array of matching properties
*/
find: <S extends Schema = any>(searchQuery: SearchQuery<S>, transaction?: Transaction | string) => Promise<ApiResponse<Property[]>>;
/**
* Retrieves a specific property by its ID
* @param id - The unique identifier of the property to retrieve
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response containing the requested property
*/
findById: (id: string, transaction?: Transaction | string) => Promise<ApiResponse<Property>>;
/**
* Retrieves values for a specific property
* @param id - The unique identifier of the property
* @param searchQuery - Query parameters to filter properties
* @param searchQuery.query - Filter query for values
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response containing the property and its values
*/
values: (id: string, searchQuery?: SearchQuery & {
query?: string;
orderBy?: OrderDirection;
}, transaction?: Transaction | string) => Promise<ApiResponse<{
metadata?: string;
name: string;
type: import("../types/value.js").PropertyType;
} & {
id: string;
} & PropertyValuesData>>;
};
/**
* API methods for managing labels in the database
*/
labels: {
/**
* Searches for labels based on the provided query
* @param searchQuery - Query parameters to filter labels
* @param transaction - Optional transaction for atomic operations
* @returns Promise with the API response containing a record of label names and their counts
*/
find: <S extends Schema = any>(searchQuery: SearchQuery<S>, transaction?: Transaction | string) => Promise<ApiResponse<Record<string, number>>>;
};
/**
* API methods for managing database transactions
*/
tx: {
/**
* Begins a new database transaction
* @param config - Optional configuration object for the transaction
* @param config.ttl - Time-to-live in milliseconds for the transaction
* @returns A new Transaction instance that can be used for subsequent operations
* @throws If the transaction cannot be started
*/
begin: (config?: Partial<{
ttl: number;
}>) => Promise<Transaction>;
/**
* Commits a transaction, making its changes permanent
* @param tx - The ID of the transaction or Transaction instance to commit
* @returns An ApiResponse indicating success or failure of the commit
* @throws If the transaction cannot be committed or doesn't exist
*/
commit: (tx: string | Transaction) => Promise<ApiResponse<{
message: string;
}>>;
/**
* Retrieves an existing transaction by its ID
* @param tx - The ID of the transaction or Transaction instance to retrieve
* @returns A Transaction instance representing the retrieved transaction
* @throws If the transaction doesn't exist or cannot be retrieved
*/
get: (tx: string | Transaction) => Promise<Transaction>;
/**
* Rolls back a transaction, undoing all changes made within it
* @param tx - The ID of the transaction or Transaction instance to roll back
* @returns An ApiResponse indicating success or failure of the rollback
* @throws If the transaction cannot be rolled back or doesn't exist
*/
rollback: (tx: string | Transaction) => Promise<ApiResponse<{
message: string;
}>>;
};
settings: {
get: () => Promise<ApiResponse<{
selfHosted: boolean;
customDB?: boolean;
managedDB?: boolean;
planType?: import("../sdk/types.js").PlanType;
} | undefined>>;
};
query: {
/**
* Runs a raw Cypher query against the connected Neo4j database.
*
* NOTE: This endpoint is cloud-only — available only on the RushDB managed
* service or when your project is connected to a custom database through
* RushDB Cloud. It will not work for self-hosted or local-only deployments.
*
* @param param0 - Object containing the Cypher query and optional params
* @param param0.query - Cypher query string to execute
* @param param0.params - Optional parameters to pass to the query
* @param transaction - Optional transaction id or Transaction instance to run the query in
* @returns ApiResponse<any> - Raw result returned by the server (Neo4j driver result wrapped in ApiResponse)
*/
raw: <T extends unknown = any>({ query, params }: {
query: string;
params?: FlatObject;
}, transaction?: Transaction | string) => Promise<ApiResponse<T>>;
};
}