Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 120 additions & 6 deletions __tests__/parameters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
HeaderParams,
JsonController,
Param,
Params,
QueryParam,
QueryParams,
} from 'routing-controllers'
Expand All @@ -17,8 +18,17 @@ import {
parseRoutes,
} from '../src'
import { SchemaObject } from 'openapi3-ts'
import { validationMetadatasToSchemas } from 'class-validator-jsonschema'
import { IsBoolean, IsNumber, IsOptional, IsString } from 'class-validator'
import {
JSONSchema,
validationMetadatasToSchemas,
} from 'class-validator-jsonschema'
import {
IsBoolean,
IsMongoId,
IsNumber,
IsOptional,
IsString,
} from 'class-validator'
const { defaultMetadataStorage } = require('class-transformer/cjs/storage')

describe('parameters', () => {
Expand All @@ -40,10 +50,33 @@ describe('parameters', () => {
types: string[]
}

class ListUserParams {
@IsMongoId()
@IsString()
@JSONSchema({
description: 'ID of the user',
example: '60d5ec49b3f1c8e4a8f8b8c1',
type: 'string',
format: 'Mongo ObjectId',
})
id: string

@IsString()
@IsOptional()
@JSONSchema({
description: 'Name of the user',
example: 'John Doe',
type: 'string',
})
name: string
}

@JsonController('/users')
// @ts-ignore: not referenced
class UsersController {
@Get('/:string/:regex(\\d{6})/:optional?/:number/:boolean/:any')
@Get(
'/:string/:regex(\\d{6})/:optional?/:number/:boolean/:any/:id/:name?'
)
getPost(
@Param('number') _numberParam: number,
@Param('invalid') _invalidParam: string,
Expand All @@ -52,6 +85,7 @@ describe('parameters', () => {
@QueryParam('limit') _limit: number,
@HeaderParam('Authorization', { required: true })
_authorization: string,
@Params() _params: ListUserParams,
@QueryParams() _queryRef?: ListUsersQueryParams,
@HeaderParams() _headerParams?: ListUsersHeaderParams
) {
Expand All @@ -67,7 +101,7 @@ describe('parameters', () => {
})

it('parses path parameter from path strings', () => {
expect(getPathParams({ ...route, params: [] })).toEqual([
expect(getPathParams({ ...route, params: [] }, schemas)).toEqual([
{
in: 'path',
name: 'string',
Expand Down Expand Up @@ -104,11 +138,67 @@ describe('parameters', () => {
required: true,
schema: { pattern: '[^\\/#\\?]+?', type: 'string' },
},
{
in: 'path',
name: 'id',
required: true,
schema: { pattern: '[^\\/#\\?]+?', type: 'string' },
},
{
in: 'path',
name: 'name',
required: false,
schema: { pattern: '[^\\/#\\?]+?', type: 'string' },
},
])
})

it('supplements path parameter with @Param decorator', () => {
expect(getPathParams(route)).toEqual([
expect(getPathParams(route, schemas)).toEqual(
expect.arrayContaining([
{
in: 'path',
name: 'string',
required: true,
schema: { pattern: '[^\\/#\\?]+?', type: 'string' },
},
{
in: 'path',
name: 'regex',
required: true,
schema: { pattern: '\\d{6}', type: 'string' },
},
{
in: 'path',
name: 'optional',
required: false,
schema: { pattern: '[^\\/#\\?]+?', type: 'string' },
},
{
in: 'path',
name: 'number',
required: true,
schema: { pattern: '[^\\/#\\?]+?', type: 'number' },
},
{
in: 'path',
name: 'boolean',
required: true,
schema: { pattern: '[^\\/#\\?]+?', type: 'boolean' },
},
{
in: 'path',
name: 'any',
required: true,
schema: {},
},
])
)
})

it('parses path param ref from @Params decorator', () => {
expect(getPathParams(route, schemas)).toEqual([
// string comes from path string
{
in: 'path',
name: 'string',
Expand Down Expand Up @@ -145,11 +235,35 @@ describe('parameters', () => {
required: true,
schema: {},
},
{
in: 'path',
name: 'id',
required: true,
schema: {
description: 'ID of the user',
example: '60d5ec49b3f1c8e4a8f8b8c1',
type: 'string',
format: 'Mongo ObjectId',
pattern: '^[0-9a-fA-F]{24}$',
},
},
{
in: 'path',
name: 'name',
required: false,
schema: {
description: 'Name of the user',
example: 'John Doe',
type: 'string',
},
},
])
})

it('ignores @Param if corresponding name is not found in path string', () => {
expect(getPathParams(route).filter((r) => r.name === 'invalid')).toEqual([])
expect(
getPathParams(route, schemas).filter((r) => r.name === 'invalid')
).toEqual([])
})

it('parses query param from @QueryParam decorator', () => {
Expand Down
39 changes: 36 additions & 3 deletions src/generateSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export function getOperation(
operationId: getOperationId(route),
parameters: [
...getHeaderParams(route),
...getPathParams(route),
...getPathParams(route, schemas),
...getQueryParams(route, schemas),
],
requestBody: getRequestBody(route) || undefined,
Expand Down Expand Up @@ -119,11 +119,14 @@ export function getHeaderParams(route: IRoute): oa.ParameterObject[] {
* Path parameters are first parsed from the path string itself, and then
* supplemented with possible @Param() decorator values.
*/
export function getPathParams(route: IRoute): oa.ParameterObject[] {
export function getPathParams(
route: IRoute,
schemas: { [p: string]: oa.SchemaObject | oa.ReferenceObject }
): oa.ParameterObject[] {
const path = getFullExpressPath(route)
const tokens = pathToRegexp.parse(path)

return tokens
const params: oa.ParameterObject[] = tokens
.filter((token) => token && typeof token === 'object') // Omit non-parameter plain string tokens
.map((token: pathToRegexp.Key) => {
const name = token.name + ''
Expand All @@ -149,6 +152,36 @@ export function getPathParams(route: IRoute): oa.ParameterObject[] {

return param
})

const paramsMeta = route.params.find((p) => p.type === 'params')
if (paramsMeta) {
const paramSchema = getParamSchema(paramsMeta) as oa.ReferenceObject
// the last segment after '/'
const paramSchemaName = paramSchema.$ref.split('/').pop() || ''
const currentSchema = schemas[paramSchemaName]

if (oa.isSchemaObject(currentSchema)) {
for (const [name, schema] of Object.entries(
currentSchema?.properties || {}
)) {
// Check if the parameter name is already in the params array.
const existingParam = params.find((param) => param.name === name)
if (existingParam) {
// remove and replace with more specific schema
params.splice(params.indexOf(existingParam), 1)
params.push({
in: 'path',
name,
required: currentSchema.required?.includes(name),
schema,
})
continue
}
}
}
}

return params
}

/**
Expand Down