GraphQL API
Client Implementation
GraphQL client libraries and setup
Client Implementation
JavaScript/TypeScript
Using fetch:
async function graphqlRequest(query, variables = {}) {
const response = await fetch('https://your-tenant.api.myxclade.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${yourJwtToken}`,
'x-graphql-request': 'true', // CSRF protection
},
body: JSON.stringify({
query,
variables,
}),
});
const result = await response.json();
if (result.errors) {
throw new Error(result.errors[0].message);
}
return result.data;
}
// Usage
const products = await graphqlRequest(`
query GetProducts($limit: Int) {
products(limit: $limit) {
products {
id
title
thumbnail
}
}
}
`, { limit: 10 });Using Apollo Client
import { ApolloClient, InMemoryCache, gql, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({
uri: 'https://your-tenant.api.myxclade.com/graphql',
});
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('jwt_token');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
'x-graphql-request': 'true',
}
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
// Usage
const GET_PRODUCTS = gql`
query GetProducts($limit: Int) {
products(limit: $limit) {
products {
id
title
thumbnail
}
}
}
`;
const { data } = await client.query({
query: GET_PRODUCTS,
variables: { limit: 10 },
});Using urql
import { createClient, cacheExchange, fetchExchange } from 'urql';
const client = createClient({
url: 'https://your-tenant.api.myxclade.com/graphql',
exchanges: [cacheExchange, fetchExchange],
fetchOptions: () => {
const token = localStorage.getItem('jwt_token');
return {
headers: {
authorization: token ? `Bearer ${token}` : '',
'x-graphql-request': 'true',
},
};
},
});
// Usage
const GetProductsQuery = `
query GetProducts($limit: Int) {
products(limit: $limit) {
products { id title }
}
}
`;
const result = await client.query(GetProductsQuery, { limit: 10 });