Skip to content

enhancement: Add support for custom connectionParams in websocket initializer #650

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: v5
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/runtime/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ApolloClients, provideApolloClients } from '@vue/apollo-composable'
import { ApolloClient, ApolloLink, createHttpLink, InMemoryCache, split } from '@apollo/client/core'
import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
import { setContext } from '@apollo/client/link/context'
import type { ClientOptions } from 'graphql-ws'
import type { ClientConfig, ErrorResponse } from '../types'
import createRestartableClient from './ws'
import { useApollo } from './composables'
Expand Down Expand Up @@ -76,11 +77,24 @@ export default defineNuxtPlugin((nuxtApp) => {
...clientConfig.wsLinkOptions,
url: clientConfig.wsEndpoint,
connectionParams: async () => {
let connectionParams: ClientOptions['connectionParams'] = clientConfig.wsLinkOptions?.connectionParams || {}

// if connection params is a function, call it
if (typeof connectionParams === 'function') {
connectionParams = await connectionParams()
}

const auth = await getAuth()
if (!auth) { return connectionParams }

if (!auth) { return }
// merge connection headers with the auth header
const headers = {
[clientConfig.authHeader!]: auth,
...(connectionParams?.headers || {})
}

return { headers: { [clientConfig.authHeader!]: auth } }
// merge existing connection params with headers
return { ...connectionParams, headers }
}
})

Expand Down
2 changes: 1 addition & 1 deletion src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export type ClientConfig = {
* Provide additional configuration for the `GraphQLWsLink`.
* See https://github.com/enisdenjo/graphql-ws/blob/master/docs/interfaces/client.ClientOptions.md
**/
wsLinkOptions?: Omit<ClientOptions, 'url' | 'connectionParams'>;
wsLinkOptions?: Omit<ClientOptions, 'url'>;

/**
* Specify a websocket endpoint to be used for subscriptions.
Expand Down