github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/kat/src/clients/db-providers/mongodb.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 { Db, MongoClient } from 'mongodb'; 16 import { config } from '../../lib/config'; 17 import { databaseCollectionName, IDatabaseProvider, indexes } from '../../lib/interfaces'; 18 import { databaseCollectionIndexes } from '../../lib/utils'; 19 20 let db: Db; 21 let mongoClient: MongoClient; 22 23 export default class MongoDBProvider implements IDatabaseProvider { 24 25 async init() { 26 try { 27 mongoClient = await MongoClient.connect(config.mongodb.connectionUrl, 28 { useNewUrlParser: true, useUnifiedTopology: true, ignoreUndefined: true }); 29 db = mongoClient.db(config.mongodb.databaseName); 30 for (const [collectionName, indexes] of Object.entries(databaseCollectionIndexes)) { 31 this.createCollection(collectionName, indexes); 32 } 33 } catch (err) { 34 throw new Error(`Failed to connect to Mongodb. ${err}`); 35 } 36 } 37 38 async createCollection(collectionName: string, indexes: indexes) { 39 try { 40 for (const index of indexes) { 41 const fields: { [f: string]: number } = {}; 42 for (const field of index.fields) { 43 fields[field] = 1; // all ascending currently 44 } 45 db.collection(collectionName).createIndex(fields, { unique: !!index.unique }); 46 } 47 } catch (err) { 48 throw new Error(`Failed to create collection. ${err}`); 49 } 50 } 51 52 count(collectionName: databaseCollectionName, query: object): Promise<number> { 53 return db.collection(collectionName).find(query).count(); 54 } 55 56 find<T>(collectionName: databaseCollectionName, query: object, sort: object, skip: number, limit: number): Promise<T[]> { 57 return db.collection(collectionName).find<T>(query, { projection: { _id: 0 } }).sort(sort).skip(skip).limit(limit).toArray(); 58 } 59 60 findOne<T>(collectionName: databaseCollectionName, query: object): Promise<T | null> { 61 return db.collection(collectionName).findOne<T>(query, { projection: { _id: 0 } }); 62 } 63 64 async updateOne(collectionName: databaseCollectionName, query: object, value: object, upsert: boolean) { 65 await db.collection(collectionName).updateOne(query, value, { upsert }); 66 } 67 68 shutDown() { 69 mongoClient.close(); 70 } 71 72 }