@increase21/simplenodejs 1.0.0 → 1.0.2

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 CHANGED
@@ -1,3 +1,5 @@
1
1
  export { CreateSimpleJsHttpServer } from "./server";
2
2
  export * from "./utils/helpers";
3
+ export * from "./utils/simpleController";
4
+ export * from "./utils/simplePlugins";
3
5
  export { Middleware, ErrorMiddleware, SimpleJsServer } from "./typings/general";
package/dist/index.js CHANGED
@@ -18,5 +18,5 @@ exports.CreateSimpleJsHttpServer = void 0;
18
18
  var server_1 = require("./server");
19
19
  Object.defineProperty(exports, "CreateSimpleJsHttpServer", { enumerable: true, get: function () { return server_1.CreateSimpleJsHttpServer; } });
20
20
  __exportStar(require("./utils/helpers"), exports);
21
- // Optional: plugins
22
- // export { SecurityPlugin } from "./plugins/SecurityPlugin";
21
+ __exportStar(require("./utils/simpleController"), exports);
22
+ __exportStar(require("./utils/simplePlugins"), exports);
package/dist/router.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { RequestObject, ResponseObject } from "./typings/context";
1
+ import { RequestObject, ResponseObject } from "./typings/general";
2
2
  export interface ControllerMeta {
3
3
  name: string;
4
- file: string;
5
4
  Controller: any;
6
5
  }
7
6
  export declare function loadControllers(root?: string): Map<string, ControllerMeta>;
package/dist/router.js CHANGED
@@ -23,11 +23,14 @@ function loadControllers(root = "controllers") {
23
23
  //if it's file load the file
24
24
  else if (file.endsWith(".js") || file.endsWith(".ts")) {
25
25
  const mod = require(full);
26
- const Controller = mod.default;
27
- if (Controller) {
28
- const key = full.replace(base, "").replace(/\\/g, "/").replace(/\.(ts|js)$/, "");
29
- map.set(key.toLowerCase(), { name: Controller.name, file: full, Controller });
30
- }
26
+ // const Controller = mod.default;
27
+ if (!full.startsWith(base))
28
+ return;
29
+ const Controller = require(full)?.default;
30
+ if (typeof Controller !== "function")
31
+ return;
32
+ const key = full.replace(base, "").replace(/\\/g, "/").replace(/\.(ts|js)$/, "");
33
+ map.set(key.toLowerCase(), { name: Controller.name, Controller });
31
34
  }
32
35
  }
33
36
  }
@@ -39,19 +42,34 @@ async function route(req, res, controllersDir) {
39
42
  // console.log("Router is called")
40
43
  const url = new URL(req.url, "http://localhost");
41
44
  const parts = url.pathname.replace(/^\/+|\/+$/g, "").split("/");
42
- const controllerPath = "/" + parts.slice(0, -1).join("/");
43
- const methodName = parts[parts.length - 1] || "index";
44
- const id = parts[parts.length];
45
- const meta = controllers.get(controllerPath.toLowerCase());
46
- if (!meta)
47
- return res.status(404).text("The requested resource does not exist");
45
+ let controllerPath = (parts.length > 2 ? "/" + parts.slice(0, 2).join("/") : `/${parts.join("/")}`).toLocaleLowerCase();
46
+ let methodName = parts.length > 2 ? parts[2] : "index";
47
+ let id = methodName !== "index" ? parts.slice(parts.indexOf(methodName) + 1) : null;
48
+ const meta = controllers.get(controllerPath);
49
+ //if the controller is not available or not found
50
+ if (!meta || !meta.name || !meta.Controller)
51
+ return res.status(404).json({ error: "The requested resource does not exist" });
48
52
  const ControllerClass = meta.Controller;
49
- const controller = new ControllerClass(req, res);
53
+ const controller = new ControllerClass();
54
+ //if the endpoint not a function
50
55
  if (typeof controller[methodName] !== "function") {
51
- return res.status(404).text("The requested resource does not exist");
56
+ //if it's using index
57
+ if (typeof controller["index"] === "function" && parts.length === 3) {
58
+ methodName = "index";
59
+ id = parts.slice(2);
60
+ }
61
+ else {
62
+ return res.status(404).json({ error: "The requested resource does not exist" });
63
+ }
64
+ }
65
+ //if the data require params but there's no matching params
66
+ if (id && id.length && (!controller[methodName].length || controller[methodName].length < id.length)) {
67
+ return res.status(404).json({ error: "The requested resource does not exist. Kindly check your url" });
52
68
  }
53
- const result = await controller[methodName](id);
54
- if (!res.writableEnded && result !== undefined) {
69
+ controller._bindContext({ req, res });
70
+ const result = await controller[methodName](...(id || []));
71
+ //if it's not responded
72
+ if (!res.writableEnded && result) {
55
73
  res.setHeader("Content-Type", "application/json");
56
74
  res.end(JSON.stringify(result));
57
75
  }
package/dist/server.d.ts CHANGED
@@ -1,4 +1,3 @@
1
1
  import { IncomingMessage, ServerResponse } from "http";
2
- import { Middleware, RequestObject, ResponseObject, SimpleJsServer } from "./typings/general";
3
- export declare function compose(middlewares: Middleware[]): (req: RequestObject, res: ResponseObject) => Promise<void>;
2
+ import { SimpleJsServer } from "./typings/general";
4
3
  export declare const CreateSimpleJsHttpServer: (handler?: (req: IncomingMessage, res: ServerResponse) => void) => SimpleJsServer;
package/dist/server.js CHANGED
@@ -4,9 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.CreateSimpleJsHttpServer = void 0;
7
- exports.compose = compose;
8
7
  const http_1 = __importDefault(require("http"));
9
8
  const router_1 = require("./router");
9
+ const node_crypto_1 = __importDefault(require("node:crypto"));
10
+ const helpers_1 = require("./utils/helpers");
10
11
  const extension = (req, res) => {
11
12
  //for response status
12
13
  res.status = (code) => {
@@ -25,36 +26,16 @@ const extension = (req, res) => {
25
26
  res.setHeader('Content-Type', 'text/plain');
26
27
  res.end(param);
27
28
  };
29
+ req.id = node_crypto_1.default.randomUUID();
30
+ res.setHeader("X-Request-Id", req.id);
28
31
  };
29
- function compose(middlewares) {
30
- return async function (req, res) {
31
- let idx = -1;
32
- async function dispatch(i) {
33
- if (i <= idx)
34
- throw new Error("next() called twice");
35
- idx = i;
36
- const fn = middlewares[i];
37
- if (!fn)
38
- return;
39
- try {
40
- await fn(req, res, () => dispatch(i + 1));
41
- }
42
- catch (err) {
43
- if (!res.writableEnded) {
44
- res.status(500).json({ error: "Middleware error" });
45
- }
46
- }
47
- }
48
- await dispatch(0);
49
- };
50
- }
51
32
  const CreateSimpleJsHttpServer = (handler) => {
52
33
  const middlewares = [];
53
34
  const errorMiddlewares = [];
54
35
  const plugins = [];
55
36
  const server = http_1.default.createServer(async (req, res) => {
56
37
  extension(req, res);
57
- const run = compose(middlewares);
38
+ const run = (0, helpers_1.composeWithError)(middlewares, errorMiddlewares);
58
39
  try {
59
40
  handler && await handler(req, res);
60
41
  if (res.writableEnded)
@@ -66,11 +47,17 @@ const CreateSimpleJsHttpServer = (handler) => {
66
47
  await (0, router_1.route)(req, res);
67
48
  }
68
49
  catch (err) {
69
- res.statusCode = 500;
70
- res.end("Internal Server Error");
50
+ // 1. Run error middlewares
51
+ for (const mw of errorMiddlewares) {
52
+ await mw(err, req, res, () => { });
53
+ }
54
+ // 2. Safe HTTP response fallback
55
+ if (!res.headersSent) {
56
+ res.statusCode = 503;
57
+ res.end("Service unavailable at the moment");
58
+ }
71
59
  }
72
60
  });
73
- server.setTimeout(60000); //60Seconds
74
61
  server.use = mw => { middlewares.push(mw); };
75
62
  server.useError = mw => errorMiddlewares.push(mw);
76
63
  server.register = async (plugin, opts) => {
@@ -1,22 +1,47 @@
1
1
  import http, { IncomingMessage, ServerResponse } from "http";
2
2
  export type Next = () => Promise<void> | void;
3
3
  export type Plugin = (app: SimpleJsServer, opts?: any) => Promise<void> | void;
4
+ export type ObjectPayload = {
5
+ [key: string]: any;
6
+ };
4
7
  export type Middleware = (req: RequestObject, res: ResponseObject, next: () => Promise<void> | void) => Promise<void> | void;
5
8
  export type ErrorMiddleware = (err: any, req: RequestObject, res: ResponseObject, next: Next) => Promise<void> | void;
6
9
  export interface SimpleJsServer extends http.Server {
7
10
  use(mw: Middleware): Promise<any> | void;
8
11
  useError: (mw: ErrorMiddleware) => void;
9
12
  register: (plugin: Plugin, opts?: any) => Promise<void>;
13
+ _environment: 'dev' | 'stag' | 'live';
10
14
  }
11
15
  export interface RequestObject extends IncomingMessage {
12
16
  body?: any;
13
17
  query?: any;
14
18
  _server_environment?: 'dev' | 'stag' | 'live';
15
- _body_size?: 0;
19
+ id?: string;
16
20
  }
17
21
  export interface ResponseObject extends ServerResponse {
18
22
  status: (value: number) => ResponseObject;
19
23
  json: (value: object) => void;
20
24
  text: (value?: string) => void;
21
25
  }
26
+ export interface SubRequestHandler {
27
+ post?: (params: PrivateMethodProps) => void;
28
+ put?: (params: PrivateMethodProps) => void;
29
+ get?: (params: PrivateMethodProps) => void;
30
+ delete?: (params: PrivateMethodProps) => void;
31
+ patch?: (params: PrivateMethodProps) => void;
32
+ }
33
+ export interface PrivateMethodProps {
34
+ body: ObjectPayload;
35
+ res: ResponseObject;
36
+ req: RequestObject;
37
+ query: ObjectPayload;
38
+ id?: string;
39
+ idMethod?: {
40
+ post?: 'required' | 'optional';
41
+ get?: 'required' | 'optional';
42
+ put?: 'required' | 'optional';
43
+ delete?: 'required' | 'optional';
44
+ patch?: 'required' | 'optional';
45
+ };
46
+ }
22
47
  export type AcceptHeaderValue = 'application/media' | 'application/text';
@@ -0,0 +1,8 @@
1
+ export type SimpleJSRateLimitType = {
2
+ windowMs: number;
3
+ max: number;
4
+ keyGenerator?: (req: any) => string;
5
+ };
6
+ export type SimpleJSBodyParseType = {
7
+ limit?: string | number;
8
+ };
@@ -1,17 +1,10 @@
1
- import { RequestObject, ResponseObject } from "../typings/context";
2
- import { ErrorMiddleware, Middleware, SimpleJsServer } from "../typings/general";
1
+ import { RequestObject, ResponseObject } from "../typings/general";
2
+ import { ErrorMiddleware, Middleware } from "../typings/general";
3
+ import { SimpleJSBodyParseType, SimpleJSRateLimitType } from "../typings/simpletypes";
3
4
  export declare function SetRequestCORS(opts: {
4
5
  name: string;
5
6
  value: string;
6
7
  }[]): (req: RequestObject, res: ResponseObject, next: any) => Promise<void>;
7
- export declare function SetRateLimiter(opts: {
8
- windowMs: number;
9
- max: number;
10
- keyGenerator?: (req: any) => string;
11
- }): (req: RequestObject, res: ResponseObject, next: () => Promise<any> | void) => Promise<void>;
12
- export declare function SetBodyParser(opts: {
13
- limit?: string | number;
14
- json?: boolean;
15
- }): (req: RequestObject, res: ResponseObject, next: () => Promise<any> | void) => 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>;
16
10
  export declare function composeWithError(middlewares: Middleware[], errorMiddlewares: ErrorMiddleware[]): (req: RequestObject, res: ResponseObject) => Promise<void>;
17
- export declare function SecurityPlugin(app: SimpleJsServer, opts: any): void;
@@ -7,15 +7,18 @@ exports.SetRequestCORS = SetRequestCORS;
7
7
  exports.SetRateLimiter = SetRateLimiter;
8
8
  exports.SetBodyParser = SetBodyParser;
9
9
  exports.composeWithError = composeWithError;
10
- exports.SecurityPlugin = SecurityPlugin;
11
10
  const node_querystring_1 = __importDefault(require("node:querystring"));
12
11
  // core/cors.ts
13
12
  function SetRequestCORS(opts) {
14
13
  return async (req, res, next) => {
15
14
  const defaults = {
16
15
  "Access-Control-Allow-Origin": "*",
17
- "Access-Control-Allow-Headers": "Authorization",
18
- "Access-Control-Allow-Methods": "GET, POST"
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'",
19
22
  };
20
23
  let merged = { ...defaults };
21
24
  for (const { name, value } of opts) {
@@ -23,13 +26,17 @@ function SetRequestCORS(opts) {
23
26
  }
24
27
  //allow credentials only when origin specified
25
28
  if (merged["Access-Control-Allow-Credentials"] === "true") {
26
- merged["Access-Control-Allow-Origin"] = req.headers.origin || "null";
29
+ const origin = req.headers.origin;
30
+ res.status(403).end();
31
+ if (!origin)
32
+ return;
33
+ merged["Access-Control-Allow-Origin"] = origin;
27
34
  }
28
35
  for (const [key, value] of Object.entries(merged)) {
29
36
  res.setHeader(key, value);
30
37
  }
31
38
  if (req.method === "OPTIONS") {
32
- res.status(204).text();
39
+ res.status(204).end();
33
40
  return;
34
41
  }
35
42
  await next();
@@ -38,9 +45,18 @@ function SetRequestCORS(opts) {
38
45
  // core/rateLimit.ts
39
46
  function SetRateLimiter(opts) {
40
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();
41
56
  return async (req, res, next) => {
42
- const key = opts.keyGenerator?.(req) || req.socket.remoteAddress || "global";
43
- const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
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");
44
60
  const now = Date.now();
45
61
  const entry = store.get(key) || { count: 0, ts: now };
46
62
  if (now - entry.ts > opts.windowMs) {
@@ -50,16 +66,10 @@ function SetRateLimiter(opts) {
50
66
  entry.count++;
51
67
  store.set(key, entry);
52
68
  if (entry.count > opts.max) {
69
+ res.setHeader("Retry-After", Math.ceil(opts.windowMs / 1000));
53
70
  res.status(429).json({ error: "Too Many Requests" });
54
71
  return;
55
72
  }
56
- setInterval(() => {
57
- const now = Date.now();
58
- for (const [k, v] of store) {
59
- if (now - v.ts > opts.windowMs * 2)
60
- store.delete(k);
61
- }
62
- }, opts.windowMs);
63
73
  await next();
64
74
  };
65
75
  }
@@ -157,8 +167,3 @@ function composeWithError(middlewares, errorMiddlewares) {
157
167
  await dispatch(0);
158
168
  };
159
169
  }
160
- function SecurityPlugin(app, opts) {
161
- app.use(SetRequestCORS(opts.cors || []));
162
- app.use(SetRateLimiter(opts.rateLimit || { windowMs: 1000, max: 100 }));
163
- app.use(SetBodyParser(opts.body || { limit: "1mb" }));
164
- }
@@ -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 SecurityPlugin(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.SecurityPlugin = SecurityPlugin;
4
+ const helpers_1 = require("./helpers");
5
+ function SecurityPlugin(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,20 +1,32 @@
1
1
  {
2
2
  "name": "@increase21/simplenodejs",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Lightweight Node.js HTTP framework with middleware and plugins",
5
- "main": "dist/index.js",
5
+ "dev": "dist/index.js",
6
+ "bugs": "https://github.com/increase21/simplenodejs/issues",
6
7
  "types": "dist/index.d.ts",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/increase21/simplenodejs.git",
11
+ "directory": ""
12
+ },
7
13
  "files": [
8
14
  "dist/**/*"
9
15
  ],
10
16
  "scripts": {
11
17
  "build": "tsc",
12
- "test": "node dist/test.js"
18
+ "test": "node dist/test.js",
19
+ "dev": "nodemon server.ts"
13
20
  },
14
- "keywords": ["http", "framework", "node", "typescript"],
21
+ "keywords": [
22
+ "http",
23
+ "framework",
24
+ "node",
25
+ "typescript"
26
+ ],
15
27
  "author": "Increase Nkanta",
16
28
  "license": "MIT",
17
29
  "devDependencies": {
18
30
  "typescript": "^5.3.0"
19
31
  }
20
- }
32
+ }
package/readme.md ADDED
File without changes
@@ -1,18 +0,0 @@
1
- import { IncomingMessage, ServerResponse } from "http";
2
- export interface Context {
3
- req: IncomingMessage;
4
- res: ServerResponse;
5
- body?: any;
6
- params?: Record<string, string>;
7
- }
8
- export interface RequestObject extends IncomingMessage {
9
- body?: any;
10
- query?: any;
11
- _server_environment?: 'dev' | 'stag' | 'live';
12
- _body_size?: 0;
13
- }
14
- export interface ResponseObject extends ServerResponse {
15
- status: (value: number) => ResponseObject;
16
- json: (value: object) => void;
17
- text: (value?: string) => void;
18
- }
File without changes