@@ -567,6 +567,93 @@ async function run () {
567567 }
568568 t . ok ( errored )
569569 } )
570+
571+ const getTestConstraint = ( ) => ( {
572+ name : 'testConstraint' ,
573+ storage : ( ) => {
574+ let headerValues = { }
575+ return {
576+ get : ( value ) => { return headerValues [ value ] || null } ,
577+ set : ( value , store ) => { headerValues [ value ] = store } ,
578+ del : ( value ) => { delete headerValues [ value ] } ,
579+ empty : ( ) => { headerValues = { } }
580+ }
581+ } ,
582+ validate ( value ) { return true } ,
583+ deriveConstraint : ( req , ctx ) => {
584+ return req . headers [ 'test-header' ]
585+ }
586+ } )
587+
588+ test ( 'constraints' , async t => {
589+ const server = Fastify ( {
590+ constraints : {
591+ testConstraint : getTestConstraint ( )
592+ }
593+ } )
594+ server . register ( proxy , {
595+ upstream : `http://localhost:${ origin . server . address ( ) . port } ` ,
596+ constraints : { testConstraint : 'valid-value' }
597+ } )
598+
599+ await server . listen ( 0 )
600+ t . teardown ( server . close . bind ( server ) )
601+ await got ( `http://localhost:${ server . server . address ( ) . port } /a` , {
602+ headers : {
603+ 'test-header' : 'valid-value'
604+ }
605+ } )
606+
607+ try {
608+ await got ( `http://localhost:${ server . server . address ( ) . port } /a` , {
609+ headers : {
610+ 'test-header' : 'invalid-value'
611+ }
612+ } )
613+ t . fail ( )
614+ } catch ( err ) {
615+ t . equal ( err . response . statusCode , 404 )
616+ }
617+
618+ try {
619+ await got ( `http://localhost:${ server . server . address ( ) . port } /a` )
620+ t . fail ( )
621+ } catch ( err ) {
622+ t . equal ( err . response . statusCode , 404 )
623+ }
624+ } )
625+
626+ test ( 'constraints with unconstrained routes' , async t => {
627+ const server = Fastify ( {
628+ constraints : {
629+ testConstraint : getTestConstraint ( )
630+ }
631+ } )
632+ server . get ( '/a' , {
633+ constraints : { testConstraint : 'without-proxy' }
634+ } , async ( ) => 'this is unproxied a' )
635+ server . register ( proxy , {
636+ upstream : `http://localhost:${ origin . server . address ( ) . port } ` ,
637+ constraints : { testConstraint : 'with-proxy' }
638+ } )
639+
640+ await server . listen ( 0 )
641+ t . teardown ( server . close . bind ( server ) )
642+
643+ const resultProxied = await got ( `http://localhost:${ server . server . address ( ) . port } /a` , {
644+ headers : {
645+ 'test-header' : 'with-proxy'
646+ }
647+ } )
648+ t . equal ( resultProxied . body , 'this is a' )
649+
650+ const resultUnproxied = await got ( `http://localhost:${ server . server . address ( ) . port } /a` , {
651+ headers : {
652+ 'test-header' : 'without-proxy'
653+ }
654+ } )
655+ t . equal ( resultUnproxied . body , 'this is unproxied a' )
656+ } )
570657}
571658
572659run ( )
0 commit comments