github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/kat/src/clients/db-providers/nedb.ts (about) 1 // Copyright © 2021 Kaleido, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 import Datastore from 'nedb-promises'; 16 import path from 'path'; 17 import { databaseCollectionName, IDatabaseProvider, indexes } from '../../lib/interfaces'; 18 import { constants, databaseCollectionIndexes } from '../../lib/utils'; 19 20 const projection = { _id: 0 }; 21 let collections: { [name: string]: Datastore } = {}; 22 23 export default class NEDBProvider implements IDatabaseProvider { 24 25 async init() { 26 try { 27 for (const [collectionName, indexes] of Object.entries(databaseCollectionIndexes)) { 28 this.createCollection(collectionName, indexes); 29 } 30 } catch (err) { 31 throw new Error(`Failed to initialize NEDB. ${err}`); 32 } 33 } 34 35 async createCollection(collectionName: string, indexes: indexes) { 36 const collection = Datastore.create({ 37 filename: path.join(constants.DATA_DIRECTORY, `${collectionName}.json`), 38 autoload: true 39 }); 40 for (const index of indexes) { 41 // No compound indexes here 42 for (let fieldName of index.fields) { 43 collection.ensureIndex({ fieldName, unique: !!index.unique }); 44 } 45 } 46 collections[collectionName] = collection; 47 } 48 49 count(collectionName: databaseCollectionName, query: object): Promise<number> { 50 return collections[collectionName].count(query); 51 } 52 53 find<T>(collectionName: databaseCollectionName, query: object, sort: object, skip: number, limit: number): Promise<T[]> { 54 return collections[collectionName].find<T>(query, projection).skip(skip).limit(limit).sort(sort); 55 } 56 57 findOne<T>(collectionName: databaseCollectionName, query: object): Promise<T | null> { 58 return collections[collectionName].findOne<T>(query, projection); 59 } 60 61 async updateOne(collectionName: databaseCollectionName, query: object, value: object, upsert: boolean) { 62 await collections[collectionName].update(query, value, { upsert }); 63 } 64 65 shutDown() { } 66 67 }