[ckan api + apollo][l]: setup apollo client to connect to actual CKAN API.
This commit is contained in:
61
lib/apolloClient.ts
Normal file
61
lib/apolloClient.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useMemo } from 'react';
|
||||
import getConfig from 'next/config';
|
||||
import { ApolloClient } from 'apollo-client';
|
||||
import { InMemoryCache } from 'apollo-cache-inmemory';
|
||||
import { RestLink } from 'apollo-link-rest';
|
||||
|
||||
let apolloClient;
|
||||
|
||||
const restLink = new RestLink({
|
||||
uri: 'https://demo.ckan.org/api/3/action/',
|
||||
typePatcher: {
|
||||
Search: (
|
||||
data: any,
|
||||
outerType: string,
|
||||
patchDeeper: RestLink.FunctionalTypePatcher
|
||||
): any => {
|
||||
if (data.result != null) {
|
||||
data.result.__typename = 'SearchResponse';
|
||||
|
||||
if (data.result.results != null) {
|
||||
data.result.results = data.result.results.map((item) => {
|
||||
if (item.organization != null) {
|
||||
item.organization.__typename = 'Organization';
|
||||
}
|
||||
return { __typename: 'Package', ...item };
|
||||
});
|
||||
}
|
||||
}
|
||||
return data;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function createApolloClient() {
|
||||
const { publicRuntimeConfig } = getConfig();
|
||||
return new ApolloClient({
|
||||
link: restLink,
|
||||
cache: new InMemoryCache(),
|
||||
});
|
||||
}
|
||||
|
||||
export function initializeApollo(initialState = null) {
|
||||
const _apolloClient = apolloClient ?? createApolloClient();
|
||||
|
||||
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
|
||||
// gets hydrated here
|
||||
if (initialState) {
|
||||
_apolloClient.cache.restore(initialState);
|
||||
}
|
||||
// For SSG and SSR always create a new Apollo Client
|
||||
if (typeof window === 'undefined') return _apolloClient;
|
||||
// Create the Apollo Client once in the client
|
||||
if (!apolloClient) apolloClient = _apolloClient;
|
||||
|
||||
return _apolloClient;
|
||||
}
|
||||
|
||||
export function useApollo(initialState) {
|
||||
const store = useMemo(() => initializeApollo(initialState), [initialState]);
|
||||
return store;
|
||||
}
|
||||
Reference in New Issue
Block a user