UNPKG

koas-core

Version:

> [Koa][] + [OpenAPI Specification][] = Koas

36 lines (35 loc) 1.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createMatcher = void 0; /** * Create a matcher function for an OpenAPI path template. * * @param pathTemplate - The OpenAPI path template for which to create a matcher. * @param resolveRef - A JSON reference resolver. * @param pathParameters - The OpenAPI path parameter objects used to determine how to process the * extracted parameters. * @returns a matcher function for extracting path parameters from a URL path. */ function createMatcher(pathTemplate, resolveRef, pathParameters = []) { const arrayNames = new Set(pathParameters .map(resolveRef) .filter(({ schema = {} }) => resolveRef(schema).type === 'array') .map(({ name }) => name)); const names = []; const pathRegex = new RegExp(`^${pathTemplate.replace(/{(\w+)}/gi, (match, name) => { names.push(name); return arrayNames.has(name) ? '(.*)' : '([^/]+)'; })}$`, 'i'); return (url) => { const urlMatch = url.match(pathRegex); if (!urlMatch) { return null; } const result = {}; for (const [index, name] of names.entries()) { result[name] = decodeURI(urlMatch[index + 1]); } return result; }; } exports.createMatcher = createMatcher;