Gomah / nuxt-graphql-request

Easy Minimal GraphQL client integration with Nuxt.js.
https://nuxt-graphql-request.vercel.app
MIT License
196 stars 16 forks source link

Session headers #29

Closed nonlinearcom closed 3 years ago

nonlinearcom commented 3 years ago

Hi, this is more a question than an issue... is it possible to replicate this type of functionality from Apollo in nuxt-graphql-request?

import { HttpLink } from 'apollo-link-http'
import { ApolloLink } from 'apollo-link'

const httpLink = new HttpLink({
    uri: process.env.GQL_ENDPOINT,
})

// Middleware operation
// If we have a session token in localStorage, add it to the GraphQL request as a Session header.

export const middleware = new ApolloLink((operation, forward) => {
    const session = localStorage.getItem('woo-session')
    if (session && session.length > 0) {
        operation.setContext(({ headers = {} }) => ({
            headers: {
                'woocommerce-session': `Session ${session}`,
            },
        }))
    }
    return forward(operation)
})

// Afterware operation
// This catches the incoming session token and stores it in localStorage, for future GraphQL requests.

export const afterware = new ApolloLink((operation, forward) => {
    return forward(operation).map((response) => {
        const context = operation.getContext()
        const { response: { headers } } = context
        const session = headers.get('woocommerce-session')

        if (session) {
            if (localStorage.getItem('woo-session') !== session) {
                localStorage.setItem('woo-session', headers.get('woocommerce-session') )
            }
        }
        return response
    })
})

export default function () {
    return {
        // default 'apollo' definition
        defaultOptions: {
            $query: {
                loadingKey: 'loading',
                fetchPolicy: 'cache-and-network',
            },
        },
        defaultHttpLink: false,
        link: middleware.concat(afterware.concat(httpLink)),
        httpEndpoint: process.env.graphqlUrl,
        fetchOptions: {
            mode: 'cors',
        },
        httpLinkOptions: {
            credentials: 'include'
        },
    }
}

I'm asking because since I found this module I try to avoid using Apollo as much as possible, but in this case I'm not sure if this kind of request is doable with nuxt-graphql-request. 🤔

Thanks in advance!