UNPKG

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