DIalogflow-Fulfillment GraphQL

DIalogflow-Fullfilment GraphQL

这里有人在 graphql 服务器上实现了对话流实现吗?你是怎么处理的?您是将 fulfillment 作为突变来处理,还是将其作为单独的 rest 端点来实现? 我可以使用 ngrok 公开我的本地服务器,但我不确定如何设置实现。我已将我的 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 上下文传递并暴露给 bot.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!
}
`;

请告知我在哪里可以编写下面的代码来设置对话流实现

dialogflow-fulfillment setup code

令人惊讶的是,它就像在我的 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}`)
})

我想写一篇关于这个的文章,因为我几乎到处都在徒劳地寻求帮助。如果我有时间这样做,我会在评论中提供。

伙计们,如果我们从本地主机进行测试,我们不应该忘记 ngrok 魔法