awslabs / aws-mobile-appsync-sdk-js

JavaScript library files for Offline, Sync, Sigv4. includes support for React Native
Apache License 2.0
920 stars 266 forks source link

[aws-appsync-auth-link]Got an error `TypeError: forward is not a function` when querying #600

Closed yaquawa closed 3 years ago

yaquawa commented 3 years ago

Here is my code:

import { store } from './store'
import awsConfig from './aws-exports'
import { AUTH_TYPE, createAuthLink } from 'aws-appsync-auth-link'
import {
    ApolloLink,
    ApolloClient,
    InMemoryCache,
    createHttpLink,
} from '@apollo/client'
import { createSubscriptionHandshakeLink } from 'aws-appsync-subscription-link'

export function createApolloClient(apolloLink: ApolloLink) {
    const cache = new InMemoryCache()

    return new ApolloClient({
        link: apolloLink,
        cache,
    })
}

export function createAppSyncApolloClient() {
    const currentSession = store.state.userModule.currentSession
    const url = awsConfig.aws_appsync_graphqlEndpoint
    const region = awsConfig.aws_appsync_region
    const auth = {
        type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS as 'AMAZON_COGNITO_USER_POOLS',
        jwtToken: currentSession?.getIdToken()?.getJwtToken(),
    }
    const publicApiKeyAuthLink = createAuthLink({
        url,
        region,
        auth: {
            type: AUTH_TYPE.API_KEY as 'API_KEY',
            apiKey: awsConfig.aws_appsync_apiKey,
        },
    })

    const apolloLink = currentSession
        ? ApolloLink.from([
              publicApiKeyAuthLink,
              createAuthLink({ url, region, auth }),
              createSubscriptionHandshakeLink({
                  url,
                  region,
                  auth,
              }),
          ])
        : publicApiKeyAuthLink

    return createApolloClient(apolloLink)
}

export function createWpApolloClient() {
    return createApolloClient(
        createHttpLink({
            uri: `${location.origin}/graphql`,
        })
    )
}

const client = createAppSyncApolloClient()
client.query({ query: gql('{foobar}') }) // this gives the error

// createWpApolloClient() was fine which doesn't use this lib

the error message:

Uncaught (in promise) TypeError: forward is not a function
    at auth-link.js:127
    at step (auth-link.js:57)
    at Object.next (auth-link.js:38)
    at fulfilled (auth-link.js:29)
yaquawa commented 3 years ago

Found the answer at https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/473, you need to append a terminal http link after createAuthLink.