Skip to content

Instantly share code, notes, and snippets.

@rbrto
Forked from jsdevtom/index.ts
Created May 3, 2020 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbrto/326a0802f8be1114686d11fa4405e56d to your computer and use it in GitHub Desktop.
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
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