UNPKG

@n1k1t/mock-server

Version:

The ultimate toolkit to intercept, transform, and simulate HTTP/WS traffic with type-safe expectations

60 lines 2.73 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpRequestContext = void 0; const lodash_1 = __importDefault(require("lodash")); const utils_1 = require("../../../utils"); const meta_1 = require("../../../meta"); const logger_1 = require("../../../logger"); const models_1 = require("../../models"); const logger = logger_1.Logger.build('Transports.Http.Context'); class HttpRequestContext extends models_1.RequestContext { constructor(provider, incoming, request, response) { super(provider, { transport: 'http' }); this.provider = provider; this.incoming = incoming; this.request = request; this.response = response; this.snapshot = this.compileSnapshot(); this.history = this.compileHistory(); this.meta = meta_1.metaStorage.generate({ ...(this.incoming.headers['x-request-id'] && { requestId: String(this.incoming.headers['x-request-id']) }), }); } handle() { logger.info('Incoming HTTP request', `[${this.incoming.method} ${this.incoming.path}]`); return super.handle(); } complete() { logger.info(`Incoming HTTP request [${this.incoming.method} ${this.incoming.path}] has finished`, `with status [${this.outgoing?.status ?? 200}] in [${Date.now() - this.timestamp}ms]`); return super.complete(); } compileSnapshot() { const snapshot = super.compileSnapshot(); const state = this.incoming.headers['x-use-mock-state'] ? (0, utils_1.parseJsonSafe)(Buffer.from(String(this.incoming.headers['x-use-mock-state']), 'base64').toString()) : null; if (state?.status === 'ERROR') { logger.error('Got error while parsing [x-use-mock-state] header', state.error?.stack ?? state.error); } snapshot.outgoing.status = 200; snapshot.incoming.headers = lodash_1.default.omit(snapshot.incoming.headers, ['transfer-encoding']); return snapshot.assign({ ...(this.incoming.headers['x-use-mock-seed'] && { seed: Number(this.incoming.headers['x-use-mock-seed']), }), ...(state?.status === 'OK' && { state: state.result, }), }); } ; static async build(provider, request, response) { const incoming = await (0, models_1.extractHttpIncommingContext)(request); return new HttpRequestContext(provider, incoming, request, response); } } exports.HttpRequestContext = HttpRequestContext; //# sourceMappingURL=context.js.map