UNPKG

11.1 kBTypeScriptView Raw
1/// <reference types="node" />
2
3import { EventEmitter } from "events";
4
5export = Nedb;
6export as namespace Nedb;
7
8declare class Nedb<G = any> extends EventEmitter {
9 constructor(pathOrOptions?: string | Nedb.DataStoreOptions);
10
11 persistence: Nedb.Persistence;
12
13 /**
14 * Load the database from the datafile, and trigger the execution of buffered commands if any
15 */
16 loadDatabase(cb?: (err: Error | null) => void): void;
17
18 /**
19 * Get an array of all the data in the database
20 */
21 getAllData(): any[];
22
23 /**
24 * Reset all currently defined indexes
25 */
26 resetIndexes(newData: any): void;
27
28 /**
29 * Ensure an index is kept for this field. Same parameters as lib/indexes
30 * For now this function is synchronous, we need to test how much time it takes
31 * We use an async API for consistency with the rest of the code
32 * @param cb Optional callback, signature: err
33 */
34 ensureIndex(options: Nedb.EnsureIndexOptions, cb?: (err: Error | null) => void): void;
35
36 /**
37 * Remove an index
38 * @param cb Optional callback, signature: err
39 */
40 removeIndex(fieldName: string, cb?: (err: Error | null) => void): void;
41
42 /**
43 * Add one or several document(s) to all indexes
44 */
45 addToIndexes<T extends G>(doc: T | T[]): void;
46
47 /**
48 * Remove one or several document(s) from all indexes
49 */
50 removeFromIndexes<T extends G>(doc: T | T[]): void;
51
52 /**
53 * Update one or several documents in all indexes
54 * To update multiple documents, oldDoc must be an array of { oldDoc, newDoc } pairs
55 * If one update violates a constraint, all changes are rolled back
56 */
57 updateIndexes<T extends G>(oldDoc: T, newDoc: T): void;
58 updateIndexes<T extends G>(updates: Array<{ oldDoc: T; newDoc: T }>): void;
59
60 /**
61 * Return the list of candidates for a given query
62 * Crude implementation for now, we return the candidates given by the first usable index if any
63 * We try the following query types, in this order: basic match, $in match, comparison match
64 * One way to make it better would be to enable the use of multiple indexes if the first usable index
65 * returns too much data. I may do it in the future.
66 *
67 * TODO: needs to be moved to the Cursor module
68 */
69 getCandidates(query: any): void;
70
71 /**
72 * Insert one or more new documents
73 * @param cb Optional callback, signature: err, insertedDoc
74 */
75 insert<T extends G>(newDoc: T, cb?: (err: Error | null, document: T) => void): void;
76 insert<T extends G>(newDocs: T[], cb?: (err: Error | null, documents: T[]) => void): void;
77
78 /**
79 * Count all documents matching the query
80 * @param query MongoDB-style query
81 */
82 count(query: any, callback: (err: Error | null, n: number) => void): void;
83 count(query: any): Nedb.CursorCount;
84
85 /**
86 * Find all documents matching the query
87 * If no callback is passed, we return the cursor so that user can limit, skip and finally exec
88 * @param query MongoDB-style query
89 * @param projection MongoDB-style projection
90 */
91 find<T extends G>(query: any, projection: any, callback: (err: Error | null, documents: T[]) => void): void;
92 find<T extends G>(query: any, projection?: any): Nedb.Cursor<T>;
93
94 /**
95 * Find all documents matching the query
96 * If no callback is passed, we return the cursor so that user can limit, skip and finally exec
97 * * @param query MongoDB-style query
98 */
99 find<T extends G>(query: any, callback: (err: Error | null, documents: T[]) => void): void;
100
101 /**
102 * Find one document matching the query
103 * @param query MongoDB-style query
104 * @param projection MongoDB-style projection
105 */
106 findOne<T extends G>(query: any, projection: any, callback: (err: Error | null, document: T) => void): void;
107
108 /**
109 * Find one document matching the query
110 * @param query MongoDB-style query
111 */
112 findOne<T extends G>(query: any, callback: (err: Error | null, document: T) => void): void;
113
114 /**
115 * Update all docs matching query v1.7.4 and prior signature.
116 * For now, very naive implementation (recalculating the whole database)
117 * @param options Optional options
118 * options.multi If true, can update multiple documents (defaults to false)
119 * options.upsert If true, document is inserted if the query doesn't match anything
120 * @param cb Optional callback, signature: err,
121 * numReplaced,
122 * upsert (set to true if the update was in fact an upsert)
123 *
124 * @api private Use Datastore.update which has the same signature
125 */
126 update(
127 query: any,
128 updateQuery: any,
129 options?: Nedb.UpdateOptions,
130 cb?: (err: Error | null, numberOfUpdated: number, upsert: boolean) => void,
131 ): void;
132
133 /**
134 * Update all docs matching query v1.8 signature.
135 * For now, very naive implementation (recalculating the whole database)
136 * @param options Optional options
137 * options.multi If true, can update multiple documents (defaults to false)
138 * options.upsert If true, document is inserted if the query doesn't match anything
139 * @param cb Optional callback, signature: err,
140 * numAffected,
141 * affectedDocuments (when returnUpdatedDocs is set to true), obj or array
142 * upsert (set to true if the update was in fact an upsert)
143 *
144 * @api private Use Datastore.update which has the same signature
145 */
146 update<T extends G>(
147 query: any,
148 updateQuery: any,
149 options?: Nedb.UpdateOptions,
150 cb?: (err: Error | null, numberOfUpdated: number, affectedDocuments: any, upsert: boolean) => void,
151 ): void;
152
153 /**
154 * Remove all docs matching the query
155 * For now very naive implementation (similar to update)
156 * @param options Optional options
157 * options.multi If true, can update multiple documents (defaults to false)
158 * @param cb Optional callback, signature: err, numRemoved
159 *
160 * @api private Use Datastore.remove which has the same signature
161 */
162 remove(query: any, options: Nedb.RemoveOptions, cb?: (err: Error | null, n: number) => void): void;
163 remove(query: any, cb?: (err: Error | null, n: number) => void): void;
164
165 addListener(event: "compaction.done", listener: () => void): this;
166 on(event: "compaction.done", listener: () => void): this;
167 once(event: "compaction.done", listener: () => void): this;
168 prependListener(event: "compaction.done", listener: () => void): this;
169 prependOnceListener(event: "compaction.done", listener: () => void): this;
170 removeListener(event: "compaction.done", listener: () => void): this;
171 off(event: "compaction.done", listener: () => void): this;
172 listeners(event: "compaction.done"): Array<() => void>;
173 rawListeners(event: "compaction.done"): Array<() => void>;
174 listenerCount(type: "compaction.done"): number;
175}
176
177declare namespace Nedb {
178 interface Cursor<T> {
179 sort(query: any): Cursor<T>;
180 skip(n: number): Cursor<T>;
181 limit(n: number): Cursor<T>;
182 projection(query: any): Cursor<T>;
183 exec(callback: (err: Error | null, documents: T[]) => void): void;
184 }
185
186 interface CursorCount {
187 exec(callback: (err: Error | null, count: number) => void): void;
188 }
189
190 interface DataStoreOptions {
191 filename?: string | undefined; // Optional, datastore will be in-memory only if not provided
192 inMemoryOnly?: boolean | undefined; // Optional, default to false
193 nodeWebkitAppName?: boolean | undefined; // Optional, specify the name of your NW app if you want options.filename to be relative to the directory where
194 autoload?: boolean | undefined; // Optional, defaults to false
195 // Optional, if autoload is used this will be called after the load database with the error object as parameter. If you don't pass it the error will be thrown
196 onload?(error: Error | null): any;
197 // (optional): hook you can use to transform data after it was serialized and before it is written to disk.
198 // Can be used for example to encrypt data before writing database to disk.
199 // This function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, which must absolutely not contain a \n character (or data will be lost)
200 afterSerialization?(line: string): string;
201 // (optional): reverse of afterSerialization.
202 // Make sure to include both and not just one or you risk data loss.
203 // For the same reason, make sure both functions are inverses of one another.
204 // Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks:
205 // NeDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths.
206 // In addition, if too much data is detected as corrupt,
207 // NeDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before (see below)
208 beforeDeserialization?(line: string): string;
209 // (optional): between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt.
210 // 0 means you don't tolerate any corruption, 1 means you don't care
211 corruptAlertThreshold?: number | undefined;
212 // (optional, defaults to false)
213 // timestamp the insertion and last update of all documents, with the fields createdAt and updatedAt. User-specified values override automatic generation, usually useful for testing.
214 timestampData?: boolean | undefined;
215 }
216
217 /**
218 * multi (defaults to false) which allows the modification of several documents if set to true
219 * upsert (defaults to false) if you want to insert a new document corresponding to the update rules if your query doesn't match anything
220 */
221 interface UpdateOptions {
222 multi?: boolean | undefined;
223 upsert?: boolean | undefined;
224 returnUpdatedDocs?: boolean | undefined;
225 }
226
227 /**
228 * options only one option for now: multi which allows the removal of multiple documents if set to true. Default is false
229 */
230 interface RemoveOptions {
231 multi?: boolean | undefined;
232 }
233
234 interface EnsureIndexOptions {
235 fieldName: string;
236 unique?: boolean | undefined;
237 sparse?: boolean | undefined;
238 expireAfterSeconds?: number | undefined;
239 }
240
241 interface Persistence {
242 compactDatafile(): void;
243 setAutocompactionInterval(interval: number): void;
244 stopAutocompaction(): void;
245 }
246}