UNPKG

@squidcloud/client

Version:

A typescript implementation of the Squid client

321 lines (320 loc) 15 kB
import { AdminClient } from './admin-client'; import { AiClient } from './ai-client'; import { ApiClient } from './api-client'; import { CollectionReference } from './collection-reference'; import { ConnectionDetails } from './connection-details'; import { DistributedLock } from './distributed-lock.manager'; import { ExecuteFunctionOptions } from './execute-function-options'; import { ExtractionClient } from './extraction-client'; import { JobClient } from './job-client'; import { NotificationClient } from './notification-client'; import { ObservabilityClient } from './observability-client'; import { PersonalStorageClient } from './personal-storage-client'; import { ApiKey, AppId, CollectionName, DocumentData, EnvironmentId, IntegrationId, SquidDeveloperId, SquidRegion } from './public-types'; import { QueueManager } from './queue.manager'; import { SchedulerClient } from './scheduler-client'; import { StorageClient } from './storage-client'; import { TransactionId } from './types'; import { WebClient } from './web-client'; /** * The different options that can be used to initialize a Squid instance. * @category Platform */ export interface SquidOptions { /** * A function that can be used to wrap messages coming from Squid to the application. This is useful for * different frameworks that need to wrap messages in order to detect changes (like Angular). * @param fn The function to wrap. */ messageNotificationWrapper?: (fn: () => any) => any; /** * The application ID that is used to identify the application in Squid. The ID can be found in the Squid Cloud * Console. */ appId: AppId; /** * The application API key, using the API key can be used to bypass security rules and other restrictions. * The API key can be found in the Squid Console. */ apiKey?: ApiKey; /** * Access token provider for the Squid instance. * Used for managing the process of verifying the identity and authorization of users who attempt to access this * application via the current Squid instance. * * When the authProvider is set, the Squid service will fetch a token and include it with every request to the Squid * backend. * * On the backend, Squid will validate the access token. */ authProvider?: SquidAuthProvider; /** * The region that the application is running in. This is used to determine the URL of the Squid API. */ region: SquidRegion; /** * The environment ID to work with, if not specified the default environment (prod) will be used. */ environmentId?: EnvironmentId; /** * The user ID of the developer that runs the environment locally. */ squidDeveloperId?: SquidDeveloperId; /** * The console region (optional and used for on-prem deployments of Squid) */ consoleRegion?: string; } /** * Authentication data provider for Squid requests. * @category Authentication */ export interface SquidAuthProvider { /** * Optional Auth integration id. * Sent as a part of all Squid requests to the backend. */ integrationId: string; /** * Returns a valid AccessToken or undefined if there is no active authorized session. * Called by Squid every time a Squid client makes requests to the Squid backend. */ getToken(): Promise<string | undefined> | string | undefined; } /** * The main entry point to the Squid Client SDK. * * The Squid class provides a comprehensive array of functionality for accessing the different integrations, executing * backend functions, managing data, and more. Upon instantiating the Squid class, you will have access to all of these * capabilities. * All public Squid functions are bound to `this` and can be used with a destructuring patterns, * like `const {setAuthProvider} = useSquid()` * * @category Platform */ export declare class Squid { readonly options: SquidOptions; private static readonly squidInstancesMap; private readonly socketManager; private readonly dataManager; private readonly documentReferenceFactory; private readonly documentStore; private readonly lockManager; private readonly querySubscriptionManager; private readonly localQueryManager; private readonly queryBuilderFactory; private readonly collectionReferenceFactory; private readonly backendFunctionManager; private readonly nativeQueryManager; private readonly destructManager; private readonly documentIdentityService; private readonly distributedLockManager; private readonly authManager; private readonly clientIdService; private readonly _connectionDetails; private readonly querySender; private readonly aiClient; private readonly jobClient; private readonly apiClient; private readonly adminClient; private readonly webClient; private readonly observabilityClient; private readonly queueManagerFactory; private readonly schedulerClient; private readonly notificationClient; private readonly _appId; /** * Creates a new instance of Squid with the given options. * * @param options The options for initializing the Squid instance. */ constructor(options: SquidOptions); /** * Returns the observability client for metrics. */ get observability(): ObservabilityClient; /** * Returns the scheduler client for managing scheduled jobs and tasks. */ get schedulers(): SchedulerClient; /** * Returns the application ID of the current Squid instance. */ get appId(): AppId; /** * Returns the global Squid instance with the given options, creating a new instance if one with the same options * does not exist. * * @param options The options for initializing the Squid instance. * @returns A global Squid instance with the given options. */ static getInstance(options: SquidOptions): Squid; /** * Returns all the global Squid instances. * * @returns An array of all the global Squid instances. */ static getInstances(): Array<Squid>; /** * Sets the authorization access token (OAuth2.0) provider that will be sent to the server and will be used for * providing the `auth` object to the security rules. * * @param authProvider The OAuth2.0 access token provider invoked for every backend request by Squid. * When the provider returns undefined, no authorization information is sent. * When a new provider is set, all future Squid backend requests will use the new token provider, and exising * in-flight requests won't be affected. * @returns void. */ setAuthProvider(authProvider: SquidAuthProvider): void; /** * Returns a reference to the collection in the provided integration. * * If the integrationId is not provided, the `built_in_db` integration id will be used. * * For more information on the CollectionReference object, please refer to the * {@link https://docs.getsquid.ai/docs/sdk/client-sdk/database/collection-reference documentation}. * * @param collectionName The name of the collection. * @param integrationId The id of the integration, default to `built_in_db`. * @returns A reference to the collection in the provided integration. * @typeParam T The type of the documents in the collection. */ collection<T extends DocumentData>(collectionName: CollectionName, integrationId?: IntegrationId): CollectionReference<T>; /** * Runs the given callback as an atomic change. All the mutations that are executed using the provided transactionId * will be atomic. Note that mutations for different integrations will not be atomic. * * For more information about transactions in Squid, please refer to the * {@link https://docs.getsquid.ai/docs/sdk/client-sdk/database/transactions documentation}. * * @param fn The callback to run as an atomic change. The function receives a transactionId that should be used for * all the mutations that should be atomic. The function should return a promise. * * @returns A promise that resolves when the transactions are committed on the server. */ runInTransaction<T = any>(fn: (transactionId: TransactionId) => Promise<T>): Promise<T>; /** * Executes a backend function identified by its name, passing the provided parameters, and returns a promise with * the result. * * For detailed information on backend functions in Squid, see the * {@link https://docs.getsquid.ai/docs/sdk/backend-sdk/executables documentation}. * * Files support: * - To send a file to the backend, simply include it as one of the parameters; it will be received as a `SquidFile` * on the backend. * - Arrays of files can also be passed directly as parameters. * * @param functionNameOrOptions - The name of the backend function to execute or detailed options which include * additional advanced options along with the function name. * @param params - A list of parameters to pass to the backend function. * @returns A promise that resolves to the result of the backend function. * @typeParam T - The expected type of the result returned by the backend function. */ executeFunction<T = any>(functionNameOrOptions: string | ExecuteFunctionOptions<T>, ...params: Array<any | File>): Promise<T>; /** * Executes a native relational query with the given parameters and returns a promise with the result. * See https://docs.getsquid.ai/docs/sdk/client-sdk/database/native-queries. * * @param integrationId The id of the integration that the query is associated with. * @param query The raw SQL or database-specific query string to execute. Use named bind variables enclosed in ${}, * e.g., ${firstName}. * @param params (Optional) An object containing key-value pairs to bind to the query variables. Defaults to an empty * object. * @returns A promise that resolves with the result of the query. */ executeNativeRelationalQuery<T = any>(integrationId: IntegrationId, query: string, params?: Record<string, any>): Promise<Array<T>>; /** * Executes a native Mongo/built-in-db query with the given pipeline and returns a promise with the result. * See https://docs.getsquid.ai/docs/sdk/client-sdk/database/native-queries#native-mongodb-queries. * * @param integrationId The id of the integration that the query is associated with. * @param collectionName The collection to query. * @param aggregationPipeline The aggregation pipeline for the query. * @returns A promise that resolves with the result of the query. */ executeNativeMongoQuery<T = any>(integrationId: IntegrationId, collectionName: string, aggregationPipeline: Array<any | undefined>): Promise<Array<T>>; /** * Executes a native Elasticsearch query against the given index and endpoint. * See https://docs.getsquid.ai/docs/sdk/client-sdk/database/native-queries. * * @param integrationId The id of the integration that the query is associated with. * @param index The Elasticsearch index to query. * @param body The raw request body to send (must be a valid ES query DSL object). * @param endpoint The Elasticsearch endpoint to call (default: "_search"). * @param method The HTTP method to use (default: "GET"). * @returns A promise that resolves with the result array. */ executeNativeElasticQuery<T = any>(integrationId: IntegrationId, index: string, body: Record<string, any>, endpoint?: string, method?: 'GET' | 'POST'): Promise<Array<T>>; /** * Returns a set of AI specific clients. */ ai(): AiClient; /** * Returns a set of functionality for interacting with jobs. */ job(): JobClient; /** * Returns a set of functionality for interacting with API integrations. */ api(): ApiClient; /** * Returns the AdminClient instance for performing administrative operations. */ admin(): AdminClient; /** * Returns a set of functionality for interacting with the web. */ web(): WebClient; /** * Returns a client for accessing file storage for the current app. * Defaults to the built-in storage integration if none is provided. * * @param integrationId The storage integration ID (default is 'built_in_storage'). */ storage(integrationId?: IntegrationId): StorageClient; /** * Returns a client for accessing personal (user-specific) file storage. * * @param integrationId The storage integration ID to use. */ personalStorage(integrationId: IntegrationId): PersonalStorageClient; /** * Returns a client for working with structured data extraction tools. */ extraction(): ExtractionClient; /** * Returns a distributed lock for the given mutex. The lock can be used to synchronize access to a shared resource. * The lock will be released when the release method on the returned object is invoked or whenever the connection * with the server is lost. * @param mutex A string that uniquely identifies the lock. * @returns A promise that resolves with the lock object. The promise will reject if failed to acquire the lock. */ acquireLock(mutex: string): Promise<DistributedLock>; /** * Executes the given callback while holding a lock for the given mutex. The lock will be released when the callback * finishes. * @param mutex A string that uniquely identifies the lock. * @param fn The callback to execute while holding the lock. * @returns A promise that resolves with the result of the callback. The promise will reject if failed * to acquire the lock. */ withLock<T>(mutex: string, fn: (lock: DistributedLock) => Promise<T>): Promise<T>; /** * Returns a queue manager for the given topic name and integration id. Using the queue manager you can consume and * produce messages */ queue<T>(topicName: string, integrationId?: IntegrationId): QueueManager<T>; /** * Destructs the Squid Client. Unsubscribes from all ongoing queries or requests, and clears the local data. * After invoking this method, the Squid client will not be usable. * * @returns A promise that resolves when the destruct process is complete. */ destruct(): Promise<void>; /** Provides information about the connection to the Squid Server. */ connectionDetails(): ConnectionDetails; /** Returns the notification client for handling (publishing and receiving) custom messages. */ getNotificationClient(): NotificationClient; private _validateNotDestructed; }