2020-03-24 14:27:30 +01:00
|
|
|
import { createClient } from "contentful";
|
|
|
|
import type { ContentfulClientApi } from "contentful";
|
|
|
|
|
|
|
|
const space = process.env.CONTENTFUL_SPACE_ID;
|
|
|
|
const accessToken = process.env.CONTENTFUL_ACCESS_TOKEN;
|
|
|
|
|
|
|
|
let client: ContentfulClientApi;
|
|
|
|
|
|
|
|
// Idempotent way to get a reference to the Contentful client.
|
|
|
|
export const getClient = (): ContentfulClientApi => {
|
2020-03-27 11:52:13 +01:00
|
|
|
if (typeof client !== "undefined") {
|
2020-03-24 14:27:30 +01:00
|
|
|
return client;
|
|
|
|
} else {
|
2020-03-27 11:52:13 +01:00
|
|
|
if (typeof space === "string" && typeof accessToken === "string") {
|
2020-03-24 14:27:30 +01:00
|
|
|
let client = createClient({
|
|
|
|
space,
|
|
|
|
accessToken,
|
|
|
|
});
|
|
|
|
|
|
|
|
return client;
|
|
|
|
} else {
|
2020-03-27 11:52:13 +01:00
|
|
|
throw new Error(
|
|
|
|
"Please set CONTENTFUL_SPACE_ID and CONTENTFUL_ACCESS_TOKEN"
|
|
|
|
);
|
2020-03-24 14:27:30 +01:00
|
|
|
}
|
|
|
|
}
|
2020-03-27 11:52:13 +01:00
|
|
|
};
|