Created
August 26, 2020 13:40
-
-
Save brunoksato/90b905e7e5f5a9e20567c72c24724d20 to your computer and use it in GitHub Desktop.
Cache mongo serverless
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
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 }; |
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 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