UNPKG

@triplit/client

Version:
269 lines (268 loc) 14.4 kB
import { SyncEngine } from '../sync-engine.js'; import { ErrorCallback, ClientFetchOptions, InfiniteSubscription, PaginatedSubscription, SubscribeBackgroundOptions, SubscriptionOptions, SubscriptionSignalPayload, TokenRefreshOptions, OnSessionErrorCallback } from './types'; import { HttpClient } from '../http-client/http-client.js'; import { Logger } from '@triplit/logger'; import { DB as EntityDB, DBTransaction, EntityStoreWithOutbox, Models, DBSchema, WriteModel, CollectionNameFromModels, SchemaQuery, FetchResult, ClearOptions, SubscriptionResultsCallback, UpdatePayload } from '@triplit/db'; import { ClientOptions, ClientTransactOptions, ConnectionOptionsChangeHandler } from './types/client.js'; /** * Friendly alias for Models type. */ export type ClientSchema = Models; export declare class TriplitClient<M extends Models<M> = Models> { awaitReady: Promise<void> | null; db: EntityDB<M, EntityStoreWithOutbox>; /** * The sync engine is responsible for managing the connection to the server and syncing data */ syncEngine: SyncEngine; private _token; private claimsPath; private _serverUrl; private readonly skipRules; private statusSubs; readonly syncSchema: boolean; http: HttpClient<M>; private defaultFetchOptions; logger: Logger; /** * A small bit of state that tracks if we plan to connect (async) on client construction * Once the connection has been attempted, this will be set to false */ private connectOnInitialization; decodedToken: Record<string, any> | undefined; /** * * @param options - The {@link ClientOptions | options} for the client */ constructor(options?: ClientOptions<M>); get ready(): Promise<void>; /** * Gets the schema of the database * * @returns The schema of the database as a Javascript object */ getSchema(): Promise<DBSchema<M> | undefined>; /** * Run a transaction with the client. * * @param callback - The callback to run within the transaction * @returns An object with the transaction ID and the output of the transaction */ transact<Output>(callback: (tx: DBTransaction<M>) => Promise<Output>, options?: Partial<ClientTransactOptions>): Promise<Output>; /** * Initializes a query builder for a collection. Chain methods such as `where`, `order`, `limit`, etc. to build a query. * * @param collectionName - The name of the collection to query * @returns A query builder for the collection */ query<CN extends CollectionNameFromModels<M>>(collectionName: CN): import("@triplit/db").QueryBuilder<M, CN, import("@triplit/db").WithInclusion<import("@triplit/db").CollectionQuery<M, CN>, {}>>; /** * Fetches data from the database. * * @param query - The query to fetch * @param options - The fetch options * @param options.policy - The fetch policy to use. Determines if the operation will retrieve data from the cache and/or the server. Defaults to `local-first`. * @returns The fetched data as a map of entities */ fetch<Q extends SchemaQuery<M>>(query: Q, options?: Partial<ClientFetchOptions>): Promise<FetchResult<M, Q, 'many'>>; private fetchLocal; /** * Fetches a single entity by its id from the database. * * @param collectionName - The name of the collection to fetch from * @param id - The id of the entity to fetch * @param options - The fetch options * @returns The fetched entity or null if it does not exist */ fetchById<CN extends CollectionNameFromModels<M>>(collectionName: CN, id: string, options?: Partial<ClientFetchOptions>): Promise<FetchResult<M, { collectionName: CN; }, 'one'>>; /** * Clears the local database of the client. Does not affect the server. * * @param options - The clear options * - `full`: If true, clears the entire database. If false, only clears your application data. Defaults to `false`. * @returns a promise that resolves when the database has been cleared */ clear(options?: ClearOptions): Promise<void>; reset(options?: ClearOptions): Promise<void>; /** * Fetches the first entity in the database that matches the query. * * @param query - The query to fetch * @param options - The fetch options * @returns The fetched entity or null if it does not exist */ fetchOne<Q extends SchemaQuery<M>>(query: Q, options?: Partial<ClientFetchOptions>): Promise<FetchResult<M, Q, 'one'>>; /** * Inserts an entity into the database. * * @param collectionName - The name of the collection to insert into * @param object - The entity to insert * @returns The transaction ID and the inserted entity, if successful */ insert<CN extends CollectionNameFromModels<M>>(collectionName: CN, object: WriteModel<M, CN>): Promise<import("@triplit/db").Unalias<import("@triplit/db").Decoded<M[CN]["schema"]>>>; /** * Updates an entity in the database. * * @param collectionName - The name of the collection to update * @param entityId - The id of the entity to update * @param updater - A function that provides the current entity and allows you to modify it * @returns The transaction ID */ update<CN extends CollectionNameFromModels<M>>(collectionName: CN, entityId: string, data: UpdatePayload<M, CN>): Promise<void>; /** * Deletes an entity from the database. * * @param collectionName - The name of the collection to delete from * @param entityId - The id of the entity to delete * @returns The transaction ID */ delete<CN extends CollectionNameFromModels<M>>(collectionName: CN, entityId: string): Promise<void>; entityIsInCache(collection: string, entityId: string): Promise<boolean>; /** * Subscribes to a client query and receives the results asynchronously. * * @param query - The client query to subscribe to. * @param onResults - The callback function to handle the results of the subscription. * @param onError - The callback function to handle any errors that occur during the subscription. * @param options - The options for the subscription. * @param options.localOnly - If true, the subscription will only use the local cache. Defaults to false. * @param options.onRemoteFulfilled - An optional callback that is called when the remote query has been fulfilled. * @returns - A function that can be called to unsubscribe from the subscription. */ subscribe<Q extends SchemaQuery<M>>(query: Q, onResults: SubscriptionResultsCallback<M, Q>, onError?: ErrorCallback, options?: Partial<SubscriptionOptions>): () => void; private get probablyIntendsToConnect(); subscribeWithStatus<Q extends SchemaQuery<M>>(query: Q, callback: (state: SubscriptionSignalPayload<M, Q>) => void, options?: Partial<SubscriptionOptions>): () => void; private _subscribeWithStatus; private filterResultsWithSyncStatus; /** * Syncs a query to your local database in the background. This is useful to pre-fetch a larger portion of data and used in combination with local-only subscriptions. */ subscribeBackground<Q extends SchemaQuery<M>>(query: Q, options?: SubscribeBackgroundOptions): () => void; /** * Subscribe to a query with helpers for pagination * This query will "oversubscribe" by 1 on either side of the current page to determine if there are "next" or "previous" pages * The window generally looks like [buffer, ...page..., buffer] * Depending on the current paging direction, the query may have its original order reversed * * The pagination will also do its best to always return full pages * @param query - The query, which should have a `limit`, to subscribe to. * @param onResults - The callback function to handle the results of the subscription. * @param onError - The callback function to handle any errors that occur during the subscription. * @param options - The options for the subscription. * @returns An object containing functions that can be called to unsubscribe from the subscription and query the previous and next pages. */ subscribeWithPagination<Q extends SchemaQuery<M>>(query: Q, onResults: (results: FetchResult<M, Q, 'many'>, info: { hasNextPage: boolean; hasPreviousPage: boolean; }) => void | Promise<void>, onError?: (error: any) => void | Promise<void>, options?: Partial<SubscriptionOptions>): PaginatedSubscription; /** * Subscribes to a client query with the ability to expand size of the results. * * @param query - The query, which should have a `limit` set, to subscribe to. * @param onResults - The callback function to handle the query results. * @param onError - The callback function to handle any errors that occur during the subscription. * @param options - The options for the subscription. * @returns An object containing functions to load more data and to unsubscribe from the subscription. */ subscribeWithExpand<Q extends SchemaQuery<M>>(query: Q, onResults: (results: FetchResult<M, Q, 'many'>, info: { hasMore: boolean; }) => void | Promise<void>, onError?: (error: any) => void | Promise<void>, options?: Partial<SubscriptionOptions>): InfiniteSubscription; /** * Updates the `token` or `serverUrl` of the client and will inform subscribers. Only will fire to subscribers if the value(s) have changed. * * @param options - The options to update the client with */ private updateConnectionOptions; /** * Starts a new sync session with the provided token * * @param token - The token to start the session with * @param connect - If true, the client will automatically connect to the server after starting the session. Defaults to true. * @param refreshOptions - Options for refreshing the token * @param refreshOptions.interval - The interval in milliseconds to refresh the token. If not provided, the token will be refreshed 500ms before it expires. * @param refreshOptions.handler - The function to call to refresh the token. It returns a promise that resolves with the new token. */ startSession(token: string | undefined, connect?: boolean, refreshOptions?: TokenRefreshOptions): Promise<(() => void) | undefined>; /** * Disconnects the client from the server and ends the current sync session. */ endSession(): Promise<void>; /** * Attempts to update the token of the current session, which re-use the current connection. If the new token does not have the same roles as the current session, an error will be thrown. */ updateSessionToken(token: string): Promise<void>; onSessionError(callback: OnSessionErrorCallback): () => void; updateGlobalVariables(vars: Record<string, any>): Promise<void>; /** * Updates the `token` of the client. This will cause the client to close its current connection to the server and attempt reopen a new one with the provided token. * * @param token */ private updateToken; /** * Updates the `serverUrl` of the client. This will cause the client to close its current connection to the server and attempt reopen a new one with the provided server URL. * * @param serverUrl */ updateServerUrl(serverUrl: string | undefined): void; /** * Sets up a listener for connection status changes * @param callback A callback that will be called when the connection status changes * @param runImmediately Run the callback immediately with the current connection status * @returns A function that removes the callback from the connection status change listeners */ onConnectionStatusChange(...args: Parameters<typeof this.syncEngine.onConnectionStatusChange>): () => void; /** * Attempts to connect the client to the server. This will start the client syncing data with the server. */ connect(): Promise<void>; /** * Disconnects the client from the server. This will stop the client from syncing data with the server. */ disconnect(): void; /** * Sends a ping message to the server. */ ping(): void; /** * The token used to authenticate with the server */ get token(): string | undefined; get serverUrl(): string | undefined; get vars(): { $token: Record<string, any>; $global: Record<string, any>; $session: Record<string, any>; }; onSyncMessageReceived(...args: Parameters<typeof this.syncEngine.onSyncMessageReceived>): () => void; onSyncMessageSent(...args: Parameters<typeof this.syncEngine.onSyncMessageSent>): () => void; onEntitySyncSuccess(...args: Parameters<typeof this.syncEngine.onEntitySyncSuccess>): () => void; onEntitySyncError(...args: Parameters<typeof this.syncEngine.onEntitySyncError>): () => void; onFailureToSyncWrites(...args: Parameters<typeof this.syncEngine.onFailureToSyncWrites>): () => void; /** * Manually send any pending writes to the remote database. This may be a no-op if: * - there is already a push in progress * - the connection is not open * * If the push is successful, it will return `success: true`. If the push fails, it will return `success: false` and a `failureReason`. */ syncWrites(...args: Parameters<typeof this.syncEngine.syncWrites>): Promise<{ didSync: boolean; syncFailureReason?: string; }>; /** * The connection status of the client with the server */ get connectionStatus(): import("../types.js").ConnectionStatus; isFirstTimeFetchingQuery(...args: Parameters<typeof this.syncEngine.isFirstTimeFetchingQuery>): Promise<boolean>; clearPendingChangesForEntity(...args: Parameters<typeof this.syncEngine.clearPendingChangesForEntity>): Promise<{ didSync: boolean; syncFailureReason?: string; }>; clearPendingChangesAll(...args: Parameters<typeof this.syncEngine.clearPendingChangesAll>): Promise<void>; private connectionOptionsChangeHandlers; onConnectionOptionsChange(callback: ConnectionOptionsChangeHandler): () => void; private warnError; }