UNPKG

@senacor/azure-function-middleware

Version:

Middleware for azure functions to handle authentication, authorization, error handling and logging

47 lines (46 loc) 2.8 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.requestBodyValidation = requestBodyValidation; const error_1 = require("../error"); const middleware_1 = require("../middleware"); function requestBodyValidation(schema, options) { var _a, _b, _c; const shouldThrowOnValidationError = (_a = options === null || options === void 0 ? void 0 : options.shouldThrowOnValidationError) !== null && _a !== void 0 ? _a : true; const transformErrorMessage = (_b = options === null || options === void 0 ? void 0 : options.transformErrorMessage) !== null && _b !== void 0 ? _b : ((message) => ({ message })); const printInputOnValidationError = (_c = options === null || options === void 0 ? void 0 : options.printInputOnValidationError) !== null && _c !== void 0 ? _c : true; return (req, context, result) => __awaiter(this, void 0, void 0, function* () { if ((0, middleware_1.isErrorResult)(result)) { context.info('Skipping request body validation because the result is faulty'); return; } const requestBody = yield req .clone() .json() .catch((error) => { context.error('Error during request body validation:', error); throw new error_1.ApplicationError('Failed to get request body for validation', 500); }); const validationResult = schema.validate(requestBody, options === null || options === void 0 ? void 0 : options.joiValidationOptions); if (validationResult.error) { context.error('Request body did not match the given schema:', JSON.stringify(validationResult.error)); if (printInputOnValidationError) { context.info('Invalid request body:', JSON.stringify(requestBody)); } if (shouldThrowOnValidationError) { throw new error_1.ApplicationError('Request body validation error', 400, transformErrorMessage(validationResult.error.message)); } } else { context.info('Request body is valid'); } }); }