-
-
Save ming-chu/1718b32a91aa7812f28654bfa03df4a4 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 hidden or 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