Skip to content

Commit

Permalink
fix: extract username from user should not return undefined (#5061)
Browse files Browse the repository at this point in the history
This fixes a return type error by changing the logic of
`extractUsernameFromUser` to never return undefined.

In the previous code, `user` could be truthy, but that doesn't mean
`email` or `username` were defined. This assumes we always fallback to
"unknown" in those scenarios.
  • Loading branch information
nunogois authored Oct 17, 2023
1 parent 5619db3 commit fd580c9
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
32 changes: 32 additions & 0 deletions src/lib/util/extract-user.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { IUser } from '../server-impl';
import { extractUsernameFromUser } from './extract-user';

describe('extractUsernameFromUser', () => {
test('Should return the email if it exists', () => {
const user = {
email: '[email protected]',
username: 'ratatoskr',
} as IUser;

expect(extractUsernameFromUser(user)).toBe(user.email);
});

test('Should return the username if it exists and email does not', () => {
const user = {
username: 'ratatoskr',
} as IUser;

expect(extractUsernameFromUser(user)).toBe(user.username);
});

test('Should return "unknown" if neither email nor username exists', () => {
const user = {} as IUser;

expect(extractUsernameFromUser(user)).toBe('unknown');
});

test('Should return "unknown" if user is null', () => {
const user = null as unknown as IUser;
expect(extractUsernameFromUser(user)).toBe('unknown');
});
});
2 changes: 1 addition & 1 deletion src/lib/util/extract-user.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { IAuthRequest, IUser } from '../server-impl';

export function extractUsernameFromUser(user: IUser): string {
return user ? user.email || user.username : 'unknown';
return user?.email || user?.username || 'unknown';
}

export function extractUsername(req: IAuthRequest): string {
Expand Down

0 comments on commit fd580c9

Please sign in to comment.