"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpLogPayloadMiddleware = exports.HttpMiddleware = void 0;
const http_1 = require("@deepkit/http");
/*@ts-ignore*/
var { __ΩScopedLogger } = require('@deepkit/logger');
const cors_1 = require("./cors");
// Deepkit's middleware code returns a 404 if the middleware throws an error
// we want to properly handle HTTP errors, so we need to wrap the middleware
class HttpMiddleware {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async execute(request, response, next) {
        try {
            await this.handle(request, response);
            next();
        }
        catch (err) {
            if (err instanceof http_1.HttpError) {
                response.writeHead(err.httpCode, {
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    ...response[cors_1.CorsHeaders],
                    'content-type': 'application/json'
                });
                response.end(JSON.stringify({
                    error: err.message
                }));
                // there's some quirk in Deepkit testing where the finish event isn't emitted
                // on ended responses during Jest testing, but works as expected in production
                // will submit a PR for this later. meanwhile, emit the finish event in Jest testing
                if (process.env.NODE_ENV === 'test') {
                    response.emit('finish');
                }
            }
            else {
                response.writeHead(500);
                response.end('Internal Server Error');
                throw err;
            }
        }
    }
}
exports.HttpMiddleware = HttpMiddleware;
HttpMiddleware.__type = [() => http_1.HttpRequest, 'request', () => http_1.HttpResponse, 'response', 'err', '', 'next', 'execute', () => http_1.HttpRequest, () => http_1.HttpResponse, 'handle', 'HttpMiddleware', 'PP7!2"P7#2$P"2%8$/&2\'"0(PP7)2"P7*2$P$`$J0+=5!x"w,'];
class HttpLogPayloadMiddleware extends HttpMiddleware {
    constructor(logger) {
        super();
        this.logger = logger;
    }
    async handle(request, _response) {
        const body = await request.readBodyText();
        this.logger.info('Logging request', {
            method: request.method,
            url: request.url,
            contentType: request.headers['content-type'] ?? '',
            body: body ?? ''
        });
    }
}
exports.HttpLogPayloadMiddleware = HttpLogPayloadMiddleware;
HttpLogPayloadMiddleware.__type = [() => HttpMiddleware, () => __ΩScopedLogger, 'logger', 'constructor', () => http_1.HttpRequest, 'request', () => http_1.HttpResponse, '_response', 'handle', 'HttpLogPayloadMiddleware', 'P7!Pn"2#;"0$PP7%2&P7\'2("0)5w*'];
//# sourceMappingURL=middleware.js.map