-
Notifications
You must be signed in to change notification settings - Fork 1
/
hiroki.js
70 lines (67 loc) · 2.01 KB
/
hiroki.js
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
68
69
70
'use strict';
const Controller = require('./lib/controller');
const ErrorCollection = require('./lib/error-collection');
const Validator = require('./lib/validator');
let instance;
class Hiroki {
constructor() {
if(instance) {
return instance;
}
this.defaultConfig = {
basePath: '/api'
};
this.config = {...this.defaultConfig};
this.models = {};
this.controllers = {};
instance = this;
return instance;
}
importModel(model, options) {
Validator.validateModel(model);
let modelName = model;
if(model.hasOwnProperty('modelName')) {
modelName = model.modelName;
}
modelName = modelName.toLowerCase();
if(!this.controllers[modelName]) {
this.controllers[modelName] = new Controller(model, {...this.defaultConfig, ...options});
}
return this.controllers[modelName];
}
importModels(models, options) {
if(Array.isArray(models)) {
models.forEach((model) => {
this.importModel(model, options);
});
}
if (typeof models === 'object') {
Object.values(models).forEach((model) => {
this.importModel(model, options);
});
}
}
setConfig(newConf) {
this.config = {
...this.defaultConfig,
...newConf
};
}
async process(_path, params) {
const path = _path.replace(/\/\//ig, '/');
const currentController = Object.values(this.controllers)
.find((controller) =>
controller.check(path)
);
if(!currentController) {
ErrorCollection.notFound(path);
}
try {
return await currentController.process(path, params);
} catch (error) {
console.error('Hiroki Error: ', error);
return {error: error.message, status: error.status || 500};
}
}
}
module.exports = Hiroki;