55 lines
1.6 KiB
TypeScript
55 lines
1.6 KiB
TypeScript
import { ApolloClient, InMemoryCache, createHttpLink, from, split } from '@apollo/client';
|
||
import { getMainDefinition } from '@apollo/client/utilities';
|
||
import { setContext } from '@apollo/client/link/context';
|
||
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
|
||
import { createClient } from 'graphql-ws';
|
||
|
||
|
||
const TOKEN_KEY = 'auth_token';
|
||
|
||
const httpLink = createHttpLink({
|
||
uri: process.env.GRAPHQL_BACKEND_URL || 'http://localhost:3050/graphql',
|
||
});
|
||
|
||
const wsLink = new GraphQLWsLink(createClient({
|
||
// url: "ws://127.0.0.1:3050/ws",
|
||
url: process.env.GRAPHQL_BACKEND_URL?.replace('/graphql', '/ws')?.replace('http://', 'ws://') || 'ws://localhost:3050/ws',
|
||
}));
|
||
|
||
const authLink = setContext((_, { headers }) => {
|
||
// 从 localStorage 获取 token
|
||
const token = typeof window !== 'undefined' ? localStorage.getItem(TOKEN_KEY) : null;
|
||
|
||
// 如果有 token,添加到 headers 中
|
||
if (token) {
|
||
return {
|
||
headers: {
|
||
...headers,
|
||
authorization: `Bearer ${token}`,
|
||
}
|
||
};
|
||
}
|
||
|
||
// 如果没有 token,返回原始 headers
|
||
return {
|
||
headers: {
|
||
...headers,
|
||
}
|
||
};
|
||
});
|
||
|
||
const link = split(
|
||
({ query }) => {
|
||
const def = getMainDefinition(query);
|
||
return def.kind === 'OperationDefinition' && def.operation === 'subscription';
|
||
},
|
||
wsLink, // 如果是 subscription,则走 ws
|
||
from([authLink, httpLink])
|
||
);
|
||
|
||
export const createApolloClient = () => {
|
||
return new ApolloClient({
|
||
link,
|
||
cache: new InMemoryCache(),
|
||
});
|
||
};
|