import { expect , test } from '@jest/globals' ; import 'reflect-metadata' ; import { http , HttpKernel , HttpRequest , JSONResponse , RouteParameterResolverContext } from '@deepkit/http' ; import { App } from '@deepkit/app' ; import { FrameworkModule } from '../src/module' ; test ( 'router parameters' , async ( ) => { class Controller2 { @ http . GET ( '/user/:name' ) string ( name ) { return new JSONResponse ( name ) ; } @ http . GET ( '/user-id/:id' ) number ( id ) { return new JSONResponse ( id ) ; } @ http . GET ( '/boolean/:yes' ) boolean ( yes ) { return new JSONResponse ( yes ) ; } @ http . GET ( ':path' ) . regexp ( 'path' , '.*' ) any ( path ) { return new JSONResponse ( path ) ; } } const app = new App ( { controllers : [ Controller2 ] , imports : [ new FrameworkModule ( ) ] } ) ; const httpHandler = app . get ( HttpKernel ) ; expect ( ( await httpHandler . request ( HttpRequest . GET ( '/user/peter' ) ) ) . json ) . toBe ( 'peter' ) ; expect ( ( await httpHandler . request ( HttpRequest . GET ( '/user-id/123' ) ) ) . json ) . toBe ( 123 ) ; expect ( ( await httpHandler . request ( HttpRequest . GET ( '/user-id/asd' ) ) ) . json ) . toMatchObject ( { message : 'Validation failed: id(invalid_number): No valid number given, got NaN' } ) ; expect ( ( await httpHandler . request ( HttpRequest . GET ( '/boolean/1' ) ) ) . json ) . toBe ( true ) ; expect ( ( await httpHandler . request ( HttpRequest . GET ( '/boolean/false' ) ) ) . json ) . toBe ( false ) ; expect ( ( await httpHandler . request ( HttpRequest . GET ( '/any' ) ) ) . json ) . toBe ( 'any' ) ; expect ( ( await httpHandler . request ( HttpRequest . GET ( '/any/path' ) ) ) . json ) . toBe ( 'any/path' ) ; } ) ; test ( 'router parameterResolver' , async ( ) => { class User { constructor ( public username ) { } } class MyRouteParameterResolver { resolve ( context ) { if ( ! context . parameters . username ) { throw new Error ( 'No :username specified' ) ; } return new User ( context . parameters . username ) ; } } @ http . resolveParameter ( User , MyRouteParameterResolver ) class Controller { @ http . GET ( 'user/:username' ) route1 ( user ) { return [ user . username ] ; } @ http . GET ( 'group' ) route2 ( user ) { return [ user . username ] ; } } const app = new App ( { providers : [ MyRouteParameterResolver ] , controllers : [ Controller ] , imports : [ new FrameworkModule ( ) ] } ) ; const httpHandler = app . get ( HttpKernel ) ; expect ( ( await httpHandler . request ( HttpRequest . GET ( '/user/peter' ) ) ) . json ) . toEqual ( [ 'peter' ] ) ; expect ( ( await httpHandler . request ( HttpRequest . GET ( '/group' ) ) ) . bodyString ) . toEqual ( 'Internal error' ) ; } ) ;