wiremock-captain
Version:
A better way to use the WireMock simulator to test your HTTP APIs
234 lines (233 loc) • 8.93 kB
JavaScript
;
// Copyright (c) WarnerMedia Direct, LLC. All rights reserved. Licensed under the MIT license.
// See the LICENSE file for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.WireMock = void 0;
const RequestModel_1 = require("./RequestModel");
const ResponseModel_1 = require("./ResponseModel");
const utils_1 = require("./utils");
// endpoint where wiremock stores mocks
const WIREMOCK_MAPPINGS_URL = '__admin/mappings';
// endpoint that records all the incoming requests
const WIREMOCK_REQUESTS_URL = '__admin/requests';
// endpoint that records all the scenario information
const WIREMOCK_SCENARIO_URL = '__admin/scenarios';
const HEADERS = { 'Content-Type': 'application/json' };
class WireMock {
constructor(baseUrl, features) {
this.baseUrl = baseUrl;
this.features = features ?? {};
}
/**
* Creates a new stub with desired request and response match
* @param request Request object for the stub mapping
* @param response AxiosResponse object for the stub mapping
* @param features Additional options to be used for creation of stub mapping
* @returns Created wiremock stub mapping. Contains `id` which is needed to delete a mapping
*/
async register(request, response, features) {
const mergedFeatures = this.mergeWireMockFeatures(features);
const mockedRequest = (0, RequestModel_1.createWireMockRequest)(request, mergedFeatures);
const mockedResponse = (0, ResponseModel_1.createWireMockResponse)(response, mergedFeatures);
let mock = {
request: mockedRequest,
response: mockedResponse,
};
if (mergedFeatures?.stubPriority) {
mock.priority = mergedFeatures.stubPriority;
}
if (mergedFeatures?.scenario) {
mock = { ...mock, ...mergedFeatures.scenario };
}
if (mergedFeatures?.webhook) {
mock.postServeActions = [
{
name: 'webhook',
parameters: {
method: mergedFeatures.webhook.method,
url: mergedFeatures.webhook.url,
...(mergedFeatures.webhook.headers && {
headers: mergedFeatures.webhook.headers,
}),
...(mergedFeatures.webhook.body && {
body: (0, utils_1.getWebhookBody)(mergedFeatures.webhook.body),
}),
...(mergedFeatures.webhook.delay && {
delay: (0, utils_1.getWebhookDelayBody)(mergedFeatures.webhook.delay),
}),
},
},
];
}
if (mergedFeatures?.fault) {
mock.response = { fault: mergedFeatures.fault };
}
if (request.metadata) {
mock.metadata = request.metadata;
}
const wiremockResponse = await fetch(this.makeUrl(WIREMOCK_MAPPINGS_URL), {
method: 'POST',
headers: HEADERS,
body: JSON.stringify(mock),
});
return (await wiremockResponse.json());
}
/**
* Removes all the existing stubs and logs of incoming requests
*/
clearAll() {
return Promise.all([this.clearAllMappings(), this.clearAllRequests()]);
}
/**
* Removes all the non-default mappings (not defined in backing store)
* and logs of incoming requests
*/
clearAllExceptDefault() {
return Promise.all([this.resetMappings(), this.clearAllRequests()]);
}
/**
* Removes all existing stubs
*/
async clearAllMappings() {
return await fetch(this.makeUrl(WIREMOCK_MAPPINGS_URL), {
method: 'DELETE',
});
}
/**
* Removes log of all past incoming requests
*/
async clearAllRequests() {
const response = await fetch(this.makeUrl(WIREMOCK_REQUESTS_URL), {
method: 'DELETE',
});
return response;
}
/**
* Deletes a stub mapping
* @param id ID of the stub to be deleted. Can be obtained when from response of `register()`
*/
async deleteMapping(id) {
const response = await fetch(this.makeUrl(`${WIREMOCK_MAPPINGS_URL}/${id}`), {
method: 'DELETE',
});
return response;
}
/**
* Returns all the request and response mappings attached to the wiremock instance
* @returns Collection of all mappings for the wiremock instance
*/
async getAllMappings() {
const response = await fetch(this.makeUrl(WIREMOCK_MAPPINGS_URL), {
method: 'GET',
});
const responseJson = (await response.json());
return responseJson.mappings;
}
/**
* @returns List of all requests made to the mocked instance
*/
async getAllRequests() {
const response = await fetch(this.makeUrl(WIREMOCK_REQUESTS_URL), { method: 'GET' });
const responseJson = (await response.json());
return responseJson.requests;
}
/**
* @returns List of all scenarios in place for the mocked instance
*/
async getAllScenarios() {
const response = await fetch(this.makeUrl(WIREMOCK_SCENARIO_URL), { method: 'GET' });
const responseJson = (await response.json());
return responseJson.scenarios;
}
/**
* Returns information about the mocked request and response corresponding to the `id`
* @param id Mapping ID to get the mapping info for
* @returns Single object mapping corresponding to the input `id`
*/
async getMapping(id) {
const response = await fetch(this.makeUrl(`${WIREMOCK_MAPPINGS_URL}/${id}`), {
method: 'GET',
});
return await response.json();
}
/**
* Returns list of request(s) made to the WireMock API
* @param method Method to match the request(s) made against
* @param endpointUrl URL to get the request(s) made against
* @returns List of wiremock requests made to the endpoint with given method
*/
async getRequestsForAPI(method, endpointUrl) {
const response = await fetch(this.makeUrl(WIREMOCK_REQUESTS_URL), { method: 'GET' });
const body = (await response.json());
return (body.requests
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.filter((r) => (0, utils_1.filterRequest)(method, endpointUrl, r)));
}
/**
* Returns list of unmatched request(s)
* @returns List of wiremock requests made that did not match any mapping
*/
async getUnmatchedRequests() {
const response = await fetch(this.makeUrl(WIREMOCK_REQUESTS_URL + '/unmatched'), {
method: 'GET',
});
const body = (await response.json());
return body.requests;
}
/**
* Resets all the scenarios to the original state
*/
async resetAllScenarios() {
const response = await fetch(this.makeUrl(WIREMOCK_SCENARIO_URL + '/reset'), {
method: 'POST',
});
return response;
}
/**
* Restores stub mappings to the defaults defined back in the backing store
*/
async resetMappings() {
const response = await fetch(this.makeUrl(WIREMOCK_MAPPINGS_URL + '/reset'), {
method: 'POST',
});
return response;
}
/**
* Finds a mapping by metadata.
* @param matchObject - The object containing metadata to match.
* @param matchType - The type of matching attributes.
* @returns The found mappings.
*/
async findMappingByMetadata(matchObject, matchType) {
const response = await fetch(this.makeUrl(WIREMOCK_MAPPINGS_URL + '/find-by-metadata'), {
method: 'POST',
headers: HEADERS,
body: JSON.stringify({ [matchType]: matchObject }),
});
return (await response.json()).mappings;
}
/**
* Removes a mapping by metadata.
* @param matchObject - The object containing metadata to match.
* @param matchType - The type of matching attributes.
* @returns The result of the removal operation.
*/
async removeMappingByMetadata(matchObject, matchType) {
const response = await fetch(this.makeUrl(WIREMOCK_MAPPINGS_URL + '/remove-by-metadata'), {
method: 'POST',
headers: HEADERS,
body: JSON.stringify({ [matchType]: matchObject }),
});
return await response.json();
}
makeUrl(endpoint) {
return new URL(endpoint, this.baseUrl).href;
}
mergeWireMockFeatures(features) {
return {
...this.features, // Base features as default values
...features, // Override with parameter values
};
}
}
exports.WireMock = WireMock;