'use strict' const Joi = require('joi') const apiSchema = require('../../schemas/api') const errorSchema = require('../../schemas/errors') const pluginConfig = { handlerType: 'score', docs: { description: 'scores', notes: 'A list of profile scores', }, } const validators = { /** Validate the header (cookie check) */ // headers: true, /** Validate the route params (/active/{thing}) */ params: Joi.object({ profile_id: Joi.number(), }), /** Validate the route query (/active/{thing}?limit=10&offset=10) */ query: Joi.object({ max_distance: Joi.number(), unit: Joi.string(), }), /** Validate the incoming payload (POST method) */ // payload: true, } const responseSchemas = { response: Joi.array().items(), error: errorSchema.single } module.exports = { method: 'GET', path: '/{profile_id}/score', options: { ...pluginConfig.docs, tags: ['api'], /** Protect this route with authentication? */ auth: false, cors: true, handler: async function (request, h) { const { profileService, matchQueueService } = request.server.services() const profileId = request.params.profile_id const maxDistanceMiles = request.query.max_distance const distanceUnit = request.query.unit ? request.query.unit : 'mile' const scoredProfiles = await profileService.scoreProfilesFor( profileId, maxDistanceMiles, distanceUnit, ) try { if (!scoredProfiles) { throw new RangeError('Unable to score profiles') } await matchQueueService.saveMatchQueue( profileId, scoredProfiles.map(profile => profile.profile_id), ) return h .response({ ok: true, handler: pluginConfig.handlerType, data: scoredProfiles, }) .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, }), 409: apiSchema.single.append({ data: responseSchemas.error, }) }, }, }, }