Как проверить правильность ввода параметров в диалоге - PullRequest
0 голосов
/ 09 января 2020

Я хочу проверить параметр, введенный пользователем, прежде чем продолжить бронирование.

Вот мой код:

function makeAppointment (agent) {
        // Use the Dialogflow's date and time parameters to create Javascript Date instances, 'dateTimeStart' and 'dateTimeEnd',
        // which are used to specify the appointment's time.
        const appointmentDuration = 1;// Define the length of the appointment to be one hour.

        const dateTimeStart = convertParametersDate(agent.parameters.date, agent.parameters.time,timeZoneOffset);
        const dateTimeEnd = addHours(dateTimeStart, appointmentDuration);
        const appointmentTimeString = getLocaleTimeString(dateTimeStart);
        const appointmentDateString = getLocaleDateString(dateTimeStart);
        // Check the availability of the time slot and set up an appointment if the time slot is available on the calendar
        return createCalendarEvent(dateTimeStart, dateTimeEnd).then(() => {
            agent.add(`Done ?`);
        }).catch(() => {
            agent.add(` ?Sorry check other date`);
        });
    }
    function createCalendarEvent (dateTimeStart, dateTimeEnd) {
        return new Promise((resolve, reject) => {
            calendar.events.list({  // List all events in the specified time period
                auth: serviceAccountAuth,
                calendarId: calendarId,
                timeMin: dateTimeStart.toISOString(),
                timeMax: dateTimeEnd.toISOString()
            }, (err, calendarResponse) => {
                // Check if there exists any event on the calendar given the specified the time period
                if (err || calendarResponse.data.items.length > 0) {
                    reject(err || new Error('Die angeforderte Zeit kollidiert mit einem anderen Termin'));
                } else {
                    // Create an event for the requested time period
                    calendar.events.insert({ auth: serviceAccountAuth,
                            calendarId: calendarId,
                            resource: {summary: 'Appointment',
                                start: {dateTime: dateTimeStart},
                                end: {dateTime: dateTimeEnd}}
                        }, (err, event) => {
                            err ? reject(err) : resolve(event);
                        }
                    );
                }
            });
        });
    }

Моя проверка должна быть такой: если dateTimeStart closehourtime

openhourtime = '09: 00 'closehourtime = '16: 00'

Можете ли вы помочь мне, как сделать это внутри кода?

1 Ответ

1 голос
/ 09 января 2020

Предполагая, что вы используете пример кода Google , где вспомогательная функция Внедрите оператор if в функции convertParametersDate, возвращающий вам объект даты, вы можете изменить свою функцию makeAppointment следующим образом, чтобы реализовать проверку даты :

function makeAppointment (agent) {
        // Use the Dialogflow's date and time parameters to create Javascript Date instances, 'dateTimeStart' and 'dateTimeEnd',
        // which are used to specify the appointment's time.
        const appointmentDuration = 1;// Define the length of the appointment to be one hour.

        const dateTimeStart = convertParametersDate(agent.parameters.date, agent.parameters.time,timeZoneOffset);
        const dateTimeEnd = addHours(dateTimeStart, appointmentDuration);
        const appointmentTimeString = getLocaleTimeString(dateTimeStart);
        const appointmentDateString = getLocaleDateString(dateTimeStart);
        // Check the availability of the time slot and set up an appointment if the time slot is available on the calendar

       //here the new part:
        var now = new Date();
        var openhour = 9;
        var closehour = 16;
        if (dateTimeStart.getTime() < now.getTime() || dateTimeStart.getHours() < openhour || dateTimeEnd.getHours()> closehour){
          agent.add(` ?Sorry check other date`);
        } else {
        return createCalendarEvent(dateTimeStart, dateTimeEnd).then(() => {
            agent.add(`Done ?`);
        }).catch(() => {
            agent.add(` ?Sorry check other date`);
        });
      }
    }

Методами, используемыми для реализации проверки, являются Javascript Методы объекта Date, в частности getTime () , getHours () и новая дата () .

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