Created
June 15, 2024 11:31
-
-
Save ShivamJoker/7aa379b49429acd907f9952a6682e6c0 to your computer and use it in GitHub Desktop.
AWS Appsync GraphQL fetcher using HTTP fetch
This file contains hidden or 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
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