UNPKG

@d3vtool/kazejs

Version:

A flexible Node.js web framework built with TypeScript, focusing on dependency injection, routing, middleware, and schema validation. Supports dynamic routes, global middleware, static files, and customizable error handling for scalable apps.

67 lines (66 loc) 2.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ObjectValidationError = exports.ValidationError = exports.Validator = void 0; exports.queryValidate = queryValidate; exports.paramsValidate = paramsValidate; const kaze_errors_1 = require("./kaze-errors"); const utils_1 = require("@d3vtool/utils"); Object.defineProperty(exports, "Validator", { enumerable: true, get: function () { return utils_1.Validator; } }); Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return utils_1.ValidationError; } }); Object.defineProperty(exports, "ObjectValidationError", { enumerable: true, get: function () { return utils_1.ObjectValidationError; } }); function queryValidate(schema, noQueryErrorMsg = "No queries found to validate") { return function (ctx, next) { if (!(schema instanceof Object)) { throw new kaze_errors_1.KazeValidationError({ error: ["Invalid schema"] }); } if (!ctx.req.query) { throw new Error(noQueryErrorMsg); } const errors = schema.validateSafely(ctx.req.query); if (Object.keys(errors).length > 0) { // send all errors to global error handler // let user decide what to do with them. throw new kaze_errors_1.KazeValidationError(errors); } try { ctx.req.query = JSON.parse(ctx.req.query); } catch (err) { const msg = `Invalid Query: ${(err instanceof Error) ? err.message : "Query structure is invalid."}`; throw new kaze_errors_1.KazeValidationError({ error: [msg] }); } next(); }; } function paramsValidate(schema, noParamsErrorMsg = "No params found to validate") { return function (ctx, next) { if (!(schema instanceof Object)) { throw new kaze_errors_1.KazeValidationError({ error: ["Invalid schema"] }); } if (!ctx.req.params) { throw new Error(noParamsErrorMsg); } const errors = schema.validateSafely(ctx.req.params); if (Object.keys(errors).length > 0) { // send all errors to global error handler // let user decide what to do with them. throw new kaze_errors_1.KazeValidationError(errors); } try { ctx.req.params = JSON.parse(ctx.req.params); } catch (err) { const msg = `Invalid Params: ${(err instanceof Error) ? err.message : "Params body is invalid."}`; throw new kaze_errors_1.KazeValidationError({ error: [msg] }); } next(); }; }