Using Services

Avatar of Hemanta SundarayHemanta Sundaray

In the previous section, we created a service called Email containing a function called sendPasswordResetEmail. Let’s now learn how to use the service.

In a real application, after a user submits the “Forgot Password” form, a form handler executes. This form handler is where we would use the Email service and call sendPasswordResetEmail to send the email. Here is what that looks like:

email.ts
function handleForgotPassword(email: string) {
return Effect.gen(function* () {
const emailService = yield* Email;
const resetLink = `https://yourapp.com/reset?token=abc123`;
yield* emailService.sendPasswordResetEmail(email, resetLink);
});
}

Notice the highlighted lines above. First, we write yield* Email to access the service by its tag. Then, we call sendPasswordResetEmail on the service to send the password reset email.

Now let’s try to run the program using Effect.runPromise:

email.ts
const program = handleForgotPassword("user@example.com");
Effect.runPromise(program);
// ^^^^^^^ Type Error!

You will see a red squiggly line under program in the line Effect.runPromise(program). When you hover over it, you will see this message:

Argument of type 'Effect<void, SendPasswordResetEmailError, Email>' is not assignable to parameter of type 'Effect<void, SendPasswordResetEmailError, never>' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
Type 'Email' is not assignable to type 'never'.ts(2379)

Focus on the last line: Type 'Email' is not assignable to type 'never'.

Why do we have this error and how do we fix it?

The type signature of program is Effect<void, SendPasswordResetEmailError, Email>. That Email in the third position is the requirements channel. It means Effect needs this requirement to be satisfied before it can run the program.

So how do we satisfy the requirement?

Using a Layer, which we will learn about in the next section.

Sign in to save progress

Stay in the loop

Get notified when new Effect Atom related content is published.