railbird-gql/graphql/client.tsx

79 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-02-03 18:23:46 -07:00
import React, {
ReactNode,
createContext,
useContext,
useState,
useMemo,
} from "react";
2024-01-06 23:48:47 -07:00
import {
ApolloClient,
2024-02-03 18:10:58 -07:00
ApolloLink,
2024-01-06 23:48:47 -07:00
InMemoryCache,
ApolloProvider,
HttpLink,
from,
} from "@apollo/client";
import { API_URI } from "@env";
2024-01-06 23:58:54 -07:00
type Props = {
children: ReactNode;
};
2024-02-03 18:23:46 -07:00
export const AuthHeaderContext = createContext<
| {
authHeader: { key: string; value: string };
setAuthHeader: React.Dispatch<
React.SetStateAction<{ key: string; value: string }>
>;
}
| undefined
>(undefined);
2024-02-03 18:10:58 -07:00
// Hook to use the auth header context
2024-02-03 18:23:46 -07:00
export const useAuthHeader = () => {
const context = useContext(AuthHeaderContext);
if (!context) {
throw new Error("useAuthHeader must be used within a ClientProvider");
}
return context;
};
2024-02-03 18:10:58 -07:00
2024-02-03 18:23:46 -07:00
export const ClientProvider: React.FC<Props> = ({ children }) => {
const [authHeader, setAuthHeader] = useState({ key: "", value: "" });
2024-01-06 23:58:54 -07:00
const httpLink = new HttpLink({
2024-02-03 18:23:46 -07:00
uri: API_URI || "https://api-dev.railbird.ai/graphql",
2024-01-06 23:58:54 -07:00
});
2024-01-14 17:38:08 -07:00
const cache = new InMemoryCache({});
2024-01-06 23:48:47 -07:00
2024-02-03 18:10:58 -07:00
const authMiddleware = new ApolloLink((operation, forward) => {
const { key, value } = authHeader;
if (key && value) {
operation.setContext({
headers: {
[key]: value,
},
});
}
return forward(operation);
2024-01-06 23:58:54 -07:00
});
2024-01-06 23:48:47 -07:00
2024-02-03 18:10:58 -07:00
// We use useMemo to avoid recreating the client on every render
const client = useMemo(
() =>
new ApolloClient({
2024-02-03 18:23:46 -07:00
// Chain the middleware with the httpLink
link: from([authMiddleware, httpLink]),
2024-02-03 18:10:58 -07:00
cache: new InMemoryCache(),
}),
[authHeader],
);
2024-02-03 18:23:46 -07:00
return (
<AuthHeaderContext.Provider value={{ authHeader, setAuthHeader }}>
<ApolloProvider client={client}>{children}</ApolloProvider>
</AuthHeaderContext.Provider>
);
2024-01-06 23:48:47 -07:00
};