-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
352 lines (310 loc) · 9.95 KB
/
index.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
var
contentful = require('contentful'),
fs = require('fs'),
mkdirp = require('mkdirp'),
q = require('q'),
chalk = require('chalk'),
rimraf = require('rimraf'),
consolidate = require('consolidate'),
path = require('path'),
merge = require('merge'),
debuginfo = {
renderCount: 0
},
DEBUGMODE = false;
function debug() {
if(DEBUGMODE) {
console.log(arguments);
}
}
// check if object exists and throws an error if not
function checkExistance(testObject, reference, throwException) {
reference = 'ref: ' + reference;
if(typeof testObject === 'string') {
debug('checkExistance: Object is a string', testObject, reference);
return 'string';
}
var name = (testObject && testObject.fields && testObject.fields.name) ? testObject.fields.name : 'no name';
// console.log(name, reference);
if(!testObject || typeof testObject === undefined || testObject === null) {
var error = new Error('checkExistance failed: Object does not exist. ', testObject, reference);
debug(error);
return false;
}
return true;
}
module.exports = (function() {
var contentTypes = {
array: [],
byId: {}
};
var options = {
engine: 'nunjucks',
templates: 'templates',
apiconfig: {
space: null,
accessToken: null,
secure: true,
host: 'cdn.contentful.com'
},
context: {
// context variables to pass into template rendering
}
};
var writeToFile = function() {
var deferred = q.defer();
var filename = options.dest;
var filepath = process.cwd() + '/' + filename;
var directory = path.dirname(filepath);
var contents = JSON.stringify(db, null, 2);
mkdirp(directory, function(err) {
if(err) {
deferred.reject(err);
return;
}
try {
fs.writeFileSync(filepath, contents, 'utf8');
} catch (err) {
deferred.reject(err);
return;
}
deferred.resolve();
});
return deferred.promise;
};
var contentfulStatic = {
config: function( optionsObject ) {
options.templates = optionsObject.templates || options.templates;
options.engine = optionsObject.engine || options.engine;
options.apiconfig.space = optionsObject.space || options.apiconfig.space;
options.apiconfig.accessToken = optionsObject.accessToken || options.apiconfig.accessToken;
options.apiconfig.secure = optionsObject.secure || options.apiconfig.secure;
options.apiconfig.host = optionsObject.host || options.apiconfig.host;
options.context = optionsObject.context || options.context;
},
/**
* Sync content from contentful. You can choose to supply a callback or just use the promise
* that is returned.
*
* @param {Function} callback (optional) a callback function(err, content)
* @return {Promise} a promise that resolves to the content.
*/
sync: function(callback){
var client = contentful.createClient(options.apiconfig);
var db = {
contentTypes: [],
entries: {},
space: {}
};
var skips = {};
var getEntries = function(locale, skip){
return client.entries({ locale:locale.code, limit:1000, skip:skip, order:'sys.createdAt' });
};
var fetchAll = function(locale, acc){
return function(result){
if (result.length == 1000){
skips[locale.code] += 1000;
return getEntries(locale, skips[locale.code]).then(fetchAll(locale, acc.concat(result)));
} else {
db.entries[locale.code] = acc.concat(result);
return acc.concat(result);
}
}
};
var promise = q.all([
client.contentTypes(),
client.space()
]).then( function(response) {
var contentTypes = response[0];
var space = response[1];
db.contentTypes = contentTypes;
db.space = space;
return q.all(db.space.locales.map(function(locale) {
skips[locale.code] = 0;
return getEntries(locale, skips[locale.code]).then( fetchAll( locale, [] ) );
})).then(function(result) {
return db;
});
}).catch(function(error){
console.log(error);
});
if (callback) {
promise.then(function(db) {
process.nextTick(function() {
callback(undefined, db);
});
}, callback);
}
return promise;
},
/**
* Renders HTML snippets for all entries.
*
* @param {Object} content The content.
* @param {Function} callback (optional) a callback function(err, html)
* @return {Promise} that resolves to an object with id of entry as key and HTML as value.
*/
render: function(content, before, callback) {
// manually setup nunjucks to not cache templates since consolidate doesn't support this option
// expose consolidate to allow for a custom setup
console.log('[contentfulStatic.render] Calling "before" callback...');
if (before != undefined) before(consolidate, content);
// Massage the data for some easy lookup
var contentTypes = {};
content.contentTypes.reduce(function(types, ct) {
checkExistance(ct, 'index.js:164');
types[ct.sys.id] = ct;
return types;
}, contentTypes);
// FIXME: Only specified locale.
var renderPromise = q.all(content.space.locales.map(function(locale) {
console.log('[contentfulStatic.render] Traversing entries in locale ' + locale.code + ' ...');
// Massage the data for some easy lookup
var entries = {};
content.entries[locale.code].reduce(function(entries, entry) {
checkExistance(entry, 'index.js:177');
entries[entry.sys.id] = entry;
return entries;
}, entries);
// Find out order to render in.
var recurse = function(obj, list, contentTypes, dupCheck) {
dupCheck = dupCheck || {};
// Render children first
if (Array.isArray(obj)) {
obj.forEach(function(item) {
recurse(item, list, contentTypes, dupCheck);
});
} else if (obj && typeof obj === 'object') {
Object.keys(obj).forEach(function(k) {
if (k !== '_sys' && k !== 'sys') {
recurse(obj[k], list, contentTypes, dupCheck);
}
});
}
// Then render current entry, if its an entry
// It's an entry to us if it has a sys.contentType
if (obj && obj.sys && obj.sys.contentType && obj.sys.id) {
if (!dupCheck[obj.sys.id]) {
list.push({
id: obj.sys.id,
filename: obj.fields && obj.fields.id || obj.sys.id,
name: obj.fields && obj.fields.name || obj.sys.id,
contentType: contentTypes[obj.sys.contentType.sys.id].name,
entry: obj
});
dupCheck[obj.sys.id] = true;
}
}
};
var toRender = [];
recurse(entries, toRender, contentTypes);
var debugTemplate = function(e) {
return '<h4>No template found</h4><pre>' + JSON.stringify(e, undefined, 2) + '</pre>';
};
// Awesome! Let's render them, one at a time and include the rendered html in the context
// of each so that they can in turn include it themselves.
var render = function(entryObj, includes) {
var deferred = q.defer();
// Try figuring out which template to use
var exists = function(pth) {
try {
fs.accessSync(pth);
return true;
} catch (e) {
return false;
}
};
// DEBUG log
if(entryObj === undefined || typeof entryObj === "string") throw new Error('invalid entryObj at index.js:232');
var debugName = entryObj && entryObj.entry.fields && entryObj.entry.fields.name ? entryObj.entry.fields.name : entryObj.entry.sys.id;
debug('rendering entry...', debugName);
// Try a nested path
var tmp = entryObj.contentType.split('-');
tmp[tmp.length - 1] = tmp[tmp.length - 1] + '.html';
var tmpl = path.join.apply(path, tmp);
if (!exists(path.join(options.templates,tmpl))) {
tmpl = entryObj.contentType + '.html';
}
// Ok let's check again (TODO: DRY)
if (!exists(path.join(options.templates, tmpl))) {
debug('Could not find template ', path.join(options.templates,tmpl));
deferred.resolve('<span>(Missing template)</span>');
} else {
var defaultContext = {
entry: entryObj.entry,
content: content,
entries: entries,
includes: includes,
contentTypes: contentTypes,
globals: {
locale: locale.code
},
debug: function(obj) {
return JSON.stringify(obj, undefined, 2);
},
include: function(obj) {
if(obj == undefined) {
debug('error: undefined object');
return false;
}
checkExistance(obj.sys, 'index.js:262');
if (Array.isArray(obj)) {
return obj.map(function(e) {
if (e && e.sys) {
return includes[e.sys.id] || debugTemplate(e);
}
return debugTemplate(e);
}).join('\n');
} else if (obj.sys) {
return includes[obj.sys.id] || debugTemplate(obj);
}
}
};
consolidate[options.engine](
path.join(options.templates, tmpl), merge.recursive(defaultContext, options.context),
function(err, html) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(html);
}
}
);
}
return deferred.promise;
};
var includes = {};
console.log('[contentfulStatic.render]', 'Rendering templates ...');
var promise = toRender.reduce(function(soFar, e) {
checkExistance(e, 'index.js:294');
return soFar.then(function(includes) {
debuginfo.renderCount++;
return render(e, includes).then(function(html) {
includes[e.id] = html;
return includes;
});
});
}, q(includes));
return promise;
})).then(function(results) {
// Re-map the data to each locale
var byLocale = {};
console.log('[contentfulStatic.render] Rendered ' + debuginfo.renderCount + ' templates.');
console.log('[contentfulStatic.render] Remap data to locales.');
content.space.locales.forEach(function(l, index) {
byLocale[l.code] = results[index];
});
return byLocale;
});
if (callback) {
renderPromise.then(function(includes) {
process.nextTick(function() {
callback(undefined, includes);
});
}, callback);
}
return renderPromise;
}
};
return contentfulStatic;
})();