user.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors.js')
  4. let User = require('../models').User
  5. router.post('/', async (req, res) => {
  6. let user, validationErrors = [];
  7. try {
  8. //Validations
  9. if(req.body.username === undefined) {
  10. validationErrors.push(Errors.missingParameter('username'))
  11. } else {
  12. if(typeof req.body.username !== 'string') {
  13. validationErrors.push(Errors.invalidParameterType('username', 'string'))
  14. } if(req.body.username.length < 6) {
  15. validationErrors.push(Errors.parmeterLengthTooSmall('username', 6))
  16. } if(req.body.username.length > 50) {
  17. validationErrors.push(Errors.parmeterLengthTooLarge('username', 50))
  18. }
  19. }
  20. if(req.body.password === undefined) {
  21. validationErrors.push(Errors.missingParameter('password'))
  22. } else {
  23. if(typeof req.body.password !== 'string') {
  24. validationErrors.push(Errors.invalidParameterType('password', 'string'))
  25. } if(req.body.password.length < 6) {
  26. validationErrors.push(Errors.parmeterLengthTooSmall('password', 6))
  27. } if(req.body.password.length > 100) {
  28. validationErrors.push(Errors.parmeterLengthTooSmall('password', 100))
  29. }
  30. }
  31. if(errors.length) throw Errors.VALIDATION_ERROR
  32. user = await User.create({
  33. username: req.body.username,
  34. hash: req.body.password
  35. })
  36. res.json(user.toJSON())
  37. } catch (err) {
  38. if(err === Errors.VALIDATION_ERROR) {
  39. res.status(400)
  40. res.json({
  41. errors: validationErrors
  42. })
  43. } else {
  44. res.json(err)
  45. }
  46. }
  47. })
  48. module.exports = router