-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgatsby-node.js
64 lines (51 loc) · 1.82 KB
/
gatsby-node.js
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const createNodeHelpers = require('gatsby-node-helpers').default;
const fetch = require('node-fetch');
const queryString = require('query-string');
const { createNodeFactory } = createNodeHelpers({
typePrefix: `Marketo`
});
async function authenticate(authUrl) {
const res = await fetch(authUrl, {});
if (res.ok) {
const {access_token} = await res.json();
return access_token
} else {
throw new Error('Wrong credentials');
}
}
exports.sourceNodes = async ({ actions }, configOptions) => {
const { createNode } = actions;
const { munchkinId, clientId, clientSecret, maxReturn } = configOptions;
const authOptions = queryString.stringify({
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret
});
const formsApiUrl = `https://${munchkinId}.mktorest.com/rest/asset/v1/forms.json${maxReturn ? `?maxReturn=${maxReturn}` : ''}`;
const authUrl = `https://${munchkinId}.mktorest.com/identity/oauth/token?${authOptions}`;
try {
const accessToken = await authenticate(authUrl);
const forms = await fetch(formsApiUrl, {
headers: { Authorization: `Bearer ${accessToken}` }
}).then(res => res.json());
async function fetchFormFields(id) {
const url = `https://${munchkinId}.mktorest.com/rest/asset/v1/form/${id}/fields.json`;
const results = await fetch(url, {
headers: { Authorization: `Bearer ${accessToken}` }
}).then(res => res.json());
return results;
};
await Promise.all(
forms.result.map(async form => {
const {result: children} = await fetchFormFields(form.id);
const Form = createNodeFactory('Form')({
...form,
children
});
createNode(Form)
})
);
} catch (err) {
console.error("gatsby-source-marketo-forms:", err.message)
}
}