Skip to content

Instantly share code, notes, and snippets.

@jsdevtom
Created July 29, 2018 14:43
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jsdevtom/3528cad872c48a4c14347ea39dd45ef1 to your computer and use it in GitHub Desktop.
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
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));
};
@FaizUlHassan123
Copy link

package.josn ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment