@increase21/simplenodejs 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +5 -0
- package/dist/index.js +22 -0
- package/dist/router.d.ts +8 -0
- package/dist/router.js +80 -0
- package/dist/server.d.ts +5 -0
- package/dist/server.js +72 -0
- package/dist/typings/general.d.ts +48 -0
- package/dist/typings/general.js +2 -0
- package/dist/typings/simpletypes.d.ts +8 -0
- package/dist/typings/simpletypes.js +2 -0
- package/dist/utils/helpers.d.ts +10 -0
- package/dist/utils/helpers.js +169 -0
- package/dist/utils/simpleController.d.ts +18 -0
- package/dist/utils/simpleController.js +33 -0
- package/dist/utils/simplePlugins.d.ts +9 -0
- package/dist/utils/simplePlugins.js +8 -0
- package/package.json +16 -2
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.CreateSimpleJsHttpServer = void 0;
|
|
18
|
+
var server_1 = require("./server");
|
|
19
|
+
Object.defineProperty(exports, "CreateSimpleJsHttpServer", { enumerable: true, get: function () { return server_1.CreateSimpleJsHttpServer; } });
|
|
20
|
+
__exportStar(require("./utils/helpers"), exports);
|
|
21
|
+
__exportStar(require("./utils/simpleController"), exports);
|
|
22
|
+
__exportStar(require("./utils/simplePlugins"), exports);
|
package/dist/router.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { RequestObject, ResponseObject } from "./typings/general";
|
|
2
|
+
export interface ControllerMeta {
|
|
3
|
+
name: string;
|
|
4
|
+
Controller: any;
|
|
5
|
+
}
|
|
6
|
+
export declare function loadControllers(root?: string): Map<string, ControllerMeta>;
|
|
7
|
+
export declare function setControllersDir(dir: string): void;
|
|
8
|
+
export declare function route(req: RequestObject, res: ResponseObject, controllersDir?: string): Promise<void>;
|
package/dist/router.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.loadControllers = loadControllers;
|
|
7
|
+
exports.setControllersDir = setControllersDir;
|
|
8
|
+
exports.route = route;
|
|
9
|
+
// router.ts
|
|
10
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
11
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
12
|
+
let controllers = new Map();
|
|
13
|
+
function loadControllers(root = "controllers") {
|
|
14
|
+
const base = node_path_1.default.resolve(process.cwd(), root);
|
|
15
|
+
const map = new Map();
|
|
16
|
+
//walk up
|
|
17
|
+
function walk(dir) {
|
|
18
|
+
//get all the file in the directory
|
|
19
|
+
for (const file of node_fs_1.default.readdirSync(dir)) {
|
|
20
|
+
//add the file name and path
|
|
21
|
+
const full = node_path_1.default.join(dir, file);
|
|
22
|
+
//load direct and reload the files
|
|
23
|
+
if (node_fs_1.default.statSync(full).isDirectory())
|
|
24
|
+
walk(full);
|
|
25
|
+
//if it's file load the file
|
|
26
|
+
else if (file.endsWith(".js") || file.endsWith(".ts")) {
|
|
27
|
+
const mod = require(full);
|
|
28
|
+
// const Controller = mod.default;
|
|
29
|
+
if (!full.startsWith(base))
|
|
30
|
+
return;
|
|
31
|
+
const Controller = require(full)?.default;
|
|
32
|
+
if (typeof Controller !== "function")
|
|
33
|
+
return;
|
|
34
|
+
const key = full.replace(base, "").replace(/\\/g, "/").replace(/\.(ts|js)$/, "");
|
|
35
|
+
map.set(key.toLowerCase(), { name: Controller.name, Controller });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
walk(base);
|
|
40
|
+
return map;
|
|
41
|
+
}
|
|
42
|
+
function setControllersDir(dir) {
|
|
43
|
+
controllers = loadControllers(dir);
|
|
44
|
+
}
|
|
45
|
+
async function route(req, res, controllersDir) {
|
|
46
|
+
// console.log("Router is called")
|
|
47
|
+
const url = new URL(req.url, "http://localhost");
|
|
48
|
+
const parts = url.pathname.replace(/^\/+|\/+$/g, "").split("/");
|
|
49
|
+
let controllerPath = (parts.length > 2 ? "/" + parts.slice(0, 2).join("/") : `/${parts.join("/")}`).toLocaleLowerCase();
|
|
50
|
+
let methodName = parts.length > 2 ? parts[2] : "index";
|
|
51
|
+
let id = methodName !== "index" ? parts.slice(parts.indexOf(methodName) + 1) : null;
|
|
52
|
+
const meta = controllers.get(controllerPath);
|
|
53
|
+
//if the controller is not available or not found
|
|
54
|
+
if (!meta || !meta.name || !meta.Controller)
|
|
55
|
+
return res.status(404).json({ error: "The requested resource does not exist" });
|
|
56
|
+
const ControllerClass = meta.Controller;
|
|
57
|
+
const controller = new ControllerClass();
|
|
58
|
+
//if the endpoint not a function
|
|
59
|
+
if (typeof controller[methodName] !== "function") {
|
|
60
|
+
//if it's using index
|
|
61
|
+
if (typeof controller["index"] === "function" && parts.length === 3) {
|
|
62
|
+
methodName = "index";
|
|
63
|
+
id = parts.slice(2);
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
return res.status(404).json({ error: "The requested resource does not exist" });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
//if the data require params but there's no matching params
|
|
70
|
+
if (id && id.length && (!controller[methodName].length || controller[methodName].length < id.length)) {
|
|
71
|
+
return res.status(404).json({ error: "The requested resource does not exist. Kindly check your url" });
|
|
72
|
+
}
|
|
73
|
+
controller._bindContext({ req, res });
|
|
74
|
+
const result = await controller[methodName](...(id || []));
|
|
75
|
+
//if it's not responded
|
|
76
|
+
if (!res.writableEnded && result) {
|
|
77
|
+
res.setHeader("Content-Type", "application/json");
|
|
78
|
+
res.end(JSON.stringify(result));
|
|
79
|
+
}
|
|
80
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from "http";
|
|
2
|
+
import { SimpleJsServer } from "./typings/general";
|
|
3
|
+
export declare const CreateSimpleJsHttpServer: (handler?: (req: IncomingMessage, res: ServerResponse) => void, opts?: {
|
|
4
|
+
controllersDir: string;
|
|
5
|
+
}) => SimpleJsServer;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.CreateSimpleJsHttpServer = void 0;
|
|
7
|
+
const http_1 = __importDefault(require("http"));
|
|
8
|
+
const router_1 = require("./router");
|
|
9
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
10
|
+
const helpers_1 = require("./utils/helpers");
|
|
11
|
+
const extension = (req, res) => {
|
|
12
|
+
//for response status
|
|
13
|
+
res.status = (code) => {
|
|
14
|
+
if (!/^\d+/.test(String(code)) || typeof code !== "number")
|
|
15
|
+
throw new Error("Status code expected to be number but got " + typeof code);
|
|
16
|
+
res.statusCode = code ? code : 200;
|
|
17
|
+
return res;
|
|
18
|
+
};
|
|
19
|
+
///convert the response to JSON
|
|
20
|
+
res.json = (param) => {
|
|
21
|
+
res.setHeader('Content-Type', 'application/json');
|
|
22
|
+
res.end(JSON.stringify(param));
|
|
23
|
+
};
|
|
24
|
+
//convert the response to text/plain
|
|
25
|
+
res.text = (param) => {
|
|
26
|
+
res.setHeader('Content-Type', 'text/plain');
|
|
27
|
+
res.end(param);
|
|
28
|
+
};
|
|
29
|
+
req.id = node_crypto_1.default.randomUUID();
|
|
30
|
+
res.setHeader("X-Request-Id", req.id);
|
|
31
|
+
};
|
|
32
|
+
const CreateSimpleJsHttpServer = (handler, opts) => {
|
|
33
|
+
const middlewares = [];
|
|
34
|
+
const errorMiddlewares = [];
|
|
35
|
+
const plugins = [];
|
|
36
|
+
//set the director of the controller
|
|
37
|
+
if (opts?.controllersDir)
|
|
38
|
+
(0, router_1.setControllersDir)(opts.controllersDir);
|
|
39
|
+
const server = http_1.default.createServer(async (req, res) => {
|
|
40
|
+
extension(req, res);
|
|
41
|
+
const run = (0, helpers_1.composeWithError)(middlewares, errorMiddlewares);
|
|
42
|
+
try {
|
|
43
|
+
handler && await handler(req, res);
|
|
44
|
+
if (res.writableEnded)
|
|
45
|
+
return;
|
|
46
|
+
await run(req, res);
|
|
47
|
+
//if the request has ended stop here
|
|
48
|
+
if (res.writableEnded)
|
|
49
|
+
return;
|
|
50
|
+
await (0, router_1.route)(req, res);
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
// 1. Run error middlewares
|
|
54
|
+
for (const mw of errorMiddlewares) {
|
|
55
|
+
await mw(err, req, res, () => { });
|
|
56
|
+
}
|
|
57
|
+
// 2. Safe HTTP response fallback
|
|
58
|
+
if (!res.headersSent) {
|
|
59
|
+
res.statusCode = 503;
|
|
60
|
+
res.end("Service unavailable at the moment");
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
server.use = mw => { middlewares.push(mw); };
|
|
65
|
+
server.useError = mw => errorMiddlewares.push(mw);
|
|
66
|
+
server.registerPlugin = async (plugin) => {
|
|
67
|
+
plugins.push(plugin);
|
|
68
|
+
await plugin(server);
|
|
69
|
+
};
|
|
70
|
+
return server;
|
|
71
|
+
};
|
|
72
|
+
exports.CreateSimpleJsHttpServer = CreateSimpleJsHttpServer;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import http, { IncomingMessage, ServerResponse } from "http";
|
|
2
|
+
export type Next = () => Promise<void> | void;
|
|
3
|
+
export type Plugin = (app: SimpleJsServer, opts?: any) => Promise<void> | void;
|
|
4
|
+
export type ObjectPayload = {
|
|
5
|
+
[key: string]: any;
|
|
6
|
+
};
|
|
7
|
+
export type Middleware = (req: RequestObject, res: ResponseObject, next: () => Promise<void> | void) => Promise<void> | void;
|
|
8
|
+
export type ErrorMiddleware = (err: any, req: RequestObject, res: ResponseObject, next: Next) => Promise<void> | void;
|
|
9
|
+
export interface SimpleJsServer extends http.Server {
|
|
10
|
+
use(mw: Middleware): Promise<any> | void;
|
|
11
|
+
useError: (mw: ErrorMiddleware) => void;
|
|
12
|
+
registerPlugin: (plugin: Plugin) => Promise<void>;
|
|
13
|
+
_environment: 'dev' | 'stag' | 'live';
|
|
14
|
+
}
|
|
15
|
+
export interface RequestObject extends IncomingMessage {
|
|
16
|
+
body?: any;
|
|
17
|
+
query?: any;
|
|
18
|
+
id?: string;
|
|
19
|
+
_server_environment?: 'dev' | 'stag' | 'live';
|
|
20
|
+
_custom_data?: ObjectPayload;
|
|
21
|
+
}
|
|
22
|
+
export interface ResponseObject extends ServerResponse {
|
|
23
|
+
status: (value: number) => ResponseObject;
|
|
24
|
+
json: (value: object) => void;
|
|
25
|
+
text: (value?: string) => void;
|
|
26
|
+
}
|
|
27
|
+
export interface SubRequestHandler {
|
|
28
|
+
post?: (params: PrivateMethodProps) => void;
|
|
29
|
+
put?: (params: PrivateMethodProps) => void;
|
|
30
|
+
get?: (params: PrivateMethodProps) => void;
|
|
31
|
+
delete?: (params: PrivateMethodProps) => void;
|
|
32
|
+
patch?: (params: PrivateMethodProps) => void;
|
|
33
|
+
}
|
|
34
|
+
export interface PrivateMethodProps {
|
|
35
|
+
body: ObjectPayload;
|
|
36
|
+
res: ResponseObject;
|
|
37
|
+
req: RequestObject;
|
|
38
|
+
query: ObjectPayload;
|
|
39
|
+
id?: string;
|
|
40
|
+
idMethod?: {
|
|
41
|
+
post?: 'required' | 'optional';
|
|
42
|
+
get?: 'required' | 'optional';
|
|
43
|
+
put?: 'required' | 'optional';
|
|
44
|
+
delete?: 'required' | 'optional';
|
|
45
|
+
patch?: 'required' | 'optional';
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export type AcceptHeaderValue = 'application/media' | 'application/text';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { RequestObject, ResponseObject } from "../typings/general";
|
|
2
|
+
import { ErrorMiddleware, Middleware } from "../typings/general";
|
|
3
|
+
import { SimpleJSBodyParseType, SimpleJSRateLimitType } from "../typings/simpletypes";
|
|
4
|
+
export declare function SetRequestCORS(opts: {
|
|
5
|
+
name: string;
|
|
6
|
+
value: string;
|
|
7
|
+
}[]): (req: RequestObject, res: ResponseObject, next: any) => Promise<void>;
|
|
8
|
+
export declare function SetRateLimiter(opts: SimpleJSRateLimitType): (req: RequestObject, res: ResponseObject, next: () => Promise<any> | void) => Promise<void>;
|
|
9
|
+
export declare function SetBodyParser(opts: SimpleJSBodyParseType): (req: RequestObject, res: ResponseObject, next: () => Promise<any> | void) => Promise<void>;
|
|
10
|
+
export declare function composeWithError(middlewares: Middleware[], errorMiddlewares: ErrorMiddleware[]): (req: RequestObject, res: ResponseObject) => Promise<void>;
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.SetRequestCORS = SetRequestCORS;
|
|
7
|
+
exports.SetRateLimiter = SetRateLimiter;
|
|
8
|
+
exports.SetBodyParser = SetBodyParser;
|
|
9
|
+
exports.composeWithError = composeWithError;
|
|
10
|
+
const node_querystring_1 = __importDefault(require("node:querystring"));
|
|
11
|
+
// core/cors.ts
|
|
12
|
+
function SetRequestCORS(opts) {
|
|
13
|
+
return async (req, res, next) => {
|
|
14
|
+
const defaults = {
|
|
15
|
+
"Access-Control-Allow-Origin": "*",
|
|
16
|
+
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization",
|
|
17
|
+
"Access-Control-Allow-Methods": "GET, POST, DELETE, PUT, PATCH",
|
|
18
|
+
"X-Content-Type-Options": "nosniff",
|
|
19
|
+
"X-Frame-Options": "DENY",
|
|
20
|
+
"Referrer-Policy": "no-referrer",
|
|
21
|
+
"Content-Security-Policy": "default-src 'none'",
|
|
22
|
+
};
|
|
23
|
+
let merged = { ...defaults };
|
|
24
|
+
for (const { name, value } of opts) {
|
|
25
|
+
merged[name] = value; // overrides defaults if same key
|
|
26
|
+
}
|
|
27
|
+
//allow credentials only when origin specified
|
|
28
|
+
if (merged["Access-Control-Allow-Credentials"] === "true") {
|
|
29
|
+
const origin = req.headers.origin;
|
|
30
|
+
res.status(403).end();
|
|
31
|
+
if (!origin)
|
|
32
|
+
return;
|
|
33
|
+
merged["Access-Control-Allow-Origin"] = origin;
|
|
34
|
+
}
|
|
35
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
36
|
+
res.setHeader(key, value);
|
|
37
|
+
}
|
|
38
|
+
if (req.method === "OPTIONS") {
|
|
39
|
+
res.status(204).end();
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
await next();
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
// core/rateLimit.ts
|
|
46
|
+
function SetRateLimiter(opts) {
|
|
47
|
+
const store = new Map();
|
|
48
|
+
const timer = setInterval(() => {
|
|
49
|
+
const now = Date.now();
|
|
50
|
+
for (const [k, v] of store) {
|
|
51
|
+
if (now - v.ts > opts.windowMs * 2)
|
|
52
|
+
store.delete(k);
|
|
53
|
+
}
|
|
54
|
+
}, opts.windowMs);
|
|
55
|
+
timer.unref();
|
|
56
|
+
return async (req, res, next) => {
|
|
57
|
+
const rawIp = req.headers["x-forwarded-for"] || req.socket.remoteAddress || "unknown";
|
|
58
|
+
const ip = Array.isArray(rawIp) ? rawIp[0] : String(rawIp).split(",")[0].trim();
|
|
59
|
+
const key = String(opts.keyGenerator?.(req) || ip || "unknown");
|
|
60
|
+
const now = Date.now();
|
|
61
|
+
const entry = store.get(key) || { count: 0, ts: now };
|
|
62
|
+
if (now - entry.ts > opts.windowMs) {
|
|
63
|
+
entry.count = 0;
|
|
64
|
+
entry.ts = now;
|
|
65
|
+
}
|
|
66
|
+
entry.count++;
|
|
67
|
+
store.set(key, entry);
|
|
68
|
+
if (entry.count > opts.max) {
|
|
69
|
+
res.setHeader("Retry-After", Math.ceil(opts.windowMs / 1000));
|
|
70
|
+
res.status(429).json({ error: "Too Many Requests" });
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
await next();
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
// core/body.ts
|
|
77
|
+
function SetBodyLimit(limit = "1mb") {
|
|
78
|
+
if (typeof limit === "number")
|
|
79
|
+
return limit;
|
|
80
|
+
const match = /^(\d+)(kb|mb)?$/i.exec(limit);
|
|
81
|
+
if (!match)
|
|
82
|
+
return 1024 * 1024;
|
|
83
|
+
const n = parseInt(match[1], 10);
|
|
84
|
+
const unit = match[2]?.toLowerCase();
|
|
85
|
+
if (unit === "kb")
|
|
86
|
+
return n * 1024;
|
|
87
|
+
if (unit === "mb")
|
|
88
|
+
return n * 1024 * 1024;
|
|
89
|
+
return n;
|
|
90
|
+
}
|
|
91
|
+
function SetBodyParser(opts) {
|
|
92
|
+
const maxSize = SetBodyLimit(opts.limit);
|
|
93
|
+
return async (req, res, next) => {
|
|
94
|
+
return new Promise(resolve => {
|
|
95
|
+
let size = 0;
|
|
96
|
+
let body = "";
|
|
97
|
+
req.on("data", chunk => {
|
|
98
|
+
size += chunk.length;
|
|
99
|
+
if (maxSize && size > maxSize) {
|
|
100
|
+
if (!res.writableEnded) {
|
|
101
|
+
res.status(413).json({ error: "Payload too large" });
|
|
102
|
+
}
|
|
103
|
+
req.destroy();
|
|
104
|
+
req.socket.destroy();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
//add the body
|
|
108
|
+
body += chunk;
|
|
109
|
+
});
|
|
110
|
+
req.on("end", () => {
|
|
111
|
+
if (res.writableEnded)
|
|
112
|
+
return resolve();
|
|
113
|
+
try {
|
|
114
|
+
if (body && !["application/text", "application/media"].includes(req.headers.accept)) {
|
|
115
|
+
req.body = JSON.parse(body);
|
|
116
|
+
//parse query
|
|
117
|
+
if (req.query) {
|
|
118
|
+
req.query = JSON.parse(JSON.stringify(node_querystring_1.default.parse(req.query)));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
req.body = body;
|
|
123
|
+
}
|
|
124
|
+
resolve(next());
|
|
125
|
+
}
|
|
126
|
+
catch (e) {
|
|
127
|
+
res.status(400).json({ error: "Invalid request body" });
|
|
128
|
+
return resolve();
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
req.on("error", () => {
|
|
132
|
+
if (!res.writableEnded) {
|
|
133
|
+
res.status(400).json({ error: "Request stream error" });
|
|
134
|
+
}
|
|
135
|
+
resolve();
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function composeWithError(middlewares, errorMiddlewares) {
|
|
141
|
+
return async function (req, res) {
|
|
142
|
+
let idx = -1;
|
|
143
|
+
async function dispatch(i) {
|
|
144
|
+
if (i <= idx)
|
|
145
|
+
throw new Error("next() called twice");
|
|
146
|
+
idx = i;
|
|
147
|
+
const fn = middlewares[i];
|
|
148
|
+
if (!fn)
|
|
149
|
+
return;
|
|
150
|
+
try {
|
|
151
|
+
await fn(req, res, () => dispatch(i + 1));
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
await dispatchError(err, 0);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
async function dispatchError(err, i) {
|
|
158
|
+
const fn = errorMiddlewares[i];
|
|
159
|
+
if (!fn) {
|
|
160
|
+
if (!res.writableEnded) {
|
|
161
|
+
res.status(500).json({ error: "Unhandled error", detail: String(err) });
|
|
162
|
+
}
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
await fn(err, req, res, () => dispatchError(err, i + 1));
|
|
166
|
+
}
|
|
167
|
+
await dispatch(0);
|
|
168
|
+
};
|
|
169
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { RequestObject, ResponseObject } from "../typings/general";
|
|
2
|
+
type HttpMethod = "get" | "post" | "put" | "patch" | "delete";
|
|
3
|
+
type SubRequestHandler = Partial<Record<HttpMethod, (params: PrivateMethodProps) => any>>;
|
|
4
|
+
interface PrivateMethodProps {
|
|
5
|
+
id?: string;
|
|
6
|
+
idMethod?: Partial<Record<HttpMethod, "required" | "optional">>;
|
|
7
|
+
}
|
|
8
|
+
export declare class SimpleNodeJsController {
|
|
9
|
+
protected req: RequestObject;
|
|
10
|
+
protected res: ResponseObject;
|
|
11
|
+
/** framework-internal method */
|
|
12
|
+
_bindContext(ctx: {
|
|
13
|
+
req: RequestObject;
|
|
14
|
+
res: ResponseObject;
|
|
15
|
+
}): void;
|
|
16
|
+
protected RunRequest(handlers: SubRequestHandler, params?: PrivateMethodProps): any;
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SimpleNodeJsController = void 0;
|
|
4
|
+
class SimpleNodeJsController {
|
|
5
|
+
/** framework-internal method */
|
|
6
|
+
_bindContext(ctx) {
|
|
7
|
+
this.req = ctx.req;
|
|
8
|
+
this.res = ctx.res;
|
|
9
|
+
}
|
|
10
|
+
RunRequest(handlers, params) {
|
|
11
|
+
const method = this.req.method?.toLowerCase();
|
|
12
|
+
if (!method) {
|
|
13
|
+
return this.res.status(400).json({ code: 400, msg: "Invalid HTTP Method" });
|
|
14
|
+
}
|
|
15
|
+
const runFn = handlers[method];
|
|
16
|
+
if (typeof runFn !== "function") {
|
|
17
|
+
return this.res.status(405).json({ code: 405, msg: "Method Not Allowed" });
|
|
18
|
+
}
|
|
19
|
+
// ID validation rules
|
|
20
|
+
if (params && params.id && (!params.idMethod || !params.idMethod[method])) {
|
|
21
|
+
return this.res.status(404).json({ code: 404, msg: "Resource not found" });
|
|
22
|
+
}
|
|
23
|
+
if (params && params.idMethod?.[method] === "required" && !params.id) {
|
|
24
|
+
return this.res.status(404).json({ code: 404, msg: "Resource not found" });
|
|
25
|
+
}
|
|
26
|
+
return runFn({
|
|
27
|
+
...(params || {}),
|
|
28
|
+
req: this.req,
|
|
29
|
+
res: this.res,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
exports.SimpleNodeJsController = SimpleNodeJsController;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { SimpleJsServer } from "../typings/general";
|
|
2
|
+
import { SimpleJSRateLimitType } from "../typings/simpletypes";
|
|
3
|
+
export declare function SimpleJsSecurityPlugin(app: SimpleJsServer, opts: {
|
|
4
|
+
cors?: {
|
|
5
|
+
name: string;
|
|
6
|
+
value: string;
|
|
7
|
+
}[];
|
|
8
|
+
rateLimit?: SimpleJSRateLimitType;
|
|
9
|
+
}): void;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SimpleJsSecurityPlugin = SimpleJsSecurityPlugin;
|
|
4
|
+
const helpers_1 = require("./helpers");
|
|
5
|
+
function SimpleJsSecurityPlugin(app, opts) {
|
|
6
|
+
app.use((0, helpers_1.SetRequestCORS)(opts.cors || []));
|
|
7
|
+
app.use((0, helpers_1.SetRateLimiter)(opts.rateLimit || { windowMs: 1000, max: 100 }));
|
|
8
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@increase21/simplenodejs",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.3",
|
|
4
4
|
"description": "Lightweight Node.js HTTP framework with middleware and plugins",
|
|
5
5
|
"dev": "dist/index.js",
|
|
6
|
+
"bugs": "https://github.com/increase21/simplenodejs/issues",
|
|
7
|
+
"main": "dist/index.js",
|
|
6
8
|
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"require": "./dist/index.js",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "https://github.com/increase21/simplenodejs.git",
|
|
19
|
+
"directory": ""
|
|
20
|
+
},
|
|
7
21
|
"files": [
|
|
8
|
-
"dist
|
|
22
|
+
"dist"
|
|
9
23
|
],
|
|
10
24
|
"scripts": {
|
|
11
25
|
"build": "tsc",
|