const Joi = require('joi') const apiSchema = require('../../schemas/api') const errorSchema = require('../../schemas/errors') const pluginConfig = { handlerType: 'reveal', docs: { description: 'reveal', notes: 'Reveal profile information to a grouping by membership', }, } const validators = { params: Joi.object({ grouping_id: Joi.number() }), query: Joi.object({ profile_id: Joi.number(), tag_id: Joi.number() }), } const responseSchemas = { response: Joi.object({ tags: Joi.array().items(), }), error: errorSchema.single, } module.exports = { method: 'POST', path: '/{grouping_id}/reveal', options: { ...pluginConfig.docs, tags: ['api'], auth: false, cors: true, handler: async function (request, h) { const { membershipService, profileService } = request.server.services() const grouping_id = request.params.grouping_id const { profile_id, tag_id } = request.query try { const tags = await profileService.revealProfileInfo({ profile_id, grouping_id, tag_id, is_deleted: false, }) // Notify both profiles that information has been revealed const memberships = await membershipService.findMemberships([ grouping_id, ]) const idsInGroup = memberships.map( membership => membership.profile_id, ) if (idsInGroup.length > 2) return console.error('ERROR: idsInGroup cannot have more than 2 entries: ', idsInGroup) // Grab User Info from Users Table const completeProfile = await profileService.getProfilesFor([profile_id], 'participant') // Grab the TagAssociation that matches the revealed profile // TODO: Check if there are multiple matching tags(?)(there shouldn't be) const returnedTag = () => { let matchingTag tags.forEach(tagAssoc => { if (tagAssoc.grouping_id === grouping_id && tagAssoc.profile_id === profile_id && tagAssoc.tag_id === tag_id) { matchingTag = tagAssoc } }) if (matchingTag) return matchingTag return console.error('ERROR: No matching tagAssociation') } const tag_description = returnedTag().tag.tag_description // TODO: Refactor completeProfile[0]... code smell const revealInfo = completeProfile[0][tag_description] idsInGroup.forEach(profile_id => { request.server.methods.notify( `${profile_id}.stonk`, { name: 'REVEALED_INFO', revealed_info: revealInfo, grouping_id: grouping_id, tag: tag_id, description: tag_description, type: 'info', }, h, ) }) return h .response({ ok: true, handler: pluginConfig.handlerType, data: { tags }, }) .code(200) } 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: { 200: apiSchema.single .append({ data: responseSchemas.response, }) .label('reveal_res'), 409: apiSchema.single .append({ data: responseSchemas.error, }) .label('error_single_res'), }, }, }, }