Created
May 3, 2018 21:24
-
-
Save maciejmatu/e6aa8851fea1f678f3b9afb8da024235 to your computer and use it in GitHub Desktop.
Lambda function that connects to mongo database and increments a number
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
const { MongoClient } = require('mongodb'); | |
const DB_URL = process.env.DB_URL || 'mongodb://localhost:27017'; | |
const DB_NAME = 'serverless-smoothielicious'; | |
function errorResponse(callback, err) { | |
console.error(err); | |
callback(null, { | |
statusCode: 500, | |
body: JSON.stringify({ error: err }) | |
}) | |
} | |
function successResponse(callback, res) { | |
// console.logs are useful for the debug log on netlify | |
console.log('Saved new page request. Current count:', res.value.requests); | |
callback(null, { | |
statusCode: 200, | |
body: JSON.stringify(res) | |
}); | |
} | |
exports.handler = function(event, context, callback) { | |
MongoClient.connect(`${DB_URL}/${DB_NAME}`, (err, connection) => { | |
if (err) return errorResponse(callback, err); | |
const db = connection.db(DB_NAME); | |
const infoCollection = db.collection('info'); | |
const updateAction = { $inc: { requests: 1 } }; // increment requests record by 1 | |
const updateOptions = { | |
projection: { _id: 0 }, | |
upsert: true, // create record if not present | |
returnOriginal: false // return updated value | |
}; | |
infoCollection.findOneAndUpdate({}, updateAction, updateOptions, (err, result) => { | |
if (err) return errorResponse(callback, err); | |
console.log('Saved new page request. Current count:', result.value.requests); | |
connection.close(); | |
callback(null, { | |
statusCode: 200, | |
body: JSON.stringify(result) | |
}); | |
}) | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment