UNPKG

2.29 kBJavaScriptView Raw
1/*
2 * Copyright (c) 2018 One Hill Technologies, LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17const all = require ('require-all');
18const { BO } = require ('base-object');
19const _ = require ('lodash');
20const path = require ('path');
21const fs = require ('fs');
22const assert = require ('assert');
23const {env} = require ('./environment');
24
25function load (opts) {
26 return new Promise ((resolve) => {
27 fs.stat (opts.dirname, (err, stats) => {
28 if (err || !stats.isDirectory ())
29 return resolve ({});
30
31 // Load all the objects in the directory.
32 let objects = all (opts);
33
34 resolve (objects);
35 });
36 });
37}
38
39/**
40 * @class Loader
41 *
42 * Utility class for loading entities from a directory.
43 */
44module.exports = BO.extend ({
45 /**
46 * Run the loader.
47 *
48 * @param opts
49 * @returns {Promise<[]>}
50 */
51 load (opts) {
52 assert (!!opts.dirname, 'Your options must have a `dirname` property');
53
54 // By default, we only want files that end in .js, and do not
55 // start with dash (-).
56 let defaults = {
57 excludeDirs: /^(env|\.(git|svn))$/,
58 recursive: true,
59 filter: /^(?!-)(.+)\.js$/
60 };
61
62 // Load the assets from the directory and from the environment directory,
63 // if applicable. We need to list the loads in this order so that when we
64 // merge, environment specific assets will take precedence.
65 //
66
67 let dirname = opts.dirname;
68 let envPath = path.join (dirname, 'env', env);
69
70 let promises = [
71 load (_.merge ({}, defaults, opts, {dirname})),
72 load (_.merge ({}, defaults, opts, {dirname: envPath}))
73 ];
74
75 return Promise.all (promises).then (result => {
76 let assets = _.merge ({}, ...result);
77 return Promise.resolve (assets);
78 });
79 }
80});