-
-
Save rbrto/326a0802f8be1114686d11fa4405e56d 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