@increase21/simplenodejs 1.0.2 → 1.0.4

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,5 +1,3 @@
1
1
  export { CreateSimpleJsHttpServer } from "./server";
2
- export * from "./utils/helpers";
3
- export * from "./utils/simpleController";
4
- export * from "./utils/simplePlugins";
5
- export { Middleware, ErrorMiddleware, SimpleJsServer } from "./typings/general";
2
+ export { SetRequestCORS, SetRateLimiter, SetBodyParser } from "./utils/helpers";
3
+ export type { SimpleJsPrivateMethodProps } from "./typings/general";
package/dist/index.js CHANGED
@@ -1,22 +1,9 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.CreateSimpleJsHttpServer = void 0;
3
+ exports.SetBodyParser = exports.SetRateLimiter = exports.SetRequestCORS = exports.CreateSimpleJsHttpServer = void 0;
18
4
  var server_1 = require("./server");
19
5
  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);
6
+ var helpers_1 = require("./utils/helpers");
7
+ Object.defineProperty(exports, "SetRequestCORS", { enumerable: true, get: function () { return helpers_1.SetRequestCORS; } });
8
+ Object.defineProperty(exports, "SetRateLimiter", { enumerable: true, get: function () { return helpers_1.SetRateLimiter; } });
9
+ Object.defineProperty(exports, "SetBodyParser", { enumerable: true, get: function () { return helpers_1.SetBodyParser; } });
package/dist/router.d.ts CHANGED
@@ -1,7 +1,5 @@
1
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>;
2
+ import { SimpleJsControllerMeta } from "./typings/simpletypes";
3
+ export declare function loadControllers(root?: string): Map<string, SimpleJsControllerMeta>;
4
+ export declare function setControllersDir(dir: string): void;
7
5
  export declare function route(req: RequestObject, res: ResponseObject, controllersDir?: string): Promise<void>;
package/dist/router.js CHANGED
@@ -4,10 +4,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.loadControllers = loadControllers;
7
+ exports.setControllersDir = setControllersDir;
7
8
  exports.route = route;
8
9
  // router.ts
9
10
  const node_fs_1 = __importDefault(require("node:fs"));
10
11
  const node_path_1 = __importDefault(require("node:path"));
12
+ let controllers = new Map();
11
13
  function loadControllers(root = "controllers") {
12
14
  const base = node_path_1.default.resolve(process.cwd(), root);
13
15
  const map = new Map();
@@ -37,7 +39,9 @@ function loadControllers(root = "controllers") {
37
39
  walk(base);
38
40
  return map;
39
41
  }
40
- const controllers = loadControllers();
42
+ function setControllersDir(dir) {
43
+ controllers = loadControllers(dir);
44
+ }
41
45
  async function route(req, res, controllersDir) {
42
46
  // console.log("Router is called")
43
47
  const url = new URL(req.url, "http://localhost");
@@ -66,7 +70,11 @@ async function route(req, res, controllersDir) {
66
70
  if (id && id.length && (!controller[methodName].length || controller[methodName].length < id.length)) {
67
71
  return res.status(404).json({ error: "The requested resource does not exist. Kindly check your url" });
68
72
  }
69
- controller._bindContext({ req, res });
73
+ //bind the controller to use the global properties
74
+ controller.__bindContext({ req, res });
75
+ ////if there's protected function to run
76
+ if (typeof controller.__checkContext === "function")
77
+ controller.__checkContext();
70
78
  const result = await controller[methodName](...(id || []));
71
79
  //if it's not responded
72
80
  if (!res.writableEnded && result) {
package/dist/server.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  import { IncomingMessage, ServerResponse } from "http";
2
2
  import { SimpleJsServer } from "./typings/general";
3
- export declare const CreateSimpleJsHttpServer: (handler?: (req: IncomingMessage, res: ServerResponse) => void) => SimpleJsServer;
3
+ export declare const CreateSimpleJsHttpServer: (handler?: (req: IncomingMessage, res: ServerResponse) => void, opts?: {
4
+ controllersDir: string;
5
+ }) => SimpleJsServer;
package/dist/server.js CHANGED
@@ -29,10 +29,13 @@ const extension = (req, res) => {
29
29
  req.id = node_crypto_1.default.randomUUID();
30
30
  res.setHeader("X-Request-Id", req.id);
31
31
  };
32
- const CreateSimpleJsHttpServer = (handler) => {
32
+ const CreateSimpleJsHttpServer = (handler, opts) => {
33
33
  const middlewares = [];
34
34
  const errorMiddlewares = [];
35
35
  const plugins = [];
36
+ //set the director of the controller
37
+ if (opts?.controllersDir)
38
+ (0, router_1.setControllersDir)(opts.controllersDir);
36
39
  const server = http_1.default.createServer(async (req, res) => {
37
40
  extension(req, res);
38
41
  const run = (0, helpers_1.composeWithError)(middlewares, errorMiddlewares);
@@ -60,9 +63,9 @@ const CreateSimpleJsHttpServer = (handler) => {
60
63
  });
61
64
  server.use = mw => { middlewares.push(mw); };
62
65
  server.useError = mw => errorMiddlewares.push(mw);
63
- server.register = async (plugin, opts) => {
66
+ server.registerPlugin = async (plugin) => {
64
67
  plugins.push(plugin);
65
- await plugin(server, opts);
68
+ await plugin(server);
66
69
  };
67
70
  return server;
68
71
  };
@@ -1,6 +1,7 @@
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 HttpMethod = "get" | "post" | "put" | "patch" | "delete";
4
5
  export type ObjectPayload = {
5
6
  [key: string]: any;
6
7
  };
@@ -9,14 +10,15 @@ export type ErrorMiddleware = (err: any, req: RequestObject, res: ResponseObject
9
10
  export interface SimpleJsServer extends http.Server {
10
11
  use(mw: Middleware): Promise<any> | void;
11
12
  useError: (mw: ErrorMiddleware) => void;
12
- register: (plugin: Plugin, opts?: any) => Promise<void>;
13
+ registerPlugin: (plugin: Plugin) => Promise<void>;
13
14
  _environment: 'dev' | 'stag' | 'live';
14
15
  }
15
16
  export interface RequestObject extends IncomingMessage {
16
17
  body?: any;
17
18
  query?: any;
18
- _server_environment?: 'dev' | 'stag' | 'live';
19
19
  id?: string;
20
+ _server_environment?: 'dev' | 'stag' | 'live';
21
+ _custom_data?: ObjectPayload;
20
22
  }
21
23
  export interface ResponseObject extends ServerResponse {
22
24
  status: (value: number) => ResponseObject;
@@ -24,13 +26,13 @@ export interface ResponseObject extends ServerResponse {
24
26
  text: (value?: string) => void;
25
27
  }
26
28
  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;
29
+ post?: (params: SimpleJsPrivateMethodProps) => void;
30
+ put?: (params: SimpleJsPrivateMethodProps) => void;
31
+ get?: (params: SimpleJsPrivateMethodProps) => void;
32
+ delete?: (params: SimpleJsPrivateMethodProps) => void;
33
+ patch?: (params: SimpleJsPrivateMethodProps) => void;
32
34
  }
33
- export interface PrivateMethodProps {
35
+ export interface SimpleJsPrivateMethodProps {
34
36
  body: ObjectPayload;
35
37
  res: ResponseObject;
36
38
  req: RequestObject;
@@ -6,3 +6,7 @@ export type SimpleJSRateLimitType = {
6
6
  export type SimpleJSBodyParseType = {
7
7
  limit?: string | number;
8
8
  };
9
+ export interface SimpleJsControllerMeta {
10
+ name: string;
11
+ Controller: any;
12
+ }
@@ -1,5 +1,4 @@
1
- import { RequestObject, ResponseObject } from "../typings/general";
2
- type HttpMethod = "get" | "post" | "put" | "patch" | "delete";
1
+ import { HttpMethod, ObjectPayload, RequestObject, ResponseObject } from "../typings/general";
3
2
  type SubRequestHandler = Partial<Record<HttpMethod, (params: PrivateMethodProps) => any>>;
4
3
  interface PrivateMethodProps {
5
4
  id?: string;
@@ -8,11 +7,16 @@ interface PrivateMethodProps {
8
7
  export declare class SimpleNodeJsController {
9
8
  protected req: RequestObject;
10
9
  protected res: ResponseObject;
10
+ protected body: ObjectPayload;
11
+ protected query: ObjectPayload;
12
+ protected method: HttpMethod;
13
+ protected _custom_data: any;
11
14
  /** framework-internal method */
12
- _bindContext(ctx: {
15
+ __bindContext(ctx: {
13
16
  req: RequestObject;
14
17
  res: ResponseObject;
15
18
  }): void;
19
+ __checkContext(): void;
16
20
  protected RunRequest(handlers: SubRequestHandler, params?: PrivateMethodProps): any;
17
21
  }
18
22
  export {};
@@ -3,25 +3,30 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SimpleNodeJsController = void 0;
4
4
  class SimpleNodeJsController {
5
5
  /** framework-internal method */
6
- _bindContext(ctx) {
6
+ __bindContext(ctx) {
7
7
  this.req = ctx.req;
8
8
  this.res = ctx.res;
9
+ this.body = ctx.req.body;
10
+ this.query = ctx.req.query;
11
+ this.method = (ctx.req.method || "").toLocaleLowerCase();
12
+ this._custom_data = ctx.req._custom_data;
9
13
  }
14
+ __checkContext() { }
10
15
  RunRequest(handlers, params) {
11
16
  const method = this.req.method?.toLowerCase();
12
17
  if (!method) {
13
- return this.res.status(400).json({ code: 400, msg: "Invalid HTTP Method" });
18
+ return this.res.status(400).json({ code: 400, error: "Invalid HTTP Method" });
14
19
  }
15
20
  const runFn = handlers[method];
16
21
  if (typeof runFn !== "function") {
17
- return this.res.status(405).json({ code: 405, msg: "Method Not Allowed" });
22
+ return this.res.status(405).json({ code: 405, error: "Method Not Allowed" });
18
23
  }
19
24
  // ID validation rules
20
25
  if (params && params.id && (!params.idMethod || !params.idMethod[method])) {
21
- return this.res.status(404).json({ code: 404, msg: "Resource not found" });
26
+ return this.res.status(404).json({ code: 404, error: "Resource not found" });
22
27
  }
23
28
  if (params && params.idMethod?.[method] === "required" && !params.id) {
24
- return this.res.status(404).json({ code: 404, msg: "Resource not found" });
29
+ return this.res.status(404).json({ code: 404, error: "Resource not found" });
25
30
  }
26
31
  return runFn({
27
32
  ...(params || {}),
@@ -1,6 +1,6 @@
1
1
  import { SimpleJsServer } from "../typings/general";
2
2
  import { SimpleJSRateLimitType } from "../typings/simpletypes";
3
- export declare function SecurityPlugin(app: SimpleJsServer, opts: {
3
+ export declare function SimpleJsSecurityPlugin(app: SimpleJsServer, opts: {
4
4
  cors?: {
5
5
  name: string;
6
6
  value: string;
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SecurityPlugin = SecurityPlugin;
3
+ exports.SimpleJsSecurityPlugin = SimpleJsSecurityPlugin;
4
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 }));
5
+ function SimpleJsSecurityPlugin(app, opts) {
6
+ opts.cors && app.use((0, helpers_1.SetRequestCORS)(opts.cors || []));
7
+ opts.rateLimit && app.use((0, helpers_1.SetRateLimiter)(opts.rateLimit || { windowMs: 1000, max: 100 }));
8
8
  }
package/package.json CHANGED
@@ -1,17 +1,25 @@
1
1
  {
2
2
  "name": "@increase21/simplenodejs",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Lightweight Node.js HTTP framework with middleware and plugins",
5
5
  "dev": "dist/index.js",
6
6
  "bugs": "https://github.com/increase21/simplenodejs/issues",
7
+ "main": "dist/index.js",
7
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
+ },
8
16
  "repository": {
9
17
  "type": "git",
10
18
  "url": "https://github.com/increase21/simplenodejs.git",
11
19
  "directory": ""
12
20
  },
13
21
  "files": [
14
- "dist/**/*"
22
+ "dist"
15
23
  ],
16
24
  "scripts": {
17
25
  "build": "tsc",