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

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

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。

猜你喜欢

转载自blog.csdn.net/onwingsofsong/article/details/82353325