Deployable hello function behind api gateway
This commit is contained in:
35
validators/index.js
Normal file
35
validators/index.js
Normal file
@@ -0,0 +1,35 @@
|
||||
const Ajv = require('ajv');
|
||||
const {customThrow} = require('../helpers');
|
||||
|
||||
const parseAndValidateBody = async (schema, body) => {
|
||||
let parsedBody;
|
||||
|
||||
try {
|
||||
parsedBody = JSON.parse(body);
|
||||
} catch (err) {
|
||||
customThrow(400, 'Error. Malformed event.parsedBody.');
|
||||
}
|
||||
|
||||
const validation = validateBody(schema, parsedBody);
|
||||
|
||||
if (!validation.isValid) {
|
||||
customThrow(400, validation.error);
|
||||
}
|
||||
|
||||
return parsedBody;
|
||||
};
|
||||
|
||||
const validateBody = (schema, body) => {
|
||||
const ajv = new Ajv();
|
||||
const validate = ajv.compile(schema);
|
||||
const isValid = validate(body);
|
||||
|
||||
return {
|
||||
isValid: isValid,
|
||||
error: JSON.stringify(validate.errors)
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
parseAndValidateBody,
|
||||
};
|
||||
33
validators/schemas.js
Normal file
33
validators/schemas.js
Normal file
@@ -0,0 +1,33 @@
|
||||
const answerSchema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"user_id": {"type": "string"},
|
||||
"question_id": {"type": "string"},
|
||||
"is_correct": {"type": "boolean"}
|
||||
},
|
||||
"required": ["user_id", "question_id", "is_correct"]
|
||||
};
|
||||
|
||||
const userSchema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "string"},
|
||||
"score": {"type": "number"}
|
||||
},
|
||||
"required": ["user_id", "question_id", "is_correct"]
|
||||
};
|
||||
|
||||
const loginFollowUpSchema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"accessToken": {"type": "string"}
|
||||
},
|
||||
"required": ["accessToken"]
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
answerSchema,
|
||||
userSchema,
|
||||
loginFollowUpSchema
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user