request-mocking-protocol
Version:
A protocol for declarative mocking of HTTP requests
68 lines • 2.17 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.UrlMatcher = void 0;
/**
* URL matcher.
*/
require("urlpattern-polyfill");
class UrlMatcher {
schema;
matcher;
hasQuery = false;
constructor(schema) {
this.schema = schema;
this.matcher =
this.schema.patternType === 'regexp' ? this.buildRegexpMatcher() : this.buildPatternMatcher();
}
match(ctx) {
const { req } = ctx;
const shouldTrimSearchParams = Boolean(this.schema.query);
const url = shouldTrimSearchParams ? trimSearchParams(req.url) : req.url;
const result = this.matcher instanceof RegExp
? this.matchRegexp(ctx, url, this.matcher)
: this.matchPattern(ctx, url, this.matcher);
ctx.log(result, `URL`, this.schema.url, `${url}${url !== req.url ? ' (query trimmed)' : ''}`);
return result;
}
matchRegexp(ctx, url, regexp) {
const result = url.match(regexp);
if (result)
ctx.appendParams(result.groups);
return Boolean(result);
}
matchPattern(ctx, url, pattern) {
const result = pattern.exec(url);
if (!result)
return false;
const keys = Object.keys(result);
keys.forEach((key) => {
const value = result[key];
if ('groups' in value)
ctx.appendParams(value.groups);
});
return true;
}
buildRegexpMatcher() {
const { url } = this.schema;
this.hasQuery = url.includes('\\?');
return regexpFromString(url);
}
buildPatternMatcher() {
const { url } = this.schema;
const urlPattern = new URLPattern(url);
this.hasQuery = urlPattern.search !== '*';
return urlPattern;
}
}
exports.UrlMatcher = UrlMatcher;
function regexpFromString(s) {
const source = s.slice(1, s.lastIndexOf('/'));
const flags = s.slice(s.lastIndexOf('/') + 1);
return new RegExp(source, flags);
}
function trimSearchParams(url) {
const urlObj = new URL(url);
urlObj.search = '';
return urlObj.toString();
}
//# sourceMappingURL=url.js.map