Adding customer schema validation

master
Mark Moffat 2019-11-16 09:32:15 +10:30
parent 17ee5bcfc4
commit 62dacd3867
3 changed files with 66 additions and 11 deletions

View File

@ -0,0 +1,49 @@
{
"$id": "newCustomer",
"type": "object",
"properties": {
"email": {
"type": "string",
"format": "email"
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"address1": {
"type": "string"
},
"address2": {
"type": "string"
},
"country": {
"type": "string"
},
"state": {
"type": "string"
},
"postcode": {
"type": "string"
},
"phone": {
"type": "string"
},
"password": {
"type": "string"
}
},
"required": [
"email",
"firstName",
"lastName",
"address1",
"address2",
"country",
"state",
"postcode",
"phone",
"password"
]
}

View File

@ -4,13 +4,14 @@ const colors = require('colors');
const randtoken = require('rand-token');
const bcrypt = require('bcryptjs');
const common = require('../lib/common');
const { validateJson } = require('../lib/schema');
const { restrict } = require('../lib/auth');
// insert a customer
router.post('/customer/create', async (req, res) => {
const db = req.app.db;
const doc = {
const customerObj = {
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
@ -24,6 +25,12 @@ router.post('/customer/create', async (req, res) => {
created: new Date()
};
const schemaResult = validateJson('newCustomer', customerObj);
if(!schemaResult){
res.status(400).json(schemaResult.errors);
return;
}
// check for existing customer
const customer = await db.customers.findOne({ email: req.body.email });
if(customer){
@ -34,14 +41,12 @@ router.post('/customer/create', async (req, res) => {
}
// email is ok to be used.
try{
await db.customers.insertOne(doc, (err, newCustomer) => {
const newCustomer = await db.customers.insertOne(customerObj);
// Customer creation successful
req.session.customer = newCustomer.insertedId;
res.status(200).json({
message: 'Successfully logged in',
customer: newCustomer
});
});
const customerReturn = newCustomer.ops[0];
delete customerReturn.password;
res.status(200).json(customerReturn);
}catch(ex){
console.error(colors.red('Failed to insert customer: ', ex));
res.status(400).json({

View File

@ -27,7 +27,8 @@ test('[Success] Create a customer', async t => {
.send(customer)
.expect(200);
t.deepEqual(res.body.message, 'Successfully logged in');
t.deepEqual(res.body.email, customer.email);
t.deepEqual(res.body.firstName, customer.firstName);
});
test('[Fail] Try create a duplicate customer', async t => {