forked from joseguerrerov/gatsby-source-contentful-locales
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-node.js
More file actions
41 lines (37 loc) · 1.52 KB
/
Copy pathgatsby-node.js
File metadata and controls
41 lines (37 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const fetch = require('node-fetch');
const { name } = require('./package.json');
exports.sourceNodes = async ({ actions, createNodeId, createContentDigest, reporter }, options) => {
if (!options.spaceId) return reporter.error(`🚨 ${name}:spaceId is a required option `);
if (!options.accessToken) return reporter.error(`🚨 ${name}:accessToken is a required option `);
if (!options.environment) options.environment = 'master';
const { createNode } = actions
const { spaceId, accessToken, environment } = options
const url = `https://cdn.contentful.com/spaces/${spaceId}/environments/${environment}/locales?access_token=${accessToken}`;
try {
// Download data from the Contentful Delivery API.
const response = await fetch(url)
// Get response data
const data = await response.json();
// Throw error for 404, spaceId not found
if (response.status === 404) throw new Error(`${data.message} Check if the spaceId is correct.`);
// Throw error for 401, invalid authentication
if (response.status === 401) throw new Error(`${data.message} Check if the accessToken is correct.`);
const {items} = data;
// Create nodes
items.map(item => {
createNode({
...item,
id: createNodeId(item.sys.id),
parent: null,
children: [],
internal: {
type: `ContentfulLocale`,
mediaType: `text/html`,
contentDigest: createContentDigest(item),
}
})
})
} catch (e) {
reporter.error(`🚨 ${name}: ${e.message}`);
}
}