UNPKG

2.68 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. and LoopBack contributors 2018,2019. All Rights Reserved.
3// Node module: @loopback/rest
4// This file is licensed under the MIT License.
5// License text available at https://opensource.org/licenses/MIT
6Object.defineProperty(exports, "__esModule", { value: true });
7exports.toExpressPath = exports.getPathVariables = exports.validateApiPath = void 0;
8const path_to_regexp_1 = require("path-to-regexp");
9/**
10 * OpenAPI spec 3.x does not specify the valid forms of path templates.
11 *
12 * Other ones such as [URI Template](https://tools.ietf.org/html/rfc6570#section-2.3)
13 * or [path-to-regexp](https://github.com/pillarjs/path-to-regexp#named-parameters)
14 * allows `[A-Za-z0-9_]`
15 */
16const POSSIBLE_VARNAME_PATTERN = /\{([^\}]+)\}/g;
17const VALID_VARNAME_PATTERN = /^[A-Za-z0-9_]+$/;
18/**
19 * Validate the path to be compatible with OpenAPI path template. No parameter
20 * modifier, custom pattern, or unnamed parameter is allowed.
21 */
22function validateApiPath(path = '/') {
23 const tokens = (0, path_to_regexp_1.parse)(path);
24 for (const token of tokens) {
25 if (typeof token === 'string')
26 continue;
27 if (typeof token === 'object') {
28 const name = token.name;
29 if (typeof name === 'string' && name !== '') {
30 throw new Error(`Invalid path template: '${path}'. Please use {${name}} instead of ':${name}'`);
31 }
32 if (typeof name === 'number') {
33 throw new Error(`Unnamed parameter is not allowed in path '${path}'`);
34 }
35 const valid = token.prefix.match(VALID_VARNAME_PATTERN);
36 if (!valid) {
37 throw new Error(`Invalid parameter name '${token.prefix}' found in path '${path}'`);
38 }
39 if (['?', '+', '*'].includes(token.modifier)) {
40 throw new Error(`Parameter modifier '{${token.prefix}}${token.modifier}' is not allowed in path '${path}`);
41 }
42 }
43 }
44 return path;
45}
46exports.validateApiPath = validateApiPath;
47/**
48 * Get all path variables. For example, `/root/{foo}/bar` => `['foo']`
49 */
50function getPathVariables(path) {
51 return path.match(POSSIBLE_VARNAME_PATTERN);
52}
53exports.getPathVariables = getPathVariables;
54/**
55 * Convert an OpenAPI path to Express (path-to-regexp) style
56 * @param path - OpenAPI path with optional variables as `{var}`
57 */
58function toExpressPath(path) {
59 // Convert `.` to `\\.` so that path-to-regexp will treat it as the plain
60 // `.` character
61 return path.replace(POSSIBLE_VARNAME_PATTERN, '{:$1}').replace('.', '\\.');
62}
63exports.toExpressPath = toExpressPath;
64//# sourceMappingURL=openapi-path.js.map
\No newline at end of file