UNPKG

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