index.js
1.59 KB
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
let _ = require('lodash');
let path = require('path');
let fs = require('fs');
let Howhap = require('howhap');
let errors = require('./errors');
let getStack = require('./get-stack');
let pluralize = require('pluralize');
module.exports = function(config) {
if(!_.isObject(config)) {
throw new Howhap(errors.BAD_CONFIG);
}
let defaultConfig = {
putBehavior: 'upsert',
hardDelete: false,
deletedAttribute: 'deletedAt',
errors: errors,
pluralEndpoints: false,
};
config = _.extend(defaultConfig, config);
if(!config.path) {
throw new Howhap(config.errors.MISSING_PATH);
}
const originalPath = config.path;
// Relative path
if(!path.isAbsolute(config.path)) {
let stack = getStack();
stack.shift();
let callingFilePath = stack.shift().getFileName();
config.path = path.join(path.dirname(callingFilePath), config.path);
}
let files = null;
try {
files = fs.readdirSync(config.path);
}
catch(e) {
if(e.code === 'ENOENT') {
throw new Howhap(config.errors.BAD_PATH, {path: originalPath});
}
throw new Howhap(config.errors.UNKNOWN, {error: e.toString()});
}
let models = files
.filter(function(file) {
// Ignore non-javascript files and hidden files.
return (path.extname(file) === '.js' && file.charAt(0) !== '.');
})
.map(function(file) {
let modelName = file.split('.')[0];
return {
model: require(path.join(config.path, file)),
name: config.pluralEndpoints ? pluralize(modelName) : modelName,
};
})
.reduce(function(before, info) {
before[info.name.toLowerCase()] = info.model;
return before;
}, {});
return require('./middleware')(models, config);
};