Skip to content

Commit

Permalink
add match function as a matcher to request; make url/verb/match all…
Browse files Browse the repository at this point in the history
… optionals; at least one must exist (#220)

* upgrade ts loader

* add `match` function as a matcher to request; make url/verb/match all optionals; at least one must exist
  • Loading branch information
david2tm authored Nov 1, 2021
1 parent 73d6000 commit 356141c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
26 changes: 26 additions & 0 deletions src/leonardo/configuration.srv.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/// <reference path="leonardo.d.ts" />
import MockRequest from "xhr-mock/lib/MockRequest";

declare let Object: any;
export function leoConfiguration() {
let _states = [],
Expand Down Expand Up @@ -34,6 +36,7 @@ export function leoConfiguration() {
addSavedState: addSavedState,
addOrUpdateSavedState: addOrUpdateSavedState,
fetchStatesByUrlAndMethod: fetchStatesByUrlAndMethod,
fetchStatesByRequest: fetchStatesByRequest,
removeState: removeState,
removeOption: removeOption,
onStateChange: onSetStates,
Expand Down Expand Up @@ -175,6 +178,29 @@ export function leoConfiguration() {
})[0];
}

function fetchStatesByRequest(request: MockRequest) {
return fetchStates()
.filter((state) => state.url || state.verb || typeof state.match === 'function')
.filter((state) => {
if (state.url) {
return isMatchUrl(state.url, request.url().toString());
}
return true;
})
.filter((state) => {
if (state.verb) {
return request.method().toLocaleLowerCase() === state.verb.toLowerCase();
}
return true;
})
.filter((state) => {
if (typeof state.match === 'function') {
return !!this.state.match.call(this.state, request);
}
return true;
})[0];
}

function isMatchUrl(stateUrlPattern, url) {
const urlRegexp = new RegExp(stateUrlPattern);
const decodedUrl = decodeURIComponent(url);
Expand Down
4 changes: 2 additions & 2 deletions src/leonardo/xhr-mock.srv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class XhrMock {
private init() {
xhrMock.setup();
xhrMock.use(async (request: MockRequest, response: MockResponse) => {
const state = Leonardo.fetchStatesByUrlAndMethod(request.url().toString(), request.method());
const state = Leonardo.fetchStatesByRequest(request);
if (state && state.active) {
const activeOption = Leonardo.getActiveStateOption(state.name);
if (!!activeOption) {
Expand Down Expand Up @@ -50,7 +50,7 @@ export class XhrMock {

const res = response.status(resStatus).headers(resHeaders).body(deepCopy(resData));
this.log(request, res);
return new Promise<MockResponse>((resolve, reject) => {
return new Promise<MockResponse>((resolve) => {
setTimeout(() => resolve(res), delay);
});
}
Expand Down

0 comments on commit 356141c

Please sign in to comment.