DIalogflow-Fullfilment GraphQL - PullRequest
       5

DIalogflow-Fullfilment GraphQL

0 голосов
/ 09 апреля 2020

Кто-нибудь здесь реализовал полное выполнение потока диалога на сервере graphql? Как вы справляетесь с этим? Вы рассматриваете выполнение как мутацию или реализуете его как отдельную конечную точку отдыха? Я могу выставить свой локальный сервер с помощью ngrok, но я не уверен, как настроить go на выполнение. Я отделил свой код DF от кода GraphQL так, что модуль DF предоставляет только поток, обрабатывающий события и текстовые запросы, в поток диалога:

// df/index.js
module.exports={

text: ()=>{
self=module.exports
// ...

return self.getResult()
},

event: ()=>{
self=module.exports
// ...

return self.getResult()
},

getResult:()=>{
//...

return{
query,
response,
cards,
quickReply
}
}
} 

Затем это передается через контекст graphQL и предоставляется боту. .resolver. js модуль, в котором соответствующие мутации для обработки текста и событий определены как показано

// schema/resolvers/bot.resolver.js
module.exports={
      // Mutation
      Mutation:{
        sendText: (parent,args,context) => {
          const {df}=context;


          const response =  df.text(args);
          return response;
        },

        sendEvent: (parent,args,context) => {
          const {df}=context;


          const response =  df.event(args);
          return response;
        },

      },

  };

Соответствующие типы graphQL определены в bot.type. js как показано:

const { gql } = require('apollo-server-express');

module.exports=gql`
type Course {
  id:ID
  header:String!
  image:String!
  description:String
  price:String!
}

type Option {
  value:String!
  payload:String
  link:String
}

type QuickReply {
  text:String!
  options:[Option!]!
}

type Bot {
  query:String!,
  response:String!
  cards:[Course!]
  quickReply:QuickReply
}

type Mutation {
  sendText(text: String!, userId:String!, parameters:String): Bot!
  sendEvent(name: String!,  userId:String!, parameters:String): Bot!
}
`;

Пожалуйста, сообщите, где я могу написать приведенный ниже код, который настраивает выполнение диалогового потока

код настройки выполнения диалогового потока

1 Ответ

0 голосов
/ 22 апреля 2020

ur Удивительно, но это было так же просто, как написать это в качестве промежуточного программного обеспечения на моем GraphQl API.

// import the required dependencies
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const { ApolloServer,  } = require('apollo-server-express');

// do not forget your graphQl schema definition
const schema = require('./schema');

// we shall also need to import the data source. 
// I will assume an array for our data source  defined as below

const models ={
Course:[
{id:1, name:'Chatbots',}
{id:2, name:'React',}
{id:3, name:'Express',}
{id:4, name:'GraphQl',}
],
Book:[
{id:1, title:'Fundermentals in Chatbots',courseId:1},
{id:2, title:'Express for Newbies',courseId:3},
{id:3, title:'Advanced AI on Bots',courseId:1},
{id:4, title:'GraphQl Simplified',courseId:4},
]
}

// Import the WebhookClient class
const { WebhookClient } = require('dialogflow-fulfillment');



// Do the graphQl gymnastics ... I find Apollo server 2 just on point.

const server = new ApolloServer(schema);

const path='/'
const port = process.env.PORT || 4000
const app = express(); // we will merge express with the Apollo server 2

// do the express gymnastics ...
app.use(path,cors(),bodyParser.json(),)

// **IT'S HERE THAT WE DEFINE DIALOG FLOW'S WEB-HOOK AS A MIDDLEWARE**
app.use('/webhook', async (request,response,next)=>{


   const agent = new WebhookClient({ request, response });

   const {parameters}=request.body.queryResult;
   const course =parameters['course'];

    // ... do the database logic here ... 
     // eg get the title of available text books for the particular course
        // I will assume
       const {id} = await models.Course.find(({name})=>name ===course)
    const books = await model.Book.filter(({courseId})=>courseId===id)
        const booksTitleArray = books.map(({title})=>title)
        let titleList = booksTitle.Array.toString(); 
        titleList.replace(',', ' , ') // put space btn comas
        titleList.replace(/\,(?=[^,]*$)/, "and")
   let intentMap = new Map();

   const recommendBooks courses=>{
      agent.add(`For ${course}, We use the following books: ${titleList}`);
    };


   intentMap.set('course.recommended.books',recommendBooks);

   agent.handleRequest(intentMap);
   next();
 })

server.applyMiddleware({ app, path });

app.listen(port,()=>{
   console.log( `Apollo Server Running on http://localhost:${port}`)
})

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

Ребята, мы не должны забывать о магии ngrok c, если мы проводим тестирование с локального хоста ?

...