feat(openapi): document constrained route params
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
4 files changed
+56
-13
No files matched your search
+2
-2
@@ -1,6 +1,6 @@
|
||||
import type { RouteDef, MatchedRoute } from './types';
|
||||
|
||||
type CompiledSegment =
|
||||
export type CompiledSegment =
|
||||
| { kind: 'static'; value: string }
|
||||
| { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string }
|
||||
| { kind: 'catchAll'; name: string };
|
||||
@@ -147,7 +147,7 @@ export function compilePattern(pattern: string): CompiledPattern {
|
||||
if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`);
|
||||
|
||||
const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;
|
||||
const rawSegments = normalized.split('/').slice(1);
|
||||
const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1);
|
||||
const segments = compileSegments(pattern, rawSegments);
|
||||
const compiled: CompiledPattern = {
|
||||
source: pattern,
|
||||
|
||||
+24
-9
@@ -1,5 +1,6 @@
|
||||
import type { ArgSpec } from './params';
|
||||
import type { Transport } from './metadata';
|
||||
import { compilePattern } from './http/router';
|
||||
|
||||
/** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */
|
||||
export interface OpenApiRoute {
|
||||
@@ -23,23 +24,37 @@ export interface OpenApiDoc {
|
||||
paths: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
type Parameter = { name: string; in: 'path' | 'query' | 'header'; required: boolean; schema: { type: 'string' } };
|
||||
type Parameter = {
|
||||
name: string;
|
||||
in: 'path' | 'query' | 'header';
|
||||
required: boolean;
|
||||
schema: { type: 'string'; pattern?: string };
|
||||
};
|
||||
|
||||
/** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */
|
||||
function templatePath(pattern: string): string {
|
||||
const segments = pattern
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.map((seg) => (seg.startsWith(':') ? `{${seg.slice(1).replace(/\*$/, '')}}` : seg));
|
||||
const segments = compilePattern(pattern).segments.map((segment) =>
|
||||
segment.kind === 'static' ? segment.value : `{${segment.name}}`,
|
||||
);
|
||||
return `/${segments.join('/')}`;
|
||||
}
|
||||
|
||||
/** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */
|
||||
function pathParams(pattern: string): Parameter[] {
|
||||
return pattern
|
||||
.split('/')
|
||||
.filter((seg) => seg.startsWith(':'))
|
||||
.map((seg) => ({ name: seg.slice(1).replace(/\*$/, ''), in: 'path', required: true, schema: { type: 'string' } }));
|
||||
return compilePattern(pattern).segments.flatMap((segment): Parameter[] => {
|
||||
if (segment.kind === 'static') return [];
|
||||
return [
|
||||
{
|
||||
name: segment.name,
|
||||
in: 'path',
|
||||
required: true,
|
||||
schema: {
|
||||
type: 'string',
|
||||
...(segment.kind === 'param' && segment.constraintSource ? { pattern: segment.constraintSource } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */
|
||||
|
||||
+25
-2
@@ -1,7 +1,7 @@
|
||||
import 'reflect-metadata';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp } from '../src/app';
|
||||
import { Route, Get, Post, Ws, Module } from '../src/metadata';
|
||||
import { Route, Get, Head, Options, Post, Ws, Module } from '../src/metadata';
|
||||
import { param, query, headers, body } from '../src/params';
|
||||
|
||||
const numSchema = {
|
||||
@@ -14,7 +14,13 @@ const numSchema = {
|
||||
|
||||
@Route('/users')
|
||||
class Users {
|
||||
@Get('/:id') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) {
|
||||
@Get('/:id(\\d+)') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) {
|
||||
return {};
|
||||
}
|
||||
@Head('/:id(\\d+)') head() {
|
||||
return {};
|
||||
}
|
||||
@Options('/:id(\\d+)') options() {
|
||||
return {};
|
||||
}
|
||||
@Post('/') create(@body() _b: unknown) {
|
||||
@@ -52,6 +58,23 @@ describe('app.openapi()', () => {
|
||||
expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' });
|
||||
});
|
||||
|
||||
it('projects a constrained param into schema.pattern', () => {
|
||||
const op = doc.paths['/api/users/{id}'].get as any;
|
||||
expect(op.parameters).toContainEqual({
|
||||
name: 'id',
|
||||
in: 'path',
|
||||
required: true,
|
||||
schema: { type: 'string', pattern: '\\d+' },
|
||||
});
|
||||
});
|
||||
|
||||
it('includes explicit HEAD and OPTIONS without inventing automatic operations', () => {
|
||||
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
|
||||
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
|
||||
expect(doc.paths['/api/users/search'].head).toBeUndefined();
|
||||
expect(doc.paths['/api/users/search'].options).toBeUndefined();
|
||||
});
|
||||
|
||||
it('marks routes that take a body with requestBody', () => {
|
||||
const op = doc.paths['/api/users'].post as any;
|
||||
expect(op.requestBody.content['application/json']).toBeDefined();
|
||||
|
||||
@@ -17,6 +17,11 @@ const route = (method: string, pattern: string): RouteDef => ({
|
||||
});
|
||||
|
||||
describe('matchPattern', () => {
|
||||
it('matches the root pattern only at root', () => {
|
||||
expect(matchPattern('/', '/')).toEqual({});
|
||||
expect(matchPattern('/', '/users')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('matches static and :param segments, decoding params', () => {
|
||||
expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' });
|
||||
expect(matchPattern('/users/:id', '/users')).toBeUndefined();
|
||||
|
||||
Reference in new issue
Block a user