Skip to content

Instantly share code, notes, and snippets.

@tksilicon
Last active May 10, 2020 15:36
Show Gist options
  • Save tksilicon/28d12818aceefe242e5bd23d2208b254 to your computer and use it in GitHub Desktop.
Save tksilicon/28d12818aceefe242e5bd23d2208b254 to your computer and use it in GitHub Desktop.
static async create(req, res, next) {
try {
const errors = validationResult(req); // Finds the validation errors in this request and wraps them in an object with handy functions
if (!errors.isEmpty()) {
return res.status(422).json({
error: {
code: `USR_03`,
message: `The email is invalid.`, // eslint-disable-line
field: `email`,
status: 400,
},
});
}
const { email, name, password } = req.query;
const cust = await Customer.findOne({
where: {
// eslint-disable-next-line object-shorthand
email: email,
},
});
if (cust) {
return res.status(422).json({
error: {
code: `USR_04`,
message: `The email already exists.`, // eslint-disable-line
field: `email`,
status: 400,
},
});
}
Customer.create({
email,
password,
name,
})
.then(user => {
const payload = { email: user.email };
const token = jwt.sign(payload, `${secret}`, { expiresIn: '24h' }); // Token is created
return res.status(200).json({
customer: {
customer_id: user.customer_id,
name: user.name,
email: user.email,
address_1: user.address_1,
address_2: user.address_2,
city: user.city,
region: user.region,
},
accessToken: `Bearer ${token}`, // Token sent to client
expiresIn: `24h`, // expiration
});
})
// eslint-disable-next-line no-unused-vars
.catch(_err => {
return res.status(400).json({
error: {
code: `USR_10`,
message: `Error occurred`, // eslint-disable-line
field: `register`,
status: 400,
},
});
});
} catch (error) {
return next(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment