centralize email parsing logic
This commit is contained in:
24
shared/utils/email.test.ts
Normal file
24
shared/utils/email.test.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { parseEmail } from "./email";
|
||||
|
||||
describe("parseEmail", () => {
|
||||
it("should correctly parse email", () => {
|
||||
expect(parseEmail("tom@example.com")).toEqual({
|
||||
local: "tom",
|
||||
domain: "example.com",
|
||||
});
|
||||
expect(parseEmail("tom.m@example.com")).toEqual({
|
||||
local: "tom.m",
|
||||
domain: "example.com",
|
||||
});
|
||||
expect(parseEmail("tom@subdomain.domain.com")).toEqual({
|
||||
local: "tom",
|
||||
domain: "subdomain.domain.com",
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw error for invalid email", () => {
|
||||
expect(() => parseEmail("")).toThrow();
|
||||
expect(() => parseEmail("invalid")).toThrow();
|
||||
expect(() => parseEmail("invalid@")).toThrow();
|
||||
});
|
||||
});
|
||||
15
shared/utils/email.ts
Normal file
15
shared/utils/email.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Parse an email address into its local and domain parts.
|
||||
*
|
||||
* @param email The email address to parse
|
||||
* @returns The local and domain parts of the email address, in lowercase
|
||||
*/
|
||||
export function parseEmail(email: string): { local: string; domain: string } {
|
||||
const [local, domain] = email.toLowerCase().split("@");
|
||||
|
||||
if (!domain) {
|
||||
throw new Error("Invalid email address");
|
||||
}
|
||||
|
||||
return { local, domain };
|
||||
}
|
||||
Reference in New Issue
Block a user