Advertisement
ADL_Rodrigo_Silva

Untitled

Jul 15th, 2022
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const User = require('../models/User');
  2.  
  3. const router = require('express').Router();
  4. const Joi = require('@hapi/joi');
  5. const bcrypt = require('bcrypt');
  6.  
  7. const schemeRegister = Joi.object({
  8.     name: Joi.string().min(6).max(255).required(),
  9.     email: Joi.string().min(6).max(255).required().email(),
  10.     password: Joi.string().min(6).max(1024).required()
  11. });
  12.  
  13. router.post('/register', async (request, response) =>
  14. {
  15.     // Validación de la data que nos llega por el request
  16.  
  17.     const { error } = schemeRegister.validate(request.body);
  18.  
  19.     console.log("error", error);
  20.  
  21.     if (error) {
  22.         return response.status(400).json(
  23.             {
  24.                 error: error.details[0].message
  25.             }
  26.         )
  27.     }
  28.  
  29.     // Encriptación del password
  30.     const salt = await bcrypt.genSalt(10);
  31.     const password = await bcrypt.hash(request.body.password, salt);
  32.  
  33.     // Creación de nuestro usuario
  34.     const user = new User(
  35.         {
  36.             name: request.body.name,
  37.             email: request.body.email,
  38.             password: password
  39.         });
  40.    
  41.     try {
  42.         const savedUser = await user.save();
  43.         response.json({
  44.             error: null,
  45.             data: savedUser
  46.         })
  47.     } catch (error) {
  48.         response.status(400).json({error});
  49.     }
  50.    
  51. });
  52.  
  53. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement