user.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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.parameterLengthTooSmall('username', 6))
  16. } if(req.body.username.length > 50) {
  17. validationErrors.push(Errors.parameterLengthTooLarge('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.parameterLengthTooSmall('password', 6))
  27. } if(req.body.password.length > 100) {
  28. validationErrors.push(Errors.parameterLengthTooLarge('password', 100))
  29. }
  30. }
  31. if(validationErrors.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. console.log(err)
  39. if(err === Errors.VALIDATION_ERROR) {
  40. res.status(400)
  41. res.json({
  42. errors: validationErrors
  43. })
  44. } else {
  45. res.status(500)
  46. res.json({
  47. errors: [Errors.unknown]
  48. })
  49. }
  50. }
  51. })
  52. module.exports = router