37 lines
937 B
TypeScript
37 lines
937 B
TypeScript
import { ApolloClient, InMemoryCache, createHttpLink, from } from '@apollo/client';
|
||
import { setContext } from '@apollo/client/link/context';
|
||
|
||
const TOKEN_KEY = 'auth_token';
|
||
|
||
const httpLink = createHttpLink({
|
||
uri: "http://127.0.0.1:3050/graphql",
|
||
});
|
||
|
||
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,
|
||
}
|
||
};
|
||
});
|
||
|
||
export const createApolloClient = () => {
|
||
return new ApolloClient({
|
||
link: from([authLink, httpLink]),
|
||
cache: new InMemoryCache(),
|
||
});
|
||
};
|