@n1k1t/mock-server
Version:
Powerful util to setup mocks over HTTP APIs
62 lines • 2.76 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WsRequestContext = void 0;
const models_1 = require("../../models");
const utils_1 = require("../../../utils");
const logger_1 = require("../../../logger");
const logger = logger_1.Logger.build('Server.Transports.Ws.Context');
class WsRequestContext extends models_1.RequestContext {
constructor(provider, socket, event, incoming) {
super(provider, { event, transport: 'ws' });
this.provider = provider;
this.socket = socket;
this.event = event;
this.incoming = incoming;
this.snapshot = this.compileSnapshot();
this.history = this.compileHistory();
}
compileSnapshot() {
const snapshot = super.compileSnapshot();
snapshot.outgoing.status = this.event === 'message' ? 0 : 1000;
snapshot.incoming.method = this.event === 'message' ? 'MSG' : 'CON';
return snapshot;
}
handle() {
this.event === 'message'
? logger.info(`Incoming WS ${event} [${this.incoming.path}] got message`, this.incoming.data)
: logger.info(`Incoming WS ${event} [${this.incoming.path}]`);
if (this.event === 'connection') {
this.streams.incoming.subscribe({
error: () => null,
next: (data) => logger.info(`Incoming WS ${this.event} [${this.incoming.path}] got message`, data),
});
}
this.streams.outgoing.subscribe({
error: () => null,
next: (data) => logger.info(`Incoming WS ${this.event} [${this.incoming.path}] has sent`, data),
});
return super.handle();
}
skip() {
this.streams.incoming.complete();
this.streams.outgoing.complete();
return super.skip();
}
complete() {
logger.info(`Incoming WS ${this.event} [${this.incoming.path}] has finished in [${Date.now() - this.timestamp}ms]`);
return super.complete();
}
static async build(provider, socket, request, event, message) {
const incoming = await (0, models_1.extractHttpIncommingContext)(request);
incoming.dataRaw = message ? Buffer.from(message.toString()) : undefined;
incoming.data = incoming.dataRaw
? incoming.type === 'plain'
? (0, utils_1.parseJsonSafe)(incoming.dataRaw.toString()).result
: (0, models_1.parsePayload)(incoming.type, incoming.dataRaw)
: undefined;
incoming.type = incoming.type === 'plain' && incoming.data !== undefined ? 'json' : incoming.type;
return new WsRequestContext(provider, socket, event, incoming);
}
}
exports.WsRequestContext = WsRequestContext;
//# sourceMappingURL=context.js.map