Explorar el Código

Added Joi validation on endpoints and added missing functionality

pull/18/head
radivoje.milutinovic hace 3 años
padre
commit
b91572a423
Se han modificado 3 ficheros con 72 adiciones y 37 borrados
  1. 56
    34
      src/endpoints/user.js
  2. 13
    0
      src/models/user.js
  3. 3
    3
      src/routes/user.js

+ 56
- 34
src/endpoints/user.js Ver fichero

@@ -1,17 +1,15 @@
const bcrypt = require("bcryptjs/dist/bcrypt")
const { Router } = require("express")
const {Router} = require("express")
const User = require("../models/user")

const getAll = async (req, res) => {
try {
if (Object.entries(req.params).length === 0) {
// const usersList = userService.GetAllUsers()
// return res.Status(200).sendJson(usersList)
const allUsers = await User.find({})
return res.status(200).send(allUsers)
} else {
if (Object.entries(req.params).length !== 0) {
return res.status(400).send('unable to get all users, request was bad')
}

const allUsers = await User.find({})
return res.status(200).send(allUsers)
} catch (e) {
return res.status(500).send(e)
}
@@ -19,12 +17,15 @@ const getAll = async (req, res) => {

const getById = async (req, res, id) => {
try {
if (req.params.id) {
//get by Id
return res.status(200).send('sending user with id of ' + req.params.id)
} else {
if (!req.params.id) {
return res.status(400).send('Bad request')
}
const user = await User.findById(id)
if (!user) {
return res.status(404).send("User with the id of: " + id + " doesnt exist")
}

return res.status(200).json(user)
} catch (e) {
return res.status(500).send(e)
}
@@ -32,30 +33,44 @@ const getById = async (req, res, id) => {

const create = async (req, res, userModel) => {
try {
if (Object.entries(userModel).length !== 0) {
//create user
const newUser = new User(req.body)
newUser.password = await bcrypt.hash(newUser.password, 8)
await newUser.save()

return res.status(201).json(newUser)
} else {
return res.status(400).send('bad request')
if (Object.entries(userModel).length === 0) {
return res.status(400).send('Object cant be empty')
}

const err = await User.joiValidate(req.body)
if (err) {
return res.status(400).send(err.message)
}

const newUser = new User(req.body)
newUser.password = await bcrypt.hash(newUser.password, 8)
await newUser.save()

return res.status(201).json(newUser)
} catch (e) {
return res.status(500).send(e)
return res.status(500).send(e.message)
}
}

const updateUser = async (req, res) => {
userFound = true
const updateUser = async (req, res, id, objBody) => {
try {
if (Object.entries(req.body).length == 0) {
return res.status(400).send('invalid input parameters')
if (Object.entries(objBody).length == 0) {
return res.status(400).send('Invalid input parameters')
}
if (!userFound) {
return res.status(404).send('user not found')
const err = await User.joiValidate(objBody)
if (err) {
return res.status(400).send(err.message)
}

let user = await User.findById(id);
if (!user) {
return res.status(404).send("User with the id of: " + id + " doesnt exist")
}
//TODO: verovatno treba da se promeni ovo, ali neka ga za sad

user = objBody
await User.updateOne(user)

return res.status(200).send('user updated successfully')
} catch (e) {
return res.status(500).send(e)
@@ -77,17 +92,24 @@ const updateUserContacts = async (req, res) => {
}
}

const deleteUser = async (req, res) => {
const deleteUser = async (req, res, id) => {
try {
if (req.params.id) {
//get by Id
return res.status(204).send('deleting user with id of ' + req.params.id)
} else {
return res.status(400).send('Bad request')
console.log("id je: " + id)
if (!id) {
return res.status(400).send('You need to provide valid Id')
}

const user = await User.findById(id)
if(!user){
return res.status(404).send("User with the id of: " + id + " doesnt exist")
}

await User.deleteOne(user)

return res.status(204).send('Deleting user with id of ' + id)
} catch (e) {
return res.status(500).send(e)
}
}

module.exports = { getAll, getById, create, updateUser, updateUserContacts, deleteUser }
module.exports = {getAll, getById, create, updateUser, updateUserContacts, deleteUser}

+ 13
- 0
src/models/user.js Ver fichero

@@ -3,6 +3,7 @@ const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const ejwt = require('express-jwt')
const Joi = require('joi')

const userSchema = new mongoose.Schema({
name: {
@@ -24,6 +25,18 @@ const userSchema = new mongoose.Schema({
}]
})

userSchema.statics.joiValidate = async function(obj) {
const schema = Joi.object({
name: Joi.string().min(2).max(30).required(),
password: Joi.string().min(8).max(30).regex(/[a-zA-Z0-9]{3,30}/).required(),
email: Joi.string().email().required(),
})

const validation = schema.validate(obj);
return validation.error
}


// userSchema.pre('save', async function(next) {
// const user = this
// console.log('pre hash: ' + user.password)

+ 3
- 3
src/routes/user.js Ver fichero

@@ -18,8 +18,8 @@ router.post('/users', async (req, res) => {
})


router.put('/users', async (req, res) => {
return await endpoints.updateUser(req, res, req.body)
router.put('/users/:id', async (req, res) => {
return await endpoints.updateUser(req, res, req.params.id, req.body)
})

router.patch('/users/:id/contacts', async (req, res) => {
@@ -27,7 +27,7 @@ router.patch('/users/:id/contacts', async (req, res) => {
})

router.delete('/users/:id', async (req, res) => {
return await endpoints.deleteUser(req, res, req.body)
return await endpoints.deleteUser(req, res, req.params.id)
})

module.exports = router

Cargando…
Cancelar
Guardar