UNPKG

1.86 kBJavaScriptView Raw
1'use strict';
2
3const StringifierStream = require('./streams/stringifier-stream');
4const Fragment = require('./fragment');
5/**
6 * Process the parsed template and handle the composition of fragments in the template
7 * using stringifier stream
8 *
9 * @param {Object} request - HTTP Request object
10 * @param {Object} options - Tailor options
11 * @param {Object} context - Dynamic overrides for fragments
12 *
13 * @return {Object} Composition of fragment streams - StringifierStream
14 */
15module.exports = function processTemplate(request, options, context) {
16 const {
17 maxAssetLinks,
18 asyncStream,
19 handleTag,
20 requestFragment,
21 fragmentTag,
22 nextIndex,
23
24 pipeDefinition,
25 pipeAttributes,
26 pipeInstanceName
27 } = options;
28
29 const resultStream = new StringifierStream(tag => {
30 const { placeholder, name } = tag;
31
32 const fetchFragment = context => {
33 const fragment = new Fragment({
34 tag,
35 index: nextIndex(),
36 context,
37 requestFragment,
38 pipeInstanceName,
39 pipeAttributes,
40 maxAssetLinks
41 });
42
43 resultStream.emit('fragment:found', fragment);
44
45 const { async } = fragment.attributes;
46
47 if (async) {
48 asyncStream.write(fragment.stream);
49 }
50
51 return fragment.fetch(request, false);
52 };
53
54 if (placeholder === 'pipe') {
55 return pipeDefinition(pipeInstanceName);
56 }
57
58 if (placeholder === 'async') {
59 // end of body tag
60 return asyncStream;
61 }
62
63 if (name === fragmentTag) {
64 return fetchFragment(context);
65 }
66
67 return handleTag(request, tag, options, context);
68 });
69
70 return resultStream;
71};