Introduction to graphql-request
graphql-request is a simple and flexible JavaScript library for making GraphQL queries and mutations. It provides a lightweight and minimal API to send GraphQL requests, making it the perfect choice for developers looking for an easy way to interact with GraphQL servers.
Basic Usage
const { request, gql } = require('graphql-request')
const query = gql`
{
user(id: "1") {
id
name
}
}
`
request('https://api.example.com/graphql', query).then((data) => console.log(data))
Setting Headers
const { request, gql } = require('graphql-request')
const query = gql`
{
user(id: "1") {
id
name
}
}
`
const headers = {
authorization: 'Bearer MY_TOKEN',
}
request({
url: 'https://api.example.com/graphql',
document: query,
requestHeaders: headers,
}).then((data) => console.log(data))
Handling Errors
const { request, gql } = require('graphql-request')
const query = gql`
{
nonExistentField
}
`
request('https://api.example.com/graphql', query)
.then((data) => console.log(data))
.catch((error) => console.error(error))
Mutations
const { request, gql } = require('graphql-request')
const mutation = gql`
mutation {
createUser(name: "John") {
id
}
}
`
request('https://api.example.com/graphql', mutation).then((data) => console.log(data))
Extending the Client
const { GraphQLClient, gql } = require('graphql-request')
const client = new GraphQLClient('https://api.example.com/graphql', {
headers: {
authorization: 'Bearer MY_TOKEN',
},
})
const query = gql`
{
user(id: "1") {
id
name
}
}
`
client.request(query).then((data) => console.log(data))
Example Application
Let’s create a small application that uses graphql-request to interact with a GraphQL API.
const { GraphQLClient, gql } = require('graphql-request')
const client = new GraphQLClient('https://api.example.com/graphql', {
headers: {
authorization: 'Bearer MY_TOKEN',
},
})
const getUserById = async (id) => {
const query = gql`
query ($id: ID!) {
user(id: $id) {
id
name
email
}
}
`
return await client.request(query, { id })
}
const createUser = async (name, email) => {
const mutation = gql`
mutation ($name: String!, $email: String!) {
createUser(name: $name, email: $email) {
id
name
email
}
}
`
return await client.request(mutation, { name, email })
}
// Usage examples
getUserById("1").then((user) => console.log(user))
createUser("Jane Doe", "jane@example.com").then((user) => console.log(user))
With these simple steps and examples, you can leverage graphql-request in your own applications to efficiently query and mutate data with GraphQL.
Hash: fe2ba32927e7dc919a533b63177e7c37beebc2ee1edddfb5b6068f2919ff654e