-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgridsome.server.js
82 lines (66 loc) · 2.3 KB
/
gridsome.server.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const pluginName = require("./package.json").name;
const axios = require('axios');
/**
* Can process an object (static) or an array of objects (collection)
*
*/
class RestSourcePlugin {
static defaultOptions() {
return {
enabled: true,
debug: false,
axiosConfig: undefined,
endpoint: undefined,
typeName: undefined,
isStatic: false,
isCollection: true,
/**
* Modify the response before it gets added to
* the collection
*/
responseInterceptor: undefined
}
}
constructor(api, options) {
this.api = api;
this.options = options;
if (this.options.isStatic) this.options.isCollection = false;
this.options = Object.assign(RestSourcePlugin.defaultOptions(), options);
api.loadSource(this.loadSource.bind(this));
}
async loadSource(actions) {
const instance = axios.create(this.options.axiosConfig);
const result = await instance.get(this.options.endpoint);
let data = result.data;
let responseInterceptor = this.options.responseInterceptor;
if (responseInterceptor !== undefined && typeof (responseInterceptor) === 'function')
data = await responseInterceptor(data);
if (this.options.isStatic)
this.staticMetadata(data, actions);
else if (this.options.isCollection)
this.collectionData(data, actions);
}
collectionData(data, actions) {
const collection = actions.addCollection(this.options.typeName);
try {
for (let item of data) {
collection.addNode(item);
}
} catch (e) {
console.error(e)
console.error("Have you set the right collection type [options.isStatic, options.isCollection]?")
}
}
staticMetadata(data, actions) {
const obj = {};
obj[this.options.typeName] = data;
const fields = typeof data !== 'object' || Array.isArray(data) ? obj : data;
for (const key of Object.keys(fields)) {
actions.addMetaData(key, fields[key])
}
}
log(a) {
if (this.options.debug) console.log(`${pluginName}: `, a);
}
}
module.exports = RestSourcePlugin