'use strict' const Joi = require('joi') const apiSchema = require('../../schemas/api') const errorSchema = require('../../schemas/errors') const surveyResponseSchema = require('../../schemas/responses') const params = require('../../schemas/params') const pluginConfig = { handlerType: 'profile', docs: { description: 'Update profile', notes: 'Update profile responses', }, } const responseSchemas = { response: surveyResponseSchema.list, error: errorSchema.single, } const validators = { /** Validate the header (cookie check) */ // headers: true, /** Validate the route params (/active/{thing}) */ params: params.profileId, /** Validate the route query (/active/{thing}?limit=10&offset=10) */ query: Joi.object({ response_key_id: Joi.number(), val: Joi.string(), }), /** Validate the incoming payload (POST method) */ // payload: responseSchemas.responses, } module.exports = { method: 'POST', path: '/{profile_id}/respond', options: { ...pluginConfig.docs, tags: ['api'], /** Protect this route with authentication? */ auth: false, cors: true, handler: async function (request, h) { const { profileService } = request.services() const profileId = request.params.profile_id const responseToSave = { profile_id: profileId, response_key_id: request.query.response_key_id, val: request.query.val, } const allResponses = await profileService.saveResponseForProfile( profileId, responseToSave, ) try { // profileService.saveResponseForProfile() will return null if it exists if (!allResponses) { throw new RangeError('Response already exists') } return h .response({ ok: true, handler: pluginConfig.handlerType, data: allResponses, }) .code(201) } catch (err) { return h .response({ ok: false, handler: pluginConfig.handlerType, data: { error: `${err}` }, }) .code(409) } }, /** Validate based on validators object */ validate: { ...validators, failAction: 'log', }, /** Validate the server response */ response: { status: { 201: apiSchema.single .append({ data: responseSchemas.response, }) .label('response_list_res'), 409: apiSchema.single .append({ data: responseSchemas.error, }) .label('error_single_res'), }, }, }, }