You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

update.js 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. 'use strict'
  2. const Joi = require('joi')
  3. const pluginConfig = {
  4. handlerType: 'profile',
  5. docs: {
  6. description: 'Update profile',
  7. notes: 'Update profile responses',
  8. },
  9. }
  10. const responseSchemas = {
  11. responses: Joi.array().items(
  12. Joi.object({
  13. response_id: Joi.number().required(),
  14. profile_id: Joi.number().required(),
  15. response_key_id: Joi.number().required(),
  16. val: Joi.string().required(),
  17. }),
  18. ),
  19. error: Joi.object({
  20. error: Joi.string(),
  21. }),
  22. }
  23. const validators = {
  24. /** Validate the header (cookie check) */
  25. // headers: true,
  26. /** Validate the route params (/active/{thing}) */
  27. params: Joi.object({ profile_id: Joi.number() }),
  28. /** Validate the route query (/active/{thing}?limit=10&offset=10) */
  29. // query: true,
  30. /** Validate the incoming payload (POST method) */
  31. payload: responseSchemas.responses,
  32. }
  33. module.exports = {
  34. method: 'PATCH',
  35. path: '/{profile_id}/update/{response_id?}',
  36. options: {
  37. ...pluginConfig.docs,
  38. tags: ['api'],
  39. /** Protect this route with authentication? */
  40. auth: false,
  41. handler: async function (request, h) {
  42. const { profileService } = request.services()
  43. const profileId = request.params.profile_id
  44. const responseId = request.params.response_id ? request.params.response_id : null
  45. /** Grab payload info */
  46. const res = request.payload
  47. try {
  48. const updatedResponses = await profileService.updateResponsesInProfile(profileId, res)
  49. if(!updatedResponses) {
  50. throw new RangeError(
  51. 'Response not updated',
  52. )
  53. }
  54. return h.response({
  55. ok: true,
  56. handler: pluginConfig.handlerType,
  57. data: updatedResponses,
  58. }).code(200)
  59. } catch (err) {
  60. return h.response({
  61. ok: false,
  62. handler: pluginConfig.handlerType,
  63. data: { error: `${err}` },
  64. }).code(409)
  65. }
  66. },
  67. /** Validate based on validators object */
  68. validate: {
  69. ...validators,
  70. failAction: 'log',
  71. },
  72. /** Validate the server response */
  73. response: {
  74. status: {
  75. 200: Joi.object({
  76. ok: Joi.bool(),
  77. handler: Joi.string(),
  78. data: responseSchemas.responses,
  79. }),
  80. 409: Joi.object({
  81. ok: Joi.bool(),
  82. handler: Joi.string(),
  83. data: responseSchemas.error,
  84. }),
  85. },
  86. },
  87. },
  88. }