request-mocking-protocol
Version:
A protocol for declarative mocking of HTTP requests
71 lines • 2.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MockClient = void 0;
/**
* MockClient class.
*/
const protocol_1 = require("../protocol");
const transport_1 = require("../transport");
const utils_1 = require("./utils");
class MockClient {
options;
mockSchemas = new Map();
headers = {};
onChange;
constructor(options) {
this.options = options;
}
get schemas() {
return [...this.mockSchemas.values()];
}
async addMock(reqSchema, resSchema) {
const mockSchema = {
reqSchema: this.buildRequestSchema(reqSchema),
resSchema: this.buildResponseSchema(resSchema),
};
this.mockSchemas.set(reqSchema, mockSchema);
await this.rebuildHeaders();
}
async GET(reqSchema, resSchema) {
return this.addMockWithMethod('GET', reqSchema, resSchema);
}
async POST(reqSchema, resSchema) {
return this.addMockWithMethod('POST', reqSchema, resSchema);
}
async PUT(reqSchema, resSchema) {
return this.addMockWithMethod('PUT', reqSchema, resSchema);
}
async DELETE(reqSchema, resSchema) {
return this.addMockWithMethod('DELETE', reqSchema, resSchema);
}
async HEAD(reqSchema, resSchema) {
return this.addMockWithMethod('HEAD', reqSchema, resSchema);
}
async ALL(reqSchema, resSchema) {
return this.addMockWithMethod(undefined, reqSchema, resSchema);
}
async reset() {
this.mockSchemas.clear();
await this.rebuildHeaders();
}
addMockWithMethod(method, reqSchema, resSchema) {
const initObj = (0, protocol_1.toMockRequestSchemaObject)(reqSchema);
return this.addMock({ ...initObj, method }, resSchema);
}
async rebuildHeaders() {
this.headers = (0, transport_1.buildMockHeaders)(this.schemas);
await this.onChange?.(this.headers);
}
buildRequestSchema(init) {
const initObj = (0, protocol_1.toMockRequestSchemaObject)(init);
const { defaultMethod: method, debug } = this.options || {};
const initObjWithDefaults = (0, utils_1.mergeOptions)({ method, debug }, initObj);
return (0, protocol_1.buildMockRequestSchema)(initObjWithDefaults);
}
buildResponseSchema(init) {
// place to apply defaults
return (0, protocol_1.buildMockResponseSchema)(init);
}
}
exports.MockClient = MockClient;
//# sourceMappingURL=index.js.map