UNPKG

@n1k1t/mock-server

Version:

Powerful util to setup mocks over HTTP APIs

53 lines 2.44 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 meta_1 = require("../../../meta"); const logger_1 = require("../../../logger"); const models_1 = require("../../models"); const logger = logger_1.Logger.build('Server.Transports.Http.Context'); class HttpRequestContext extends models_1.RequestContext { constructor(provider, incoming, request, response) { super(provider, { transport: 'http', event: 'connection' }); 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(); 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']), }), ...(this.incoming.headers['x-use-mock-state'] && { state: JSON.parse(Buffer.from(String(this.incoming.headers['x-use-mock-state']), 'base64').toString()), }), }); } ; 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