@n1k1t/mock-server
Version:
The ultimate toolkit to intercept, transform, and simulate HTTP/WS traffic with type-safe expectations
90 lines • 2.92 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestMessage = void 0;
const rfdc_1 = __importDefault(require("rfdc"));
const lodash_1 = __importDefault(require("lodash"));
const utils_1 = require("../utils");
const clone = (0, rfdc_1.default)();
class RequestMessage {
constructor(provided) {
this.provided = provided;
this.direction = this.provided.direction;
this.type = this.provided.type;
this.timestamp = this.provided.timestamp ?? Date.now();
this.data = this.provided.data;
this.raw = this.provided.raw;
}
is(type) {
return this.type === type;
}
serialize() {
if (this.data instanceof Buffer) {
return this.data;
}
if (lodash_1.default.isObject(this.data)) {
return Buffer.from(JSON.stringify(this.data));
}
if (this.data !== undefined) {
return Buffer.from(String(this.data));
}
return this.raw.data ?? Buffer.from('');
}
/** Returns bytes length of data */
size() {
return this.direction === 'incoming'
? this.raw.data?.length ?? this.serialize().length
: this.serialize().length;
}
/** Clones this instance */
clone(options) {
return new RequestMessage({
direction: this.direction,
type: this.type,
timestamp: this.timestamp,
data: (options?.deep && lodash_1.default.isObject(this.data)) ? clone(this.data) : this.data,
raw: this.raw,
});
}
redirect(direction) {
this.direction = direction;
return this;
}
toPlain() {
return {
direction: this.direction,
type: this.type,
timestamp: this.timestamp,
data: this.data,
};
}
toCache() {
return {
direction: this.direction,
type: this.type,
timestamp: this.timestamp,
data: this.data,
raw: {
data: this.raw.data?.toString('base64'),
},
};
}
static build(directionOrPlain, predicate) {
if (lodash_1.default.isObject(directionOrPlain)) {
return new RequestMessage(Object.assign(directionOrPlain, { raw: {} }));
}
const parsed = (0, utils_1.parsePayload)(predicate);
return new RequestMessage({
direction: directionOrPlain,
type: (parsed?.type ?? 'plain'),
data: (parsed?.data ?? undefined),
raw: {
data: predicate instanceof Buffer ? predicate : undefined,
},
});
}
}
exports.RequestMessage = RequestMessage;
//# sourceMappingURL=message.js.map