-
Notifications
You must be signed in to change notification settings - Fork 0
/
mupli-api.js
80 lines (66 loc) · 2.26 KB
/
mupli-api.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
71
72
73
74
75
76
77
78
79
80
import { CoreUtils, FileDetails, FileLoader } from "mupli-core";
export class ApiModule {
moduleName;
_routerPrefix;
_routes = {};
constructor(config = { routerPrefix: undefined, moduleName: undefined }) {
this._routerPrefix = config.routerPrefix ?? "/api";
this.moduleName = config.moduleName ?? "api";
}
async init(appName, config) {
const me = this;
const routes = this._routes;
routes[appName] ??= {};
let files = CoreUtils.getFiles(appName, config) //
.filter((x) => x.is("js") || x.is("json"));
for (const key in files) {
/**
* @type {FileDetails}
*/
const fd = files[key];
if (fd.moduleFilePath.indexOf("/_") < 0) {
if (fd.is("js")) {
let actions = await this._getActions(fd);
Object.keys(actions).forEach((key) => {
let action = actions[key];
routes[appName][this._routerPrefix + fd.route + key] =
action;
});
} else if (fd.is("json")) {
const jsonString = FileLoader.load(fd);
routes[appName][this._routerPrefix + fd.route] = async (
ctx
) => {
return jsonString;
};
}
}
}
}
async _getActions(actionFd) {
const module = await FileLoader.asObject(actionFd);
const methodNames = Object.keys(module).filter(
(methodName) => !methodName.startsWith("_")
);
if (methodNames.length <= 0)
throw new Error(
"No '" +
actionFd.name +
"' or 'init' method in file: " +
actionFd.filePath
);
const actions = {};
methodNames.forEach((m) => {
if (m == "init") {
actions[""] = module[m];
} else {
actions["/" + m] = module[m];
}
});
return actions;
}
routes({ appName }) {
return this._routes[appName];
}
}
export const apiModule = new ApiModule();