Created
April 4, 2024 14:44
-
-
Save iRoachie/012e95fb464ad49b5ffc163fe9d9e3de to your computer and use it in GitHub Desktop.
joi validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Joi = require('joi'); | |
const bcrypt = require('bcrypt'); | |
const { checkRecordsExists, insertRecord } = require('../utils/sqlSchemaFunction'); | |
const SignUpSchema = Joi.object({ | |
email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } }).required(), | |
username: Joi.string().alphanum().min(3).max(15).required(), | |
password: Joi.string().min(8).required(), | |
}); | |
const register = async (req, res) => { | |
try { | |
const { email, username, password } = await SignUpSchema.validateAsync( | |
req.body, { abortEarly: false } | |
); | |
const salt = await bcrypt.genSalt(10); | |
const hashedPassword = await bcrypt.hash(password, salt); | |
const user = { username, email, password: hashedPassword }; | |
const userAlreadyExists = await checkRecordsExists('users', 'email', email); | |
if (userAlreadyExists) { | |
return res.status(400).json('Email must be unique'); | |
} | |
await insertRecord("users", user); | |
res.status(200).json('User created successfully'); | |
} catch (err) { | |
if (Joi.isError(err)) { | |
return res.status(400).json(err.details); | |
} | |
res.status(500).json({ err: err.message }); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment