'use strict' 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 { dispatchNotification } = require('../../utils') const pluginConfig = { handlerType: 'grouping', docs: { description: 'active memberships', notes: 'A list of groupings with active membership', }, } 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({ type: Joi.string().lowercase().min(6).max(11) }), /** Validate the incoming payload (POST method) */ // payload: true, } const responseSchemas = { single: groupingSchema.single, list: groupingSchema.listWithProfiles, error: errorSchema.single, } module.exports = { method: 'GET', path: '/{profile_id}', options: { ...pluginConfig.docs, tags: ['api'], /** Protect this route with authentication? */ auth: false, cors: true, handler: async function (request, h) { const { membershipService, profileService } = request.server.services() const membershipType = request.query.type const profileId = request.params.profile_id let groupings = await membershipService.findGroupingsByProfileId( profileId, membershipType, ) /** * Heavily process the result by storing just a profile_id * and attach complete profiles */ let pIds = groupings.reduce((ids, grouping) => { grouping.profiles.forEach(p => { if (p.profile_id == profileId) return ids.push(p.profile_id) grouping.profile = p.profile_id }) delete grouping.profiles return ids }, []) /** Assemble complete profiles to reference and pass */ const completedProfiles = await profileService.getProfilesFor( pIds, 'participant', false, ) const reformattedGroupings = groupings.map(g => { completedProfiles.forEach(p => { g.profile = g.profile == p.profile_id ? p : g.profile }) return g }) dispatchNotification( { name: 'MSHRM', price: (500 + Math.floor(Math.random() * 100)).toString(), order: null, type: 'info', }, `${profileId}.stonk`, h, ) try { return { ok: true, handler: pluginConfig.handlerType, data: reformattedGroupings, } } catch (err) { return { ok: false, handler: pluginConfig.handlerType, data: { error: `${err}` }, } } }, /** Validate based on validators object */ validate: { ...validators, failAction: 'log', }, /** Validate the server response */ response: { schema: apiSchema.single .append({ data: responseSchemas.list, }) .label('grouping_list_res'), }, }, }