UNPKG

2.27 kBJavaScriptView Raw
1'use strict'
2
3const path = require('path')
4const mm = require('micromatch')
5const klaw = require('klaw')
6const rename = require('rename-extension')
7const execute = require('./execute')
8const save = require('./save')
9
10/**
11 * Run multiple route functions parallel.
12 * @public
13 * @param {Array} routes - Array of route configurations.
14 * @param {String} srcPath - Path to the source folder.
15 * @param {String} distPath - Path to the destination folder.
16 * @param {Object} opts - Additional optional options.
17 * @param {Function} next - The callback that handles the response. Receives the following properties: err.
18 */
19module.exports = function(routes, srcPath, distPath, opts, next) {
20
21 const getHandlerFn = (filePath) => {
22
23 // Set file path relative to the src path as route paths are relative, too
24 const fileRoute = path.relative(srcPath, filePath)
25
26 // Generate an array of matching routes and use the first matching route only
27 const matches = routes.filter((route) => mm.isMatch(fileRoute, route.path))
28 const route = matches[0]
29
30 // Return resolved promise when no matching route found
31 if (route==null) return Promise.resolve()
32
33 // Save file in distPath at the same location as in srcPath,
34 // but with a different extension.
35 const fileSave = (() => {
36
37 // Switch from src to dist
38 const fileDist = filePath.replace(srcPath, distPath)
39
40 // Check if fn exists
41 const hasFn = (typeof route.handler.out==='function')
42
43 return (hasFn===true ? rename(fileDist, route.handler.out(route.opts)) : fileDist)
44
45 })()
46
47 // Return promise when matching route found
48 return new Promise((resolve, reject) => {
49
50 // Execute handler
51 execute(route, fileRoute, filePath, true, (err, data) => {
52
53 if (err!=null) return reject(err)
54
55 // Save file to disk
56 save(fileSave, data, opts, (err) => {
57
58 if (err!=null) return reject(err)
59
60 resolve()
61
62 })
63
64 })
65
66 })
67
68 }
69
70 // Array of fns to execute
71 const query = []
72
73 klaw(srcPath).on('data', (file) => {
74
75 const fn = getHandlerFn(file.path)
76
77 // Store handler fn in query
78 query.push(fn)
79
80 }).on('end', () => {
81
82 // Wait for each promise to resolve and continue with next.
83 // Ensure that the first parameter of next is empty.
84 Promise.all(query).then(() => next(), next)
85
86 })
87
88}
\No newline at end of file