Skip to content

Instantly share code, notes, and snippets.

@maciejmatu
Created May 3, 2018 21:24
Show Gist options
  • Save maciejmatu/e6aa8851fea1f678f3b9afb8da024235 to your computer and use it in GitHub Desktop.
Save maciejmatu/e6aa8851fea1f678f3b9afb8da024235 to your computer and use it in GitHub Desktop.
Lambda function that connects to mongo database and increments a number
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