The Email class offers methods to validate, parse, and manipulate email addresses. It supports operations like retrieving the username, domain, and alias, and email validation using an external API via the EmailVerifier class.
bun add @edgefirst-dev/emailImport the Email class and create an instance using a valid email string or an Email object.
import{Email}from"@edgefirst-dev/email";letemail=Email.from("user@example.com");console.log(email.toString());// "user@example.com"You can retrieve and modify the username, domain (hostname), and alias from an email object.
letemail=Email.from("user+alias@example.com");console.log(email.username);// "user"console.log(email.hostname);// "example.com"console.log(email.alias);// "alias"email.username="newuser";email.hostname="newdomain.com";email.alias="newalias";console.log(email.toString());// "newuser+newalias@newdomain.com"Tip
If you want to disallow users from using aliases in their email addresses, you can set the alias property to undefined.
letemail=Email.from("user+alias@example.com)
email.alias=undefined;console.log(email.toString());// "user@example.com"This can be useful to prevent users from creating multiple accounts using the same email address.
The EmailVerifier class validates an email through an external API.
import{Email}from"@edgefirst-dev/email";letemail=Email.from("user@example.com");try{awaitemail.verify();console.log("Email is valid");}catch(error){console.error("Invalid email:",error);}You can override this by extending the Email class and implementing your own verification logic.
classMyEmailextendsEmail{overrideverifier={asyncverify(email: Email): Promise<void>{// Custom verification logic that throws if it's invalid},};}letmyEmail=MyEmail.from("user@example.com");awaitmyEmail.verify();// This will call your own verify functionYou can retrieve the SHA-256 hash of an email address.
console.log(email.hash);// SHA-256 hash of the emailThis can be used along with Gravatar to get the user's avatar.
letemail=Email.from("user@example.com");letavatar=`https://www.gravatar.com/avatar/${email.hash}`;The Email class provides static methods for validation and parsing:
Email.canParse("user@example.com");// trueEmail.canParse("invalid-email");// falseThis is similar to URL.canParse in the URL class.
You can test the EmailVerifier using msw to mock API responses.
import{http}from"msw";import{setupServer}from"msw/node";import{Email}from"@edgefirst-dev/email";letserver=setupServer(http.get("https://verifier.meetchopra.com/verify/user@example.com",(req,res,ctx)=>{returnres(ctx.json({status: true}));}));server.listen();letemail=Email.from("user@example.com");awaitemail.verify();// Mocked valid responseSee LICENSE