HAPI JS и неверный запрос - PullRequest
       25

HAPI JS и неверный запрос

0 голосов
/ 15 февраля 2020

Я пытаюсь создать API с HAPI, и при выполнении тестов я получаю неверный запрос 400 ошибок

Может кто-нибудь объяснить мне, что я делаю неправильно?

Я пытался следовать всем документам, но я просто в шоке

Моя первая проблема в том, что когда я запускаю тест с использованием LAB ... ловушка не перехватывает и не возвращает никаких ошибок

Моя вторая проблема заключается в том, что когда я пытаюсь выполнить простой запрос GET, я получаю недопустимая ошибка URL

Я записываю ответ, и в журнале показываются параметры моего запроса, а запрос пуст.

У меня такое ощущение, что это может быть что-то незначительное, что я просматриваю, но после того, как смотрю на экран в течение 10 часов, я просто в полной растерянности

Мой индекс


const after = async (server: Server) => {
    await server.route(require('./routes'));
};

export const plugin: Plugin<any> = {
    name: 'api'
    register: async (server: Server, options: any) => {
        await server.dependency('server-database', after);
    }
};

Мои маршруты


const SchedulesRoutes = require('./player-schedules/schedules-routes');

module.exports = [...SchedulesRoutes];

Мой фактический запрос GET

import joi from '@hapi/joi';
import moment from 'moment';

import { dateFormat } from '../../../lib/util/defaults';
import { badRequest } from 'boom';
import { ServerRoute } from 'hapi';


const tags = ['api', 'schedule', 'schedules'];

module.exports = [
    {
        path: '/players/{playerId}/scheduled-games',
        method: 'GET',
        config: {
            tags,
            description: 'Returns Entire Scheduled Games per Player ID',
            handler: async (request, h) => {
                try {
                    const params = request.params;
                    const query = request.query;

                    const res = await request.app.db
                        .request()
                        .input('IdProvider', params.playerId)
                        .input('Start Date', query.startDate)
                        .input('End Date', query.endDate)
                        .execute('SS_GetScheduledGamesByPlayer');

                        console.log(res.recordsets);

                    let games = res.recordsets[0].sort((game1, game2) => {
                        const date1 = moment(game1.date).format(dateFormat);
                        const date2 = moment(game2.date).format(dateFormat);

                        if (date1 > date2) return 1;
                        if (date2 > date1) return -1;
                        return 0;
                    });

                    games = games.reduce((acc, curr) => {
                        const date = moment(curr.date).utc().format(dateFormat);

                        acc[date] = acc[date] || [];
                        acc[date].push(curr);

                        return acc;
                    }, {});
                    console.log(res.recordsets);
                    return { games };
                }
                catch (err) {
                    console.log(err);
                    return badRequest('Bad Request');
                }

            },
            validate: {
                params: {
                    playerId: joi.number().required()
                },
                query: {
                    startDate: joi.date().required().default(moment(new Date()).format(dateFormat)),
                    endDate: joi.date()
                }
            }
        },
    }
];

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...