Skip to content

Instantly share code, notes, and snippets.

@smcalilly
Last active July 10, 2020 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smcalilly/cbd80a28c96125647b2083ac79875c7e to your computer and use it in GitHub Desktop.
Save smcalilly/cbd80a28c96125647b2083ac79875c7e to your computer and use it in GitHub Desktop.
A basic GraphQL service for AWS AppSync with Okta authentication
import AWSAppSyncClient, { AUTH_TYPE } from 'aws-appsync';
import gql from 'graphql-tag';
import * as queries from './queries';
import * as mutations from './mutations';
function configureAppSyncClient() {
const token = JSON.parse(localStorage.getItem('okta-token-storage'))
const config = JSON.parse(localStorage.getItem('config'))
const client = new AWSAppSyncClient({
url: config['awsAppsyncGraphqlEndpoint'],
region: config['awsRegion'],
auth: {
type: AUTH_TYPE.OPENID_CONNECT,
jwtToken: token.idToken.idToken,
},
disableOffline: true
});
return client;
}
export async function query(operation, args) {
const client = configureAppSyncClient()
const query = queries[operation];
return await client.query({
query: gql(query),
variables: { ...args }
}).then(({ data }) => {
return data[operation]
})
}
export async function mutation(operation, args) {
const client = configureAppSyncClient();
const mutation = mutations[operation]
return await client.mutate({
mutation: gql(mutation),
variables: { ...args }
})
}
// You can use the functions in a React application like this
useEffect(() => {
query('getMessages')
.then((messages) => {
console.log(messages)
setMessages(messages)
})
.catch((error) => {
console.log('error', error)
setError(true)
})
})
@smcalilly
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment