Created
July 29, 2018 14:43
-
-
Save jsdevtom/3528cad872c48a4c14347ea39dd45ef1 to your computer and use it in GitHub Desktop.
Connect to MongoDB from Google Cloud function best practice through Maintaining Persistent Connections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {CustomError} from "./error/custom-error.interface"; | |
require('dotenv').config(); | |
import {RequestHandler} from 'express'; | |
import {MongoClient} from 'mongodb'; | |
let client: MongoClient; | |
const connectToClientIfDropped: () => Promise<void> = async () => { | |
if (client && client.isConnected()) { | |
return; | |
} | |
const uri = process.env.MONGOURI; | |
if (uri == null) { | |
throw new CustomError('uri not defined'); | |
} | |
try { | |
client = await MongoClient.connect(uri, { useNewUrlParser: true }); | |
} catch (e) { | |
throw new CustomError('failed to connect to mongo client', e); | |
} | |
}; | |
export const getAllFromDB: RequestHandler = async (req, res) => { | |
await connectToClientIfDropped() | |
.catch((err: CustomError) => { | |
console.error(err.message, err.error); | |
res.status(500).end(err.message); | |
return; | |
}); | |
const docs = await client.db('test').collection('sites').find().toArray(); | |
res.send('Result: ' + JSON.stringify(docs)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
package.josn ?