@wxn0brp/falcon-frame 0.5.9 → 0.6.0

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/README.md CHANGED
@@ -22,7 +22,7 @@ yarn add @wxn0brp/falcon-frame
22
22
  ## 🚦 Usage Example
23
23
 
24
24
  ```ts
25
- import FalconFrame from "@wxn0brp/falcon-frame";
25
+ import FalconFrame, { validateBody } from "@wxn0brp/falcon-frame";
26
26
  const app = new FalconFrame();
27
27
 
28
28
  app.setOrigin("*");
@@ -67,22 +67,18 @@ app.post("/login", (req, res) => {
67
67
  res.status(401).json({ status: "fail", message: "Invalid credentials" });
68
68
  });
69
69
 
70
- app.post("/register", (req, res, next) => {
71
- const { valid, validErrors } = req.valid({
70
+ app.post(
71
+ "/register",
72
+ validateBody({
72
73
  username: "required|string|min:3|max:20",
73
74
  password: "required|string|min:8",
74
- });
75
-
76
- if (!valid) {
77
- return res.status(400).json({ status: "error", errors: validErrors });
75
+ }),
76
+ (req, res) => {
77
+ const { username, password } = req.body;
78
+ USERS[username] = password;
79
+ return { status: "success", message: "User registered successfully" };
78
80
  }
79
-
80
- next();
81
- }, (req, res) => {
82
- const { username, password } = req.body;
83
- USERS[username] = password;
84
- return { status: "success", message: "User registered successfully" };
85
- });
81
+ );
86
82
 
87
83
  // Protected route
88
84
  app.get("/dashboard", requireAuth, (req, res) => {
@@ -1,6 +1,6 @@
1
- import FalconFrame from "./index.js";
1
+ import FalconFrame, { FFResponse } from "./index.js";
2
2
  import type { FFRequest, ParseBodyFunction, RouteHandler, StandardBodyParserOptions } from "./types.js";
3
3
  export declare function parseLimit(limit: string | number): number;
4
4
  export declare function getContentType(req: FFRequest): string | undefined;
5
- export declare function getRawBody(req: FFRequest, limit: number): Promise<string>;
5
+ export declare function getRawBody(req: FFRequest, res: FFResponse, limit: number): Promise<string>;
6
6
  export declare function getStandardBodyParser(type: string, parser: ParseBodyFunction, FF: FalconFrame, opts: StandardBodyParserOptions): RouteHandler;
@@ -25,16 +25,18 @@ export function parseLimit(limit) {
25
25
  export function getContentType(req) {
26
26
  return req.headers["content-type"]?.split(";")[0].toLowerCase();
27
27
  }
28
- export function getRawBody(req, limit) {
28
+ export function getRawBody(req, res, limit) {
29
29
  return new Promise((resolve, reject) => {
30
30
  let body = "";
31
31
  req.on("data", (chunk) => {
32
32
  body += chunk.toString();
33
33
  if (limit && body.length > limit) {
34
34
  const error = new Error("Payload Too Large");
35
- // @ts-ignore
36
- error.statusCode = 413;
35
+ res.status(413);
36
+ res.FF._413(req, res);
37
37
  req.destroy();
38
+ // @ts-ignore
39
+ error.cancel = true;
38
40
  return reject(error);
39
41
  }
40
42
  });
@@ -53,13 +55,14 @@ export function getStandardBodyParser(type, parser, FF, opts) {
53
55
  return next();
54
56
  }
55
57
  try {
56
- const body = await getRawBody(req, limit);
58
+ const body = await getRawBody(req, res, limit);
57
59
  req.body = await parser(body, req, FF);
60
+ next();
58
61
  }
59
62
  catch (err) {
63
+ if (err.cancel)
64
+ return;
60
65
  req.body = {};
61
- }
62
- finally {
63
66
  next();
64
67
  }
65
68
  };
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import http from "http";
3
3
  import { renderHTML } from "./render.js";
4
4
  import { FFResponse } from "./res.js";
5
5
  import { Router } from "./router.js";
6
- import type { BeforeHandleRequest, EngineCallback, FFRequest, RouteHandler } from "./types.js";
6
+ import type { BeforeHandleRequest, EngineCallback, ErrorHandler, FFRequest, RouteHandler, ValidationErrorFormatter } from "./types.js";
7
7
  export interface Opts {
8
8
  loggerOpts?: LoggerOptions;
9
9
  bodyLimit?: string;
@@ -16,7 +16,10 @@ export declare class FalconFrame<Vars extends Record<string, any> = any> extends
16
16
  vars: Vars;
17
17
  opts: Opts;
18
18
  engines: Record<string, EngineCallback>;
19
+ _400_formatter: ValidationErrorFormatter;
19
20
  _404: RouteHandler;
21
+ _413: RouteHandler;
22
+ _500: ErrorHandler;
20
23
  constructor(opts?: Partial<Opts>);
21
24
  addBodyParser(parser: RouteHandler): this;
22
25
  listen(port: number | string, callback?: (() => void) | boolean, beforeHandleRequest?: BeforeHandleRequest): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
@@ -40,8 +43,12 @@ export declare class FalconFrame<Vars extends Record<string, any> = any> extends
40
43
  * @returns The server object returned by the listen method.
41
44
  */
42
45
  l(port: number): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
46
+ set400Formatter(formatter: ValidationErrorFormatter): void;
43
47
  set404(handler: RouteHandler): void;
48
+ set413(handler: RouteHandler): void;
49
+ set500(handler: ErrorHandler): void;
44
50
  }
45
51
  export default FalconFrame;
46
52
  export * as Helpers from "./helpers.js";
53
+ export { validateBody } from "./valid.js";
47
54
  export { FFRequest, FFResponse, renderHTML, RouteHandler, Router };
package/dist/index.js CHANGED
@@ -12,9 +12,22 @@ export class FalconFrame extends Router {
12
12
  vars = {};
13
13
  opts = {};
14
14
  engines = {};
15
+ _400_formatter = (err) => {
16
+ return {
17
+ err: true,
18
+ msg: "Bad request",
19
+ errors: err,
20
+ };
21
+ };
15
22
  _404 = (req, res) => {
16
23
  res.end("404: File had second thoughts");
17
24
  };
25
+ _413 = (req, res) => {
26
+ res.end("413: Cat is too fat");
27
+ };
28
+ _500 = (err, req, res) => {
29
+ res.end("500: The code had an existential crisis");
30
+ };
18
31
  constructor(opts = {}) {
19
32
  super();
20
33
  const loggerOpts = opts?.loggerOpts || {};
@@ -119,10 +132,20 @@ export class FalconFrame extends Router {
119
132
  l(port) {
120
133
  return this.listen(+process.env.PORT || port, true);
121
134
  }
135
+ set400Formatter(formatter) {
136
+ this._400_formatter = formatter;
137
+ }
122
138
  set404(handler) {
123
139
  this._404 = handler;
124
140
  }
141
+ set413(handler) {
142
+ this._413 = handler;
143
+ }
144
+ set500(handler) {
145
+ this._500 = handler;
146
+ }
125
147
  }
126
148
  export default FalconFrame;
127
149
  export * as Helpers from "./helpers.js";
150
+ export { validateBody } from "./valid.js";
128
151
  export { FFResponse, renderHTML, Router };
package/dist/req.js CHANGED
@@ -61,15 +61,24 @@ export function handleRequest(req, res, FF) {
61
61
  }
62
62
  }
63
63
  req.middleware = middleware;
64
- const result = await middleware.middleware(req, res, next);
65
- if (result && !res._ended) {
66
- if (typeof result === "string") {
67
- return res.end(result);
64
+ try {
65
+ const result = await middleware.middleware(req, res, next);
66
+ if (result && !res._ended) {
67
+ if (typeof result === "string") {
68
+ return res.end(result);
69
+ }
70
+ else if (typeof result === "object") {
71
+ if (result instanceof FFResponse)
72
+ return res.end();
73
+ return res.json(result);
74
+ }
68
75
  }
69
- else if (typeof result === "object") {
70
- if (result instanceof FFResponse)
71
- return res.end();
72
- return res.json(result);
76
+ }
77
+ catch (err) {
78
+ logger.error(`Unhandled error in middleware for path [${middleware.path}]:`, err.stack || err);
79
+ if (!res.headersSent && !res.writableEnded) {
80
+ res.status(500);
81
+ FF._500(err, req, res);
73
82
  }
74
83
  }
75
84
  }
package/dist/types.d.ts CHANGED
@@ -2,6 +2,7 @@ import FalconFrame from "./index.js";
2
2
  import { FFResponse } from "./res.js";
3
3
  import http from "http";
4
4
  export type RouteHandler = (req: FFRequest, res: FFResponse, next?: () => void) => void | any;
5
+ export type ErrorHandler = (err: Error, req: FFRequest, res: FFResponse) => void | any;
5
6
  export type Method = "get" | "post" | "put" | "delete" | "all";
6
7
  export interface Params {
7
8
  [key: string]: string;
@@ -53,6 +54,7 @@ export interface ValidationResult {
53
54
  [key: string]: string[];
54
55
  };
55
56
  }
57
+ export type ValidationErrorFormatter = (errors: ValidationResult["validErrors"]) => Record<string, any>;
56
58
  export type BeforeHandleRequest = (req: http.IncomingMessage, res: http.ServerResponse) => any;
57
59
  export interface StaticServeOptions {
58
60
  utf8?: boolean;
package/dist/valid.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- import { ValidationResult, ValidationSchema } from "./types.js";
1
+ import { RouteHandler, ValidationResult, ValidationSchema } from "./types.js";
2
2
  export declare function validate(schema: ValidationSchema, data: any): ValidationResult;
3
+ export declare function validateBody(schema: ValidationSchema): RouteHandler;
package/dist/valid.js CHANGED
@@ -56,3 +56,13 @@ export function validate(schema, data) {
56
56
  }
57
57
  return { valid: isValid, validErrors: errors };
58
58
  }
59
+ export function validateBody(schema) {
60
+ return (req, res, next) => {
61
+ const validationResult = req.valid(schema);
62
+ if (validationResult.valid) {
63
+ return next ? next() : undefined;
64
+ }
65
+ const errorResponse = res.FF._400_formatter(validationResult.validErrors);
66
+ res.status(400).json(errorResponse);
67
+ };
68
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wxn0brp/falcon-frame",
3
- "version": "0.5.9",
3
+ "version": "0.6.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "author": "wxn0brP",