graphql 在sub query 子查詢中獲取header中的token
阿新 • • 發佈:2018-10-31
以下內容基於graphql-yoga,它是基於apollo graphql server,並整合了
graphql-subscriptions
/subscriptions-transport-ws
: GraphQL subscriptions servergraphql.js
/graphql-tools
: GraphQL engine & schema helpersgraphql-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。