Last active
July 10, 2020 02:06
-
-
Save smcalilly/cbd80a28c96125647b2083ac79875c7e to your computer and use it in GitHub Desktop.
A basic GraphQL service for AWS AppSync with Okta authentication
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 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) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a blog post that explains this code: https://dev.to/smcalilly/a-graphql-service-for-aws-appsync-and-okta-28i3