Просмотр исходного кода

Added Joi validation on endpoints and added missing functionality

pull/18/head
radivoje.milutinovic 3 лет назад
Родитель
Сommit
b91572a423
3 измененных файлов: 72 добавлений и 37 удалений
  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 Просмотреть файл

const bcrypt = require("bcryptjs/dist/bcrypt") const bcrypt = require("bcryptjs/dist/bcrypt")
const { Router } = require("express")
const {Router} = require("express")
const User = require("../models/user") const User = require("../models/user")


const getAll = async (req, res) => { const getAll = async (req, res) => {
try { 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') 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) { } catch (e) {
return res.status(500).send(e) return res.status(500).send(e)
} }


const getById = async (req, res, id) => { const getById = async (req, res, id) => {
try { 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') 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) { } catch (e) {
return res.status(500).send(e) return res.status(500).send(e)
} }


const create = async (req, res, userModel) => { const create = async (req, res, userModel) => {
try { 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) { } 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 { 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') return res.status(200).send('user updated successfully')
} catch (e) { } catch (e) {
return res.status(500).send(e) return res.status(500).send(e)
} }
} }


const deleteUser = async (req, res) => {
const deleteUser = async (req, res, id) => {
try { 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) { } catch (e) {
return res.status(500).send(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 Просмотреть файл

const bcrypt = require('bcryptjs') const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken') const jwt = require('jsonwebtoken')
const ejwt = require('express-jwt') const ejwt = require('express-jwt')
const Joi = require('joi')


const userSchema = new mongoose.Schema({ const userSchema = new mongoose.Schema({
name: { name: {
}] }]
}) })


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) { // userSchema.pre('save', async function(next) {
// const user = this // const user = this
// console.log('pre hash: ' + user.password) // console.log('pre hash: ' + user.password)

+ 3
- 3
src/routes/user.js Просмотреть файл

}) })




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) => { router.patch('/users/:id/contacts', async (req, res) => {
}) })


router.delete('/users/:id', 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 module.exports = router

Загрузка…
Отмена
Сохранить