mosaicmap/lib/apollo-client.ts
2025-08-18 00:03:16 +08:00

55 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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(),
});
};