diff --git a/CHANGELOG.md b/CHANGELOG.md index e12dd13..469db64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -* +* Support for fastify handlers and structures ### Changed diff --git a/package.json b/package.json index 9db021d..4b4a51b 100644 --- a/package.json +++ b/package.json @@ -22,18 +22,20 @@ "typings": "index.ts", "peerDependencies": { "dotenv": "^16.4.5", + "fastify": "^4.26.1", "hive-js-util": "^0.5.3", "yonius": "^0.13.11" }, "devDependencies": { "@types/chai": "^4.3.12", "@types/mocha": "^10.0.6", - "@types/node": "^20.11.21", + "@types/node": "^20.11.24", "@typescript-eslint/eslint-plugin": "^7.1.0", "@typescript-eslint/parser": "^7.1.0", "chai": "^5.1.0", "dotenv": "^16.4.5", "eslint": "^8.57.0", + "fastify": "^4.26.1", "hive-js-util": "^0.5.3", "mocha": "^10.3.0", "mocha-cli": "^1.0.1", diff --git a/ts/fastify.ts b/ts/fastify.ts new file mode 100644 index 0000000..f044ae7 --- /dev/null +++ b/ts/fastify.ts @@ -0,0 +1,30 @@ +import { FastifyRequest, FastifyReply } from "fastify"; +import { Error } from "./structs"; + +export const errorHandlerFastify = ( + errG: globalThis.Error, + req: FastifyRequest, + res: FastifyReply +) => { + const err = errG as unknown as Error; + const code = + err.code && Number(err.code) >= 100 && Number(err.code) < 600 + ? Number(err.code) + : 500; + const result: { + error: string; + code: number; + stack?: string[]; + } = { error: err.message, code: code }; + if (process.env.NODE_ENV !== "production") { + result.stack = err.stack ? err.stack.split("\n") : []; + } + res.code(result.code).send(result); +}; + +export const notFoundHandlerFastify = ( + req: FastifyRequest, + res: FastifyReply +) => { + res.code(404).send({ error: "Route not found", code: 404 }); +}; diff --git a/ts/index.ts b/ts/index.ts index 291e884..f18da5d 100644 --- a/ts/index.ts +++ b/ts/index.ts @@ -1,3 +1,5 @@ -export * from "./fs"; export * from "./boot"; +export * from "./fastify"; +export * from "./fs"; export * from "./logging"; +export * from "./structs"; diff --git a/ts/structs.ts b/ts/structs.ts new file mode 100644 index 0000000..a1a3cea --- /dev/null +++ b/ts/structs.ts @@ -0,0 +1,5 @@ +export type Error = { + message: string; + code: number; + stack?: string; +};