user.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. if(err === Errors.VALIDATION_ERROR) {
  39. res.status(400)
  40. res.json({
  41. errors: validationErrors
  42. })
  43. } else if(err.name === 'SequelizeUniqueConstraintError') {
  44. res.status(400)
  45. res.json({
  46. errors: [Errors.accountAlreadyCreated]
  47. })
  48. } else {
  49. res.status(500)
  50. res.json({
  51. errors: [Errors.unknown]
  52. })
  53. }
  54. }
  55. })
  56. module.exports = router