Skip to content

Instantly share code, notes, and snippets.

@zzdjk6
Created August 19, 2018 23:19
Show Gist options
  • Save zzdjk6/162e8df2e3f56faec34cb43b5402b886 to your computer and use it in GitHub Desktop.
Save zzdjk6/162e8df2e3f56faec34cb43b5402b886 to your computer and use it in GitHub Desktop.
Persisted GraphQL Queries with axios and SilverStripe 4: after
import axios from "axios";
import StorageService from "./StorageService";
import persistedQueryMapping from "../graphql/mapping.json";
import compress from "graphql-query-compress";
export default class AxiosService {
static getInstance(query, variables) {
let headers = {};
const user = StorageService.readUser();
if (user && user.Token) {
headers["Authorization"] = "Bearer " + user.Token;
}
// webpack graphql loader will trim "query" at the beginning
let compressedQuery = compress(query);
if (compressedQuery.startsWith("{")) {
compressedQuery = "query" + compressedQuery;
}
let data = {
query: compressedQuery,
variables: variables
};
if (persistedQueryMapping[compressedQuery]) {
delete data.query;
data.id = persistedQueryMapping[compressedQuery];
}
return axios.create({
url: "/graphql",
method: "post",
data: data,
headers: headers
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment