mosaicmap/lib/apollo-client.ts
2025-07-28 07:25:32 +08:00

37 lines
937 B
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 } 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(),
});
};