Skip to content

Instantly share code, notes, and snippets.

@paulswail
Last active April 6, 2022 11:29
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 paulswail/c121aef415e404b4f893b8a2d30ae3c5 to your computer and use it in GitHub Desktop.
Save paulswail/c121aef415e404b4f893b8a2d30ae3c5 to your computer and use it in GitHub Desktop.
AppSync GraphQL CodeGenerator Config with Lambda resolver types, Nodejs operation functions and React hooks
// frontend lib module which is injected into the codegen'd hooks
import { getAuthToken } from './auth'
export const API_URL = process.env.REACT_APP_API_URL!
/**
* Custom fetcher used by codegen'd hooks to first load auth token, then make the fetch request.
*/
export const fetcher = <TData, TVariables>(query: string, variables?: TVariables) => {
return async (): Promise<TData> => {
console.log('fetcher: API_URL', API_URL)
const authToken = await getAuthToken()
const res = await fetch(API_URL, {
method: 'POST',
// ...{ credentials: 'include' },
headers: {
...(authToken && { Authorization: authToken }),
},
body: JSON.stringify({ query, variables }),
})
const json = await res.json()
if (json.errors) {
const { message } = json.errors[0]
throw new Error(message)
}
return json.data
}
}
# file to tell the generator about AppSync-specific scalars
scalar AWSDate
scalar AWSTime
scalar AWSDateTime
scalar AWSTimestamp
scalar AWSEmail
scalar AWSJSON
scalar AWSURL
scalar AWSPhone
scalar AWSIPAddress
schema:
- 'services/graphql-api/src/schemas/appsync.graphql'
- 'services/graphql-api/src/schemas/schema.api.graphql'
overwrite: true
hooks:
afterAllFileWrite:
- prettier --write
config:
maybeValue: 'T | null | undefined'
scalars:
AWSJSON: string
AWSDate: string
AWSTime: string
AWSDateTime: string
AWSTimestamp: number
AWSEmail: string
AWSURL: string
AWSPhone: string
AWSIPAddress: string
generates:
# Generate types and resolver signatures for use in the backend Lambda handlers
services/graphql-api/src/__generated__/api-types.ts:
config:
useIndexSignature: true
makeResolverTypeCallable: true
contextType: 'aws-lambda#Context'
plugins:
- typescript
- typescript-resolvers
# Generate operations for use in the backend E2E tests
services/graphql-api/tests/__generated__/api-operations.ts:
documents:
- services/graphql-api/tests/test-cases/e2e/**/*.graphql
plugins:
- typescript
- typescript-operations
- typescript-graphql-request
# Generate types and React hooks for the frontend web app
services/webapp/src/__generated__/api-types-and-hooks.tsx:
documents:
- services/webapp/graphql/operations/*.graphql
plugins:
- typescript
- typescript-operations
- typescript-react-query
config:
errorType: 'any'
fetcher:
func: '../lib/api-client#fetcher'
isReactHook: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment