UNPKG

mongoing

Version:

cloud function computing mongodb middleware

46 lines (43 loc) 1.38 kB
'use strict' const { connect } = require('mongodb') /** * url * process.env.MONGODB * mongodb://127.0.0.1:27017/mongoing */ module.exports = function (callback, url, options = {}) { let collections = [] let mongourl = typeof url === 'string' ? url : (process.env.MONGODB || 'mongodb://127.0.0.1:27017/mongoing') if (url instanceof Array) { collections = url } else if (options instanceof Array) { collections = options } options = Object.assign({ useNewUrlParser: true, useUnifiedTopology: true }, options instanceof Array ? {} : options) return async (...args) => { let __client = null let __db = null try { __client = await connect(mongourl, options) __db = __client.db() let list = await __db.collections() const collectionMap = {} list.forEach(i => collectionMap[i.collectionName] = i) for (let name of collections) { if (!collectionMap[name]) { collectionMap[name] = __db.collection(name) } } const result = await callback(...args, { __client, __db, ...collectionMap }) return result } catch (err) { throw err } finally { __client && await __client.close() } } }