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.

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