import{request,GraphQLClient}from'graphql-request'// Run GraphQL queries/mutations using a static functionrequest(endpoint,query,variables).then((data)=>console.log(data))// ... or create a GraphQL client instance to send requestsconstclient=newGraphQLClient(endpoint,{headers: {}})client.request(query,variables).then((data)=>console.log(data))
You can also use the single argument function variant:
If you want to set headers after the GraphQLClient has been initialised, you can use the setHeader() or setHeaders() functions.
import{GraphQLClient}from'graphql-request'constclient=newGraphQLClient(endpoint)// Set a single headerclient.setHeader('authorization','Bearer MY_TOKEN')// Override all existing headersclient.setHeaders({authorization: 'Bearer MY_TOKEN',anotherheader: 'header_value'})
Set endpoint
If you want to change the endpoint after the GraphQLClient has been initialised, you can use the setEndpoint() function.
It is possible to pass custom headers for each request. request() and rawRequest() accept a header object as the third parameter
import{GraphQLClient}from'graphql-request'constclient=newGraphQLClient(endpoint)constquery=gql` query getMovie($title: String!) { Movie(title: $title) { releaseDate actors { name } } }`constvariables={title: 'Inception',}constrequestHeaders={authorization: 'Bearer MY_TOKEN'}// Overrides the clients headers with the passed valuesconstdata=awaitclient.request(query,variables,requestHeaders)
Passing dynamic headers to the client
It's possible to recalculate the global client headers dynamically before each request.
To do that, pass a function that returns the headers to the headers property when creating a new GraphQLClient.
import{GraphQLClient}from'graphql-request'constclient=newGraphQLClient(endpoint,{headers: ()=>({'X-Sent-At-Time': Date.now()})})constquery=gql`
querygetCars{cars{
name
}}// Function saved in the client runs and calculates fresh headers before each requestconstdata=awaitclient.request(query)
import{request,gql}from'graphql-request'asyncfunctionmain(){constendpoint='https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr'constquery=gql` { Movie(title: "Inception") { releaseDate actors { fullname # "Cannot query field 'fullname' on type 'Actor'. Did you mean 'name'?" } } } `try{constdata=awaitrequest(endpoint,query)console.log(JSON.stringify(data,undefined,2))}catch(error){console.error(JSON.stringify(error,undefined,2))process.exit(1)}}main().catch((error)=>console.error(error))
请发表评论