json-file-database
Version:
Lightweight Database on NodeJS by JSON Files
88 lines (87 loc) • 2.68 kB
TypeScript
/**
* The element will be used in collections.
*/
export declare type Element = object;
/**
* The condition to to compare elements.
* @template E the type of elements.
* @template I the type of id.
* @param el the element.
* @returns whether the element matches the condition.
*/
export declare type Condition<E extends Element> = (el: Readonly<E>) => boolean;
/**
* The comparator to compare two elements, the id won't be omitted.
* @param first the first id.
* @param second the second id.
* @returns the comparing result.
*/
export declare type Comparator<E extends Element> = (first: Partial<E>, second: Partial<E>) => number;
/**
* The function to save the collection.
* @param name the name of the collection.
* @param elements the getter of elements to be saved in JSON file.
*/
export declare type Save = (name: string, elements: any[]) => void;
/**
* The options when creating a collection.
* @template E the type of elements.
* @template I the type of id.
*/
export interface InternalCollectionOptions<E extends Element> {
/**
* The name of collection.
*/
name: string;
/**
* The comparator to compare the elements.
*/
comparator: Comparator<E>;
/**
* The elements of the collection.
*/
elements: E[];
/**
* To save the collection.
*/
save: Save;
/**
* The primary key.
*/
primaryKey: keyof E;
}
/**
* A collection is like an array.
* You can insert, update, delete and find elements in it.
*
* When you apply methods affecting the collection,
* it will start a debounced saver.
*
* Using `Array.from(collection)`, `[...collection]`,
* or `for (const element of collection)` is also good practice.
*
* @template E the type of elements.
* @template I the type of id.
*/
export declare class Collection<E extends Element> {
private readonly comparator;
private readonly name;
private readonly save;
private readonly primaryKey;
private readonly elements;
constructor(options: InternalCollectionOptions<E>);
protected startSaving(): void;
findAll(cond: Condition<E>): readonly E[];
removeAll(cond: Condition<E>): number;
/**
* @returns the index to insert or get, and whether it has found the element.
*/
private searchIndex;
[Symbol.iterator](): Iterator<Readonly<E>>;
insert(el: E): boolean;
update(el: Partial<E>): boolean;
remove(el: Partial<E>): boolean;
has(el: Partial<E>): boolean;
has(cond: Condition<E>): boolean;
find(el: Partial<E>): Readonly<E> | undefined;
}