File tree Expand file tree Collapse file tree 2 files changed +27
-1
lines changed
Expand file tree Collapse file tree 2 files changed +27
-1
lines changed Original file line number Diff line number Diff line change @@ -47,7 +47,16 @@ export const optionalAuthValidator = async (
4747 next : NextFunction
4848) => {
4949 if ( req . headers . authorization ) {
50- await authValidator ( req , res , next ) ;
50+ // The purpose of this middleware is to optionally retrieve user info
51+ // if applicable, thereby preventing a 401 error on an invalid token
52+ const callNext : unknown = ( ) => next ( ) ;
53+ const controlledRes = {
54+ ...res ,
55+ sendStatus : callNext as typeof res . sendStatus ,
56+ send : callNext as typeof res . send ,
57+ end : callNext as typeof res . end ,
58+ } as Response ;
59+ await authValidator ( req , controlledRes , callNext as NextFunction ) ;
5160 } else next ( ) ;
5261} ;
5362
Original file line number Diff line number Diff line change @@ -69,6 +69,23 @@ describe('Post endpoints', async () => {
6969 expect ( resBody . length ) . toBe ( 0 ) ;
7070 } ) ;
7171
72+ it ( 'should respond with posts array on invalid auth token and not send 401' , async ( ) => {
73+ const POST_COUNT = 2 ;
74+ for ( let i = 0 ; i < POST_COUNT ; i ++ ) {
75+ await createPost ( postFullData ) ;
76+ }
77+ const res = await api . get ( POSTS_URL ) . set ( 'Authorization' , 'blah' ) ;
78+ const resBody = res . body as PostFullData [ ] ;
79+ expect ( res . statusCode ) . toBe ( 200 ) ;
80+ expect ( res . type ) . toMatch ( / j s o n / ) ;
81+ expect ( resBody ) . toBeTypeOf ( 'object' ) ;
82+ expect ( Array . isArray ( resBody ) ) . toBe ( true ) ;
83+ expect ( resBody . length ) . toBe ( POST_COUNT ) ;
84+ for ( const post of resBody ) {
85+ assertPostData ( post , postFullData ) ;
86+ }
87+ } ) ;
88+
7289 it ( 'should respond with an array of posts with their images' , async ( ) => {
7390 const POST_COUNT = 2 ;
7491 const postData = { ...postFullData , image : dbImgOne . id } ;
You can’t perform that action at this time.
0 commit comments