Skip to content

Instantly share code, notes, and snippets.

@lucasklaassen
Created March 3, 2018 17:21
Show Gist options
  • Save lucasklaassen/d69a448a2b78f393f468a3064d3400de to your computer and use it in GitHub Desktop.
Save lucasklaassen/d69a448a2b78f393f468a3064d3400de to your computer and use it in GitHub Desktop.
Serverless lambda function which handles validation, JSON parsing of request and error handling.
'use strict';
import utilities from './../lib/utilities';
import ExampleObject from './../objects/ExampleObject';
import Ajv from 'ajv';
const schema = {
"properties": {
"primaryID": {
"type": "string",
"format": "uuid"
}
},
"required": ["primaryID"]
};
module.exports.fetch = async function(event, context, callback) {
if (event.source === 'serverless-plugin-warmup') {
console.log('WarmUP - Lambda is warm!');
return callback(null, 'Lambda is warm!');
}
try {
const ajv = new Ajv();
const query = utilities.parseJSON(event.query);
const validate = ajv.compile(schema);
const valid = validate(query);
if(valid){
let exampleObject = new ExampleObject(event);
let response = await exampleObject.fetch();
return callback(null, response);
} else {
return callback(
new Error(
"[400] ".concat(ajv.errorsText(validate.errors))
)
);
}
} catch(error) {
console.error(error);
return callback(new Error('[500] Internal Server Error'));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment