Skip to content

Instantly share code, notes, and snippets.

@ShivamJoker
Created June 15, 2024 11:31
Show Gist options
  • Save ShivamJoker/7aa379b49429acd907f9952a6682e6c0 to your computer and use it in GitHub Desktop.
Save ShivamJoker/7aa379b49429acd907f9952a6682e6c0 to your computer and use it in GitHub Desktop.
AWS Appsync GraphQL fetcher using HTTP fetch
export const createGqlClient = (authToken: string, API: string) => (async (query) => {
if (!authToken) {
throw "Invalid Auth Token passed";
}
if (!API) {
throw "Invalid API URL passed";
}
const response = await fetch(`https://${API}/graphql`, {
body: JSON.stringify({ query }),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: authToken,
},
});
if (response.status === 401) {
// handle unauthorized request
}
}
if (!response.ok) {
return new Promise((resolve, reject) => {
response
.text()
.then((text) => {
try {
reject(JSON.parse(text));
} catch (err) {
reject(text);
}
})
.catch(reject);
});
}
const json = await response.json();
return json.data;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment