Skip to content

Instantly share code, notes, and snippets.

@brunoksato
Created August 26, 2020 13:40
Show Gist options
  • Save brunoksato/90b905e7e5f5a9e20567c72c24724d20 to your computer and use it in GitHub Desktop.
Save brunoksato/90b905e7e5f5a9e20567c72c24724d20 to your computer and use it in GitHub Desktop.
Cache mongo serverless
mongoose.Promise = global.Promise;
let cache = null;
const connect = async (database) => {
if (cache) {
logger.info('[DATABASE] Using cache');
return Promise.resolve(cache);
}
return mongoose
.connect(database, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
bufferCommands: false,
bufferMaxEntries: 0,
})
.then((db) => {
cache = db;
return cache;
});
};
const disconnect = async () => {
await mongoose.disconnect();
};
mongoose.connection
.on('connecting', () => logger.info('[DATABASE] Connecting database'))
.on('connected', () => logger.info('[DATABASE] Database connected'))
.on('disconnected', () => logger.warn('[DATABASE] Database disconnected'))
.on('open', () => logger.info('[DATABASE] Connection opened'))
.on('close', () => logger.warn('[DATABASE] Connection closed'))
.on('error', (error) => logger.error(`[DATABASE] ${error.message}`));
export { connect, disconnect };
import serverless from 'serverless-http';
const handler = serverless(app);
export const start = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
const database = "youdb"
await connect(database);
const result = await handler(event, context);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment