Created
August 19, 2018 23:19
-
-
Save zzdjk6/162e8df2e3f56faec34cb43b5402b886 to your computer and use it in GitHub Desktop.
Persisted GraphQL Queries with axios and SilverStripe 4: after
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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