const Joi = require('joi') const apiSchema = require('../../schemas/api') const errorSchema = require('../../schemas/errors') const groupingSchema = require('../../schemas/groupings') const params = require('../../schemas/params') const pluginConfig = { handlerType: 'grouping', docs: { description: 'join', notes: 'Join a grouping by creating a membership record', }, } const validators = { params: params.profileId, payload: groupingSchema.single .append({ target_id: Joi.number().required(), role: Joi.string(), }) .label('grouping_membership_single'), } const responseSchemas = { response: Joi.object({ memberships: Joi.array().items(), hasMatch: Joi.boolean(), }).label('grouping_membership_list'), error: errorSchema.single, } module.exports = { method: 'POST', path: '/{profile_id}/join', options: { ...pluginConfig.docs, tags: ['api'], auth: false, cors: true, /** * Join a grouping by creating a membership record * @param {*} request * @param {*} h * @returns {object} */ handler: async function (request, h) { try { const { membershipService } = request.server.services() /** Grab payload info */ const profileId = request.params.profile_id const res = request.payload const groupingToWrite = { grouping_id: res.grouping_id, grouping_name: res.grouping_name, grouping_type: res.grouping_type, } /** Default to participant role */ const role = res.role ? res.role : 'participant' // TODO: LIMIT the amount of groupings by checking type // !: You should only be able to match with the target_id ONCE // !: You should only be associated with a single company too /** User membership service method to create membership */ const memberships = await membershipService.joinGrouping( profileId, res.target_id, groupingToWrite, role, ) // console.log(memberships) return h .response({ ok: true, handler: pluginConfig.handlerType, data: { memberships, hasMatch: memberships.every( membership => membership.is_active == true, ), }, }) .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('join_grouping_res'), 409: apiSchema.single .append({ data: responseSchemas.error, }) .label('error_single_res'), }, }, }, }