UNPKG

9.43 kBTypeScriptView Raw
1import { EventEmitter } from 'events'
2
3// Type definitions for NeDB 1.8
4// Project: https://github.com/bajankristof/nedb-promises
5// Definitions by: Sam Denty <https://github.com/samdenty99>
6// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
7export = Datastore
8export as namespace Datastore
9
10type Document = {
11 _id: string
12 createdAt?: Date
13 updatedAt?: Date
14}
15
16/**
17 * @summary
18 * As of v2.0.0 the Datastore class extends node's built
19 * in EventEmitter class and implements each method as an event
20 * plus additional error events.
21 *
22 * All event callbacks will be passed the same type of values,
23 * the first being the datastore, then the operation result (if there is any)
24 * and then the arguments of the called method. (Check out the first example!)
25 *
26 * All events have a matching error event that goes by the name of `${method}Error`,
27 * for example `findError` or `loadError`. The callbacks of these events will receive
28 * the same parameters as the normal event handlers except that instead of the
29 * operation result there will be an operation error. (Check out the second example!)
30 *
31 * A generic `error` event is also available. This event will be emitted at any of
32 * the above error events. The callbacks of this event will receive the same parameters
33 * as the specific error event handlers except that there will be one more parameter
34 * passed between the datastore and the error object, that being the name of the method
35 * that failed. (Check out the third example!)
36 *
37 * @example
38 * let datastore = Datastore.create()
39 * datastore.on('update', (datastore, result, query, update, options) => {
40 * })
41 * datastore.on('load', (datastore) => {
42 * // this event doesn't have a result
43 * })
44 * datastore.on('ensureIndex', (datastore, options) => {
45 * // this event doesn't have a result
46 * // but it has the options argument which will be passed to the
47 * // event handlers
48 * })
49 *
50 * @example
51 * let datastore = Datastore.create()
52 * datastore.on('updateError', (datastore, error, query, update, options) => {
53 * })
54 * datastore.on('loadError', (datastore, error) => {
55 * })
56 * datastore.on('ensureIndexError', (datastore, error, options) => {
57 * })
58 *
59 * @example
60 * let datastore = Datastore.create()
61 * datastore.on('error', (datastore, event, error, ...args) => {
62 * // for example
63 * // datastore, 'find', error, [{ foo: 'bar' }, {}]
64 * })
65 *
66 * @class
67 */
68declare class Datastore extends EventEmitter {
69
70 persistence: Nedb.Persistence
71
72 /**
73 * Datastore constructor...
74 *
75 * You should use `Datastore.create(...)` instead
76 * of `new Datastore(...)`. With that you can access
77 * the original datastore's properties such as `datastore.persistence`.
78 *
79 * It's basically the same as the original:
80 * https://github.com/louischatriot/nedb#creatingloading-a-database
81 */
82 constructor(pathOrOptions?: string | Nedb.DatastoreOptions)
83
84 /**
85 * Load the datastore.
86 */
87 load(): Promise<undefined>
88
89 /**
90 * Find documents that match a query.
91 *
92 * It's basically the same as the original:
93 * https://github.com/louischatriot/nedb#finding-documents
94 *
95 * There are differences minor in how the cursor works though.
96 *
97 * @example
98 * datastore.find({ ... }).sort({ ... }).exec().then(...)
99 *
100 * @example
101 * datastore.find({ ... }).sort({ ... }).then(...)
102 *
103 * @example
104 * // in an async function
105 * await datastore.find({ ... }).sort({ ... })
106 */
107 find<T>(query: any, projection?: {[p in keyof T | '_id' | 'createdAt' | 'updatedAt']?:number}): Nedb.Cursor<T & Document>
108
109 /**
110 * Find a document that matches a query.
111 *
112 * It's basically the same as the original:
113 * https://github.com/louischatriot/nedb#finding-documents
114 */
115 findOne<T>(query: any, projection?: {[p in keyof T | '_id' | 'createdAt' | 'updatedAt']?:number}): Promise<T & Document>
116
117 /**
118 * Insert a document or documents.
119 *
120 * It's basically the same as the original:
121 * https://github.com/louischatriot/nedb#inserting-documents
122 *
123 * @param {Object|Object[]} docs
124 * @return {Promise.<Object|Object[]>}
125 */
126 insert<T extends any | any[]>(docs: T): Promise<T & Document>
127
128 /**
129 * Update documents that match a query.
130 *
131 * It's basically the same as the original:
132 * https://github.com/louischatriot/nedb#updating-documents
133 *
134 * If you set `options.returnUpdatedDocs`,
135 * the returned promise will resolve with
136 * an object (if `options.multi` is `false`) or
137 * with an array of objects.
138 */
139
140 update<T>(
141 query: any,
142 updateQuery: any,
143 options?: Nedb.UpdateOptions & { returnUpdatedDocs?: false }
144 ): Promise<number>
145
146 update<T>(
147 query: any,
148 updateQuery: any,
149 options?: Nedb.UpdateOptions & { returnUpdatedDocs: true; multi?: false }
150 ): Promise<T & Document>
151
152 update<T>(
153 query: any,
154 updateQuery: any,
155 options?: Nedb.UpdateOptions & { returnUpdatedDocs: true; multi: true }
156 ): Promise<(T & Document)[]>
157
158 /**
159 * Remove documents that match a query.
160 *
161 * It's basically the same as the original:
162 * https://github.com/louischatriot/nedb#removing-documents
163 */
164 remove(query: any, options: Nedb.RemoveOptions): Promise<number>
165
166 /**
167 * Count all documents matching the query
168 * @param query MongoDB-style query
169 */
170 count(query: any): Promise<number>
171
172 /**
173 * Ensure an index is kept for this field. Same parameters as lib/indexes
174 * For now this function is synchronous, we need to test how much time it takes
175 * We use an async API for consistency with the rest of the code
176 */
177 ensureIndex(options: Nedb.EnsureIndexOptions): Promise<undefined>
178
179 /**
180 * Remove an index
181 */
182 removeIndex(fieldName: string): Promise<undefined>
183
184 /**
185 * Create a database instance.
186 *
187 * Use this over `new Datastore(...)` to access
188 * original nedb datastore properties, such as
189 * `datastore.persistence`.
190 *
191 * For more information visit:
192 * https://github.com/louischatriot/nedb#creatingloading-a-database
193 */
194 static create(pathOrOptions?: string | Nedb.DatastoreOptions): Datastore
195}
196
197declare namespace Nedb {
198 interface Cursor<T> extends Promise<T[]> {
199 sort(query: any): Cursor<T>
200 skip(n: number): Cursor<T>
201 limit(n: number): Cursor<T>
202 projection(projection: {[p in keyof T | '_id' | 'createdAt' | 'updatedAt']?:number}): Cursor<T>
203 exec(): Promise<T[]>
204 }
205
206 interface DatastoreOptions {
207 filename?: string // Optional, datastore will be in-memory only if not provided
208 inMemoryOnly?: boolean // Optional, default to false
209 nodeWebkitAppName?: boolean // Optional, specify the name of your NW app if you want options.filename to be relative to the directory where
210 autoload?: boolean // Optional, defaults to false
211 // 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
212 onload?(error: Error): any
213 // (optional): hook you can use to transform data after it was serialized and before it is written to disk.
214 // Can be used for example to encrypt data before writing database to disk.
215 // 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)
216 afterSerialization?(line: string): string
217 // (optional): reverse of afterSerialization.
218 // Make sure to include both and not just one or you risk data loss.
219 // For the same reason, make sure both functions are inverses of one another.
220 // Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks:
221 // 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.
222 // In addition, if too much data is detected as corrupt,
223 // 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)
224 beforeDeserialization?(line: string): string
225 // (optional): between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt.
226 // 0 means you don't tolerate any corruption, 1 means you don't care
227 corruptAlertThreshold?: number
228 // (optional, defaults to false)
229 // 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.
230 timestampData?: boolean
231 }
232
233 /**
234 * multi (defaults to false) which allows the modification of several documents if set to true
235 * upsert (defaults to false) if you want to insert a new document corresponding to the update rules if your query doesn't match anything
236 */
237 interface UpdateOptions {
238 multi?: boolean
239 upsert?: boolean
240 returnUpdatedDocs?: boolean
241 }
242
243 /**
244 * options only one option for now: multi which allows the removal of multiple documents if set to true. Default is false
245 */
246 interface RemoveOptions {
247 multi?: boolean
248 }
249
250 interface EnsureIndexOptions {
251 fieldName: string
252 unique?: boolean
253 sparse?: boolean
254 }
255
256 interface Persistence {
257 compactDatafile(): void
258 setAutocompactionInterval(interval: number): void
259 stopAutocompaction(): void
260 }
261}