index.js
1.61 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
'use strict';
var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var Howhap = require('howhap');
var errors = require('./errors');
var getStack = require('./get-stack');
var pluralize = require('pluralize');
module.exports = function (config) {
if (!_.isObject(config)) {
throw new Howhap(errors.BAD_CONFIG);
}
var 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);
}
var originalPath = config.path;
// Relative path
if (!path.isAbsolute(config.path)) {
var stack = getStack();
stack.shift();
var callingFilePath = stack.shift().getFileName();
config.path = path.join(path.dirname(callingFilePath), config.path);
}
var 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() });
}
var models = files.filter(function (file) {
// Ignore non-javascript files and hidden files.
return path.extname(file) === '.js' && file.charAt(0) !== '.';
}).map(function (file) {
var 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);
};