@apollo/client#ApolloClient TypeScript Examples
The following examples show how to use
@apollo/client#ApolloClient.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: apolloClient.ts From next-page-tester with MIT License | 6 votes |
export function addApolloState<P>(
client: ApolloClient<NormalizedCacheObject>,
pageProps: GetStaticPropsResult<P>
) {
// @ts-expect-error just checking
if (pageProps.props) {
// @ts-expect-error injected prop
pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract();
}
return pageProps;
}
Example #2
Source File: apollo.ts From storefront with MIT License | 6 votes |
export default function createClient({
initialState = {},
}: { initialState?: NormalizedCacheObject } = {}) {
if (apolloClient == null) {
apolloClient = new ApolloClient({
// eslint-disable-next-line unicorn/prefer-spread
link: errorLink.concat(
// eslint-disable-next-line unicorn/prefer-spread
authLink.concat(
// eslint-disable-next-line unicorn/prefer-spread
afterware.concat(
createHttpLink({
uri: process.env.GRAPHQL_URL,
credentials: 'include',
}),
),
),
),
cache: new InMemoryCache({ possibleTypes: introspectionResult.possibleTypes }).restore(
initialState,
),
});
}
return apolloClient;
}
Example #3
Source File: withApollo.ts From lireddit with MIT License | 6 votes |
createClient = (ctx: NextPageContext) =>
new ApolloClient({
uri: process.env.NEXT_PUBLIC_API_URL as string,
credentials: "include",
headers: {
cookie:
(typeof window === "undefined"
? ctx?.req?.headers.cookie
: undefined) || "",
},
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
posts: {
keyArgs: [],
merge(
existing: PaginatedPosts | undefined,
incoming: PaginatedPosts
): PaginatedPosts {
return {
...incoming,
posts: [...(existing?.posts || []), ...incoming.posts],
};
},
},
},
},
},
}),
})
Example #4
Source File: apolloClient.tsx From nextjs-hasura-boilerplate with MIT License | 6 votes |
createApolloClient = (token: string) => {
const ssrMode = typeof window === "undefined";
const link = !ssrMode
? split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
createWSLink(token),
createHttpLink(token)
)
: createHttpLink(token);
return new ApolloClient({ ssrMode, link, cache: new InMemoryCache() });
}
Example #5
Source File: with-graphql.tsx From nextjs-strapi-boilerplate with MIT License | 6 votes |
WithGraphQL = ({
session,
children,
}: {
session: session;
children: ReactNode;
}) => {
const token = session?.jwt?.toString();
const client = new ApolloClient({
uri:
`${process.env.NEXT_PUBLIC_API_URL}/graphql` ||
"http://localhost:1337/graphql",
credentials: "same-origin",
cache: new InMemoryCache(),
headers: {
authorization: `Bearer ${token}`,
},
});
return <ApolloProvider client={client}>{children}</ApolloProvider>;
}
Example #6
Source File: ChatMessages.test.tsx From glific-frontend with GNU Affero General Public License v3.0 | 6 votes |
test('Collection: if cache', async () => {
cache.writeQuery(collection);
const client = new ApolloClient({
cache: cache,
assumeImmutableResults: true,
});
const chatMessagesWithCollection = (
<ApolloProvider client={client}>
<MockedProvider mocks={[...CONVERSATION_MOCKS, ...mocksWithConversation]}>
<ChatMessages collectionId="5" />
</MockedProvider>
</ApolloProvider>
);
const { getByTestId } = render(chatMessagesWithCollection);
// need to check why we click this
// await waitFor(() => {
// fireEvent.click(getByTestId('jumpToLatest'));
// });
});
Example #7
Source File: index.ts From fullstack-starterkit with MIT License | 6 votes |
function configureApolloClient(config: Config): ApolloClient<NormalizedCacheObject> {
const httpLink = new HttpLink({ uri: config.endpoints.https });
const wsLink = new WebSocketLink({
uri: config.endpoints.wss,
options: { reconnect: true }
});
const link = split(
({ query }) => {
const definition = getMainDefinition(query);
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
},
wsLink,
httpLink
);
const client = new ApolloClient({
link: ApolloLink.from([
onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
);
}
if (networkError) {
console.log(`[Network error]: ${networkError}`);
}
}),
link
]),
cache: new InMemoryCache()
});
return client;
}
Example #8
Source File: nextApollo.ts From liferay-grow with MIT License | 6 votes |
function createApolloClient() {
const Authorization = getToken();
return new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
allPosts: concatPagination(),
},
keyFields: ['id'],
},
},
}),
link: new HttpLink({
credentials: 'same-origin',
headers: {
Authorization,
},
uri: `${baseURL}/graphql`,
}),
ssrMode: typeof window === 'undefined',
});
}
Example #9
Source File: apolloClient.ts From next-page-tester with MIT License | 6 votes |
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: new HttpLink({
uri: 'https://nextjs-graphql-with-prisma-simple.vercel.app/api', // Server URL (must be absolute)
credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
fetch,
}),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
allPosts: concatPagination(),
},
},
},
}),
});
}
Example #10
Source File: CGraphQLClient.ts From Cromwell with MIT License | 6 votes |
/** @internal */
private async createClient() {
let doneInit: (() => void) | undefined;
this.initializePromise = new Promise<void>(done => doneInit = done);
if (isServer()) {
// If backend, try to find service secret key to make
// authorized requests to the API server.
this.serviceSecret = await getServiceSecret();
}
const cache = new InMemoryCache();
const link = createHttpLink({
uri: this.getBaseUrl(),
credentials: 'include',
fetch: this.fetch,
headers: this.serviceSecret && { 'Authorization': `Service ${this.serviceSecret}` },
});
this.apolloClient = new ApolloClient({
cache: cache,
link: link,
name: 'cromwell-core-client',
queryDeduplication: false,
defaultOptions: {
query: {
fetchPolicy: 'network-only',
},
watchQuery: {
fetchPolicy: 'cache-and-network',
},
},
});
doneInit?.();
this.initializePromise = undefined;
}
Example #11
Source File: withData.tsx From keycapsets.com with GNU General Public License v3.0 | 6 votes |
function createApolloClient() {
const isBrowser: boolean = typeof window === 'undefined';
return new ApolloClient({
ssrMode: isBrowser,
link: authLink.concat(
createUploadLink({
uri: apiUrl,
})
),
cache: new InMemoryCache(),
});
}
Example #12
Source File: client.ts From ui with GNU Affero General Public License v3.0 | 6 votes |
getClient = (): ApolloClient<NormalizedCacheObject> => {
if (!client) {
const config = getConfig() as NextConfigType
if (!config) return client
const { publicRuntimeConfig, serverRuntimeConfig } = config
client = new ApolloClient<NormalizedCacheObject>({
cache: new InMemoryCache(),
link: from([
setContext((request, context) => {
const headers: { [key: string]: string } = {}
if (process.browser) {
const access = localStorage.getItem('access')
if (access) {
headers.authorization = `Bearer ${access}`
}
}
return {
headers,
}
}),
new HttpLink({
uri: serverRuntimeConfig.endpoint || publicRuntimeConfig.endpoint,
}),
]),
})
}
return client
}
Example #13
Source File: Filters.tsx From condo with MIT License | 6 votes |
getGQLSelectFilterDropdown = (
props: ComponentProps<typeof GraphQlSearchInput>,
search: (client: ApolloClient<Record<string, unknown>>, queryArguments: string) => Promise<Array<Record<string, unknown>>>,
mode?: ComponentProps<typeof GraphQlSearchInput>['mode'],
containerStyles?: CSSProperties
) => {
return ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => {
return (
<SelectFilterContainer
clearFilters={clearFilters}
showClearButton={selectedKeys && selectedKeys.length > 0}
style={containerStyles}
>
<GraphQlSearchInput
style={GRAPHQL_SEARCH_INPUT_STYLE}
search={search}
showArrow
mode={mode}
value={selectedKeys}
onChange={(e) => {
setSelectedKeys(e)
confirm({ closeDropdown: false })
}}
{...props}
/>
</SelectFilterContainer>
)
}
}
Example #14
Source File: App.tsx From graphql-schema-registry with MIT License | 6 votes |
App = ({ api }: AppProps) => {
const config = createConfig(api);
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new HttpLink({
uri: config.grapqhlEndpoint,
credentials: 'include',
}),
});
return (
<GlobalConfigContext.Provider value={config}>
<ApolloProvider client={client}>
<Main />
</ApolloProvider>
</GlobalConfigContext.Provider>
);
}
Example #15
Source File: apolloClient.tsx From nextjs-hasura-fullstack with MIT License | 6 votes |
createApolloClient = (token: string) => {
const ssrMode = typeof window === 'undefined'
const link = !ssrMode
? split(
//only create the split in the browser
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query)
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
)
},
createWSLink(token),
createHttpLink(token),
)
: createHttpLink(token)
return new ApolloClient({ ssrMode, link, cache })
}
Example #16
Source File: withApollo.tsx From NextJS-NestJS-GraphQL-Starter with MIT License | 6 votes |
withApollo = nextWithApollo(
({ initialState, headers, ...rest }) => {
const httpLink = new HttpLink({
uri: IS_SERVER ? SERVER_API_ENDPOINT : BROWSER_API_ENDPOINT,
headers: {
...headers
},
credentials: 'include'
});
return new ApolloClient({
ssrMode: IS_SERVER,
link: httpLink,
cache: new InMemoryCache().restore(initialState || {}),
// A hack to get ctx oin the page's props on the initial render
// @ts-ignore
defaultOptions: { ...rest }
});
},
{
render: ({ Page, props }) => {
return (
<ApolloProvider client={props.apollo}>
<Page {...props} {...props.apollo.defaultOptions.ctx} />
</ApolloProvider>
);
}
}
)
Example #17
Source File: initApollo.tsx From nft-marketplace with European Union Public License 1.2 | 6 votes |
function create(initialState) {
const httpLink = new HttpLink({
uri: GRAPHQL_ENDPOINT,
credentials: 'same-origin',
});
return new ApolloClient({
connectToDevTools: process.browser,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
link: httpLink,
cache: new InMemoryCache({ possibleTypes }).restore(initialState || {}),
});
}
Example #18
Source File: index.tsx From Insomniac-NextJS-boilerplate with MIT License | 6 votes |
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: new HttpLink({
uri: process.env.NEXT_PUBLIC_API_URL, // Server URL (must be absolute)
}),
cache: new InMemoryCache(),
});
}
Example #19
Source File: client.ts From Frontend with MIT License | 6 votes |
createClient = () => {
const uri = process.env.GATSBY_GRAPHQL_ENDPOINT;
const httpLink = createHttpLink({
uri,
fetch
});
const authToken = hasWindow ? localStorage.getItem('token') : '';
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
authorization: authToken ? `Bearer ${authToken}` : ''
}
});
return forward(operation);
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache({
dataIdFromObject: (object) => {
// eslint-disable-next-line no-underscore-dangle
switch (object.__typename) {
case 'Person':
return object.uid;
default:
return defaultDataIdFromObject(object); // fall back to default handling
}
}
})
});
return client;
}
Example #20
Source File: index.ts From atlas with GNU General Public License v3.0 | 6 votes |
createApolloClient = () => {
const subscriptionLink = new WebSocketLink({
uri: QUERY_NODE_GRAPHQL_SUBSCRIPTION_URL,
options: {
reconnect: true,
reconnectionAttempts: 5,
},
})
const orionLink = new HttpLink({ uri: ORION_GRAPHQL_URL })
const batchedOrionLink = new BatchHttpLink({ uri: ORION_GRAPHQL_URL, batchMax: 10 })
const orionSplitLink = split(
({ operationName }) => {
return operationName === 'GetVideos' || operationName === 'GetVideoCount'
},
batchedOrionLink,
orionLink
)
const operationSplitLink = split(
({ query }) => {
const definition = getMainDefinition(query)
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription'
},
subscriptionLink,
orionSplitLink
)
return new ApolloClient({ cache, link: operationSplitLink })
}
Example #21
Source File: Security.ts From jmix-frontend with Apache License 2.0 | 6 votes |
constructor(private apolloClient: ApolloClient<unknown>) {
makeObservable<Security, "effectivePermissions">(this, {
attrPermissionCache: observable,
effectivePermissions: observable,
isDataLoaded: computed,
permissions: computed,
loadPermissions: action
});
}
Example #22
Source File: cachingAssets.ts From atlas with GNU General Public License v3.0 | 6 votes |
removeVideoFromCache = (videoId: string, client: ApolloClient<object>) => {
const videoRef = `Video:${videoId}`
client.cache.modify({
fields: {
videos: (existingVideos = []) => {
return existingVideos.filter((video: VideoFieldsFragment) => video.id !== videoId)
},
videosConnection: (existing = {}) => {
return (
existing && {
...existing,
totalCount: existing.edges.find((edge: NormalizedVideoEdge) => edge.node.__ref === videoRef)
? existing.totalCount - 1
: existing.totalCount,
edges: existing.edges.filter((edge: NormalizedVideoEdge) => edge.node.__ref !== videoRef),
}
)
},
},
})
client.cache.evict({ id: videoRef })
}
Example #23
Source File: Security.test.ts From jmix-frontend with Apache License 2.0 | 6 votes |
async function createSecurity(permsMockConfig?: PermsMockConfig): Promise<Security> {
const mockApolloClient = new ApolloClient<{}>({
link: new MockLink([{
request: {
query: PERMISSIONS_QUERY,
},
result: {
data: {
permissions: createPerms(permsMockConfig),
},
},
}]),
cache: new InMemoryCache({})
});
return new Security(mockApolloClient);
}
Example #24
Source File: client.ts From ui with GNU Affero General Public License v3.0 | 5 votes |
client: ApolloClient<NormalizedCacheObject>
Example #25
Source File: MainStore.test.ts From jmix-frontend with Apache License 2.0 | 5 votes |
function createMockApolloClient() {
return new ApolloClient<{}>({
link: new MockLink([]),
cache: new InMemoryCache({})
});
}
Example #26
Source File: index.tsx From game-store-monorepo-app with MIT License | 5 votes |
client = new ApolloClient({
link: from([errorLink, httpLink]),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
allGames: {
keyArgs: ['dates', 'pageSize', 'tags', 'genres', 'publishers', 'ordering', 'search'],
merge(existing: RawgGameResponse, incoming: RawgGameResponse): RawgGameResponse {
return handleQueryMergeResult<RawgGameResponse>(existing, incoming);
},
},
gameSeries: {
keyArgs: ['id'],
merge(existing: RawgGameResponse, incoming: RawgGameResponse): RawgGameResponse {
return handleQueryMergeResult<RawgGameResponse>(existing, incoming);
},
},
allGenres: {
keyArgs: ['pageSize', 'ordering'],
merge(existing: RawgGenreResponse, incoming: RawgGenreResponse): RawgGenreResponse {
return handleQueryMergeResult<RawgGenreResponse>(existing, incoming);
},
},
allTags: {
keyArgs: ['pageSize', 'ordering'],
merge(existing: RawgTagResponse, incoming: RawgTagResponse): RawgTagResponse {
return handleQueryMergeResult<RawgTagResponse>(existing, incoming);
},
},
allPublishers: {
keyArgs: ['pageSize', 'ordering'],
merge(existing: RawgPublisherResponse, incoming: RawgPublisherResponse): RawgPublisherResponse {
return handleQueryMergeResult<RawgPublisherResponse>(existing, incoming);
},
},
},
},
},
}),
})
Example #27
Source File: subgraph.ts From nouns-monorepo with GNU General Public License v3.0 | 5 votes |
clientFactory = (uri: string) =>
new ApolloClient({
uri,
cache: new InMemoryCache(),
})
Example #28
Source File: withData.tsx From keycapsets.com with GNU General Public License v3.0 | 5 votes |
apolloClient: ApolloClient<{}>
Example #29
Source File: MainStore.ts From jmix-frontend with Apache License 2.0 | 5 votes |
constructor(
private apolloClient: ApolloClient<unknown>,
private jmixREST: JmixRestConnection,
options?: MainStoreOptions
) {
this._appName = options?.appName ?? '';
this.storage = options?.storage ?? window.localStorage;
this.clientId = options?.clientId ?? 'client';
this.secret = options?.secret ?? 'secret';
this.obtainTokenEndpoint = options?.obtainTokenEndpoint ?? '/oauth/token';
this.revokeTokenEndpoint = options?.revokeTokenEndpoint ?? '/oauth/revoke';
this.locale = this.storage.getItem(this.localeStorageKey)
?? options?.locale
?? 'en';
this.graphqlEndpoint = options?.graphqlEndpoint ?? '/graphql';
if (options?.contentDisplayMode != null) {
this.contentDisplayMode = options.contentDisplayMode;
}
this.jmixREST.onLocaleChange(this.handleLocaleChange);
this.security = new Security(this.apolloClient);
makeObservable<MainStore, "handleLocaleChange">(this, {
initialized: observable,
authenticated: observable,
usingAnonymously: observable,
userName: observable,
locale: observable,
messages: observable,
enumMessages: observable,
contentDisplayMode: observable,
initialize: action,
loadMessages: action,
loginRequired: computed,
login: action,
logout: action,
handleLocaleChange: action
});
autorun(() => {
if (this.initialized && (this.authenticated || this.usingAnonymously)) {
this.security.loadPermissions();
this.loadMessages();
}
})
// Save locale to storage whenever it is changed
autorun(() => {
if (this.locale != null) {
this.storage.setItem(this.localeStorageKey, this.locale);
// TODO remove once REST is fully replaced by GraphQL.
this.jmixREST.locale = this.locale;
} else {
this.storage.removeItem(this.localeStorageKey);
}
});
reaction(() => this.locale, (locale) => {
this.localeChangeListeners.forEach((onLocaleChanged) => onLocaleChanged(locale));
});
}