helene
Version: 
Real-time Web Apps for Node.js
163 lines (162 loc) • 6.7 kB
TypeScript
import { EventEmitter2 } from 'eventemitter2';
import { Cursor, Projection, Query, SortQuery } from './cursor';
import { Index } from './indexes';
import { LastStepModifierFunctions } from './last-step-modifier-functions';
import { Persistence } from './persistence';
import { IStorage } from './types';
export declare const CollectionEvent: {
    READY: string;
    UPDATED: string;
    ERROR: string;
    COMPACTED: string;
};
export type HookFunction = <T = any>(doc: any) => Promise<void>;
export type TransformerHookFunction = <T = any>(doc: T) => Promise<T>;
export type UpdateHookFunction = <T = any>(newDoc: T, oldDoc: T) => Promise<void>;
export type UpdateTransformerHookFunction = <T = any>(newDoc: T, oldDoc: T) => Promise<T>;
export type CollectionOptions = {
    name?: string;
    timestamps?: boolean;
    autoload?: boolean;
    onload?: (err?: Error) => void;
    afterSerialization?: (doc: any) => any;
    beforeDeserialization?: (doc: any) => any;
    corruptAlertThreshold?: number;
    compareStrings?: (a: string, b: string) => number;
    storage?: IStorage;
    /**
     * The interval (in milliseconds) at which the datafile will be compacted. Minimum value is 5000 (5 seconds). Default is 60000 (1 minute).
     */
    compactionInterval?: number;
    beforeInsert?: TransformerHookFunction;
    afterInsert?: HookFunction;
    beforeUpdate?: UpdateTransformerHookFunction;
    afterUpdate?: UpdateHookFunction;
    beforeRemove?: HookFunction;
    afterRemove?: HookFunction;
};
export type UpdateQuery = Partial<{
    [key in keyof typeof LastStepModifierFunctions]: any;
}> & Record<string, any>;
export type UpdateOptions = {
    multi?: boolean;
    upsert?: boolean;
    returnUpdatedDocs?: boolean;
    [key: string]: any;
};
export type IndexOptions = {
    fieldName: string;
    unique?: boolean;
    sparse?: boolean;
    expireAfterSeconds?: number;
};
export type BaseDocument = {
    _id?: string | number;
    [key: string]: any;
};
export declare class Collection<CT extends BaseDocument = BaseDocument> extends EventEmitter2 {
    name: string | null;
    inMemoryOnly: boolean;
    autoload: boolean;
    timestampData: boolean;
    compareStrings: (a: string, b: string) => number;
    persistence: Persistence;
    indexes: Record<string, Index>;
    ttlIndexes: Record<string, any>;
    ready: boolean;
    beforeInsert: TransformerHookFunction;
    afterInsert: HookFunction;
    beforeUpdate: UpdateTransformerHookFunction;
    afterUpdate: UpdateHookFunction;
    beforeRemove: TransformerHookFunction;
    afterRemove: HookFunction;
    constructor({ name, storage, autoload, timestamps, compareStrings, corruptAlertThreshold, onload, afterSerialization, beforeDeserialization, compactionInterval, beforeInsert, afterInsert, beforeUpdate, afterUpdate, beforeRemove, afterRemove, }?: CollectionOptions);
    deferEmit(event: string, ...args: any[]): void;
    /**
     * Load the database from the datafile, and trigger the execution of buffered commands if any
     */
    loadDatabase(): Promise<any>;
    /**
     * Get an array of all the data in the database
     */
    getAllData(): any[];
    /**
     * Reset all currently defined indexes
     */
    resetIndexes(newData?: any[]): void;
    /**
     * Ensure an index is kept for this field. Same parameters as lib/indexes
     * For now this function is synchronous, we need to test how much time it takes
     * We use an async API for consistency with the rest of the code
     */
    ensureIndex(options: IndexOptions): Promise<any>;
    /**
     * Remove an index
     */
    removeIndex(fieldName: string): Promise<void>;
    /**
     * Add one or several document(s) to all indexes
     */
    addToIndexes(doc: CT): void;
    /**
     * Remove one or several document(s) from all indexes
     */
    removeFromIndexes(doc: CT): void;
    /**
     * Update one or several documents in all indexes
     * To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs
     * If one update violates a constraint, all changes are rolled back
     */
    updateIndexes(oldDoc: Record<string, any>, newDoc?: Record<string, any>): void;
    /**
     * Return the list of candidates for a given query
     * Crude implementation for now, we return the candidates given by the first usable index if any
     * We try the following query types, in this order: basic match, $in match, comparison match
     * One way to make it better would be to enable the use of multiple indexes if the first usable index
     * returns too much data. I may do it in the future.
     *
     * Returned candidates will be scanned to find and remove all expired documents
     *
     * @param {Query} query
     * @param {Boolean} dontExpireStaleDocs Optional, defaults to false, if true don't remove stale docs. Useful for the remove function which shouldn't be impacted by expirations
     */
    getCandidates(query: any, dontExpireStaleDocs?: boolean): Promise<any>;
    insert(newDoc: CT): Promise<CT>;
    /**
     * Create a new _id that's not already in use
     */
    createNewId(): string;
    /**
     * Prepare a document (or array of documents) to be inserted in a database
     * Meaning adds _id and timestamps if necessary on a copy of newDoc to avoid any side effect on user input
     * @api private
     */
    prepareDocumentForInsertion(newDoc: any): Promise<any>;
    /**
     * If newDoc is an array of documents, this will insert all documents in the cache
     * @api private
     */
    _insertInCache(preparedDoc: any): void;
    /**
     * If one insertion fails (e.g. because of a unique constraint), roll back all previous
     * inserts and throws the error
     * @api private
     */
    _insertMultipleDocsInCache(preparedDocs: any): void;
    ensureReady(): Promise<void>;
    count(query: Query): Promise<number>;
    find(query?: Query, projection?: Projection): Cursor<CT>;
    findOne(query: Query, projection?: Projection, sort?: SortQuery): Promise<CT>;
    update(query: Query, updateQuery: UpdateQuery, options?: UpdateOptions): Promise<any>;
    updateOne(query: Query, updateQuery: UpdateQuery, options?: Omit<UpdateOptions, 'multi'>): Promise<any>;
    updateMany(query: Query, updateQuery: UpdateQuery, options?: Omit<UpdateOptions, 'multi'>): Promise<any>;
    remove(query: Query, options?: {
        multi?: boolean;
    }): Promise<number>;
    deleteOne(query: Query): Promise<number>;
    deleteMany(query: Query): Promise<number>;
}
/**
 * Creates a new collection and waits until it is ready.
 */
export declare function createCollection<CT extends BaseDocument = BaseDocument>(options: CollectionOptions): Promise<Collection<CT>>;