Skip to content
Merged
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
11 changes: 10 additions & 1 deletion src/middlewares/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,16 @@ export const optionalAuthValidator = async (
next: NextFunction
) => {
if (req.headers.authorization) {
await authValidator(req, res, next);
// The purpose of this middleware is to optionally retrieve user info
// if applicable, thereby preventing a 401 error on an invalid token
const callNext: unknown = () => next();
const controlledRes = {
...res,
sendStatus: callNext as typeof res.sendStatus,
send: callNext as typeof res.send,
end: callNext as typeof res.end,
} as Response;
await authValidator(req, controlledRes, callNext as NextFunction);
} else next();
};

Expand Down
17 changes: 17 additions & 0 deletions src/tests/api/v1/posts.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,23 @@ describe('Post endpoints', async () => {
expect(resBody.length).toBe(0);
});

it('should respond with posts array on invalid auth token and not send 401', async () => {
const POST_COUNT = 2;
for (let i = 0; i < POST_COUNT; i++) {
await createPost(postFullData);
}
const res = await api.get(POSTS_URL).set('Authorization', 'blah');
const resBody = res.body as PostFullData[];
expect(res.statusCode).toBe(200);
expect(res.type).toMatch(/json/);
expect(resBody).toBeTypeOf('object');
expect(Array.isArray(resBody)).toBe(true);
expect(resBody.length).toBe(POST_COUNT);
for (const post of resBody) {
assertPostData(post, postFullData);
}
});

it('should respond with an array of posts with their images', async () => {
const POST_COUNT = 2;
const postData = { ...postFullData, image: dbImgOne.id };
Expand Down