美文网首页
graphql 在sub query 子查询中获取header中

graphql 在sub query 子查询中获取header中

作者: onwingsofsong | 来源:发表于2018-09-24 09:57 被阅读10次

    以下内容基于graphql-yoga,它是基于apollo graphql server,并整合了

    graphql-subscriptions/subscriptions-transport-ws: GraphQL subscriptions server

    graphql.js/graphql-tools: GraphQL engine & schema helpers

    graphql-playground: Interactive GraphQL IDE

    graphql client端将token添加到header中发送到server端,然鹅在graphql server端的子查询中,无法从context中获取任何信息。因为client端发送请求,只有父查询中有context。

    以 database与datatable的关系为例:

    type Query {

    database(id: Int!):Database

    datatables:[DataTable!]!

    }

    type Database{

    id: Int

    name: String

    datatable_list:[DataTable]

    }

    type DataTable{

    id: Int

    name: String

    }

    父查询获取token的方法是:

    const datatable=(root, { id },context)=>{

        token=context.request.get('token')

        return fetch(`${baseURL}/datatable/${id}`,{headers: {

            'Content-Type': 'application/json',

            'Accept': 'application/json',

            'wx-token':token,

        }}).then(res => res.json())}

    其子查询获取token的方法是:

    Database:{

        async datatable_list({ id },context){

            return await fetch(`${baseURL}/database/${id}/datatables`,{headers: {

                'Content-Type': 'application/json',

                'Accept': 'application/json',

                'wx-token':context.request.get('token'),

            }}).then(res => res.json())}

    },

    通过异步调用,可以共享父查询的context。

    相关文章

      网友评论

          本文标题:graphql 在sub query 子查询中获取header中

          本文链接:https://www.haomeiwen.com/subject/afucoftx.html