UNPKG

@senacor/azure-function-middleware

Version:

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

47 lines (46 loc) 2.69 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.responseBodyValidation = responseBodyValidation; const error_1 = require("../error"); const middleware_1 = require("../middleware"); function responseBodyValidation(schemas, options) { var _a, _b; const shouldThrowOnValidationError = (_a = options === null || options === void 0 ? void 0 : options.shouldThrowOnValidationError) !== null && _a !== void 0 ? _a : false; const printInputOnValidationError = (_b = options === null || options === void 0 ? void 0 : options.printInputOnValidationError) !== null && _b !== void 0 ? _b : true; return (req, context, result) => __awaiter(this, void 0, void 0, function* () { if ((0, middleware_1.isErrorResult)(result)) { context.info(`Skipping response body validation because the result is faulty`); return; } const httpResponse = result.$result; const responseStatus = httpResponse.status; if (!responseStatus || !schemas[responseStatus]) { if (shouldThrowOnValidationError) { throw new error_1.ApplicationError(`Response body validation error as there is no schema for status ${responseStatus}`, 500); } return; } const validationResult = schemas[responseStatus].validate(httpResponse.jsonBody, options === null || options === void 0 ? void 0 : options.joiValidationOptions); if (validationResult.error) { context.error('Response body did not match the given schema:', JSON.stringify(validationResult.error)); if (printInputOnValidationError) { context.info('Invalid response body:', JSON.stringify(httpResponse.jsonBody)); } if (shouldThrowOnValidationError) { throw new error_1.ApplicationError('Response body validation error', 500); } } else { context.info('Response body is valid'); } }); }