app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const { userValidator } = require('./services/validators')
const userController = require('./controllers/users')
app.use(express.json());
app.post('/singup', userValidator, userController.createUser)
app.listen(4000, () => {
console.log('Server started')
})
user.js //Контроллер
const { User } = require('../models')
const { validationResult } = require('express-validator')
function createUser(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() })
}
// res.send(req.body);
User.findOne({where: {email: req.body.email }}).then(user => {
if (user) {
return Promise.reject({statusCode: 422, message: "This email is already used"});
} else {
const { login, email, password } = req.body;
return User.create({login, email, password});
}
})
.then(user => {
res.json(user);
})
.catch( error => {
res.status(error.statusCode || 400).json({error: error.message});
})
}
module.exports = {
createUser
}
validators.js
const { body } = require('express-validator');
const validators = {
userValidator: [
body('email').trim().isEmail().normalizeEmail(),
body('password').not().isEmpty().trim()
.isLength({ min: 5 }).withMessage('must be at least 5 chars long')
.matches(/\d/).withMessage('must contain a number')
]
}
module.exports = validators;