centralize email parsing logic

This commit is contained in:
Tom Moor
2024-07-07 10:54:19 -04:00
parent c484d1defe
commit bdcde1aa53
8 changed files with 52 additions and 9 deletions

View 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
View 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 };
}