Integrating Effect with SvelteKit: Seeking Better Load Handlers

I've been experimenting with integrating Effect with SvelteKit. So far I'm finding it pretty successful but I'm curious if there's a better, more idiomatic(?) way to write load handlers than I'm currently doing. The exit handling in particular feels a little clunky to me. Having to await the Effect.runPromiseExit result before piping to Exit.getOrElse feels like I'm missing something. (cause) => cause.pipe(...) also feels like I'm missing an idiom. I'd greatly appreciate any insight!

import { AuthService, AuthServiceLive, ServerLoadEvent } from '$lib/server';
import { redirect } from '@sveltejs/kit';
import { Boolean, Cause, Effect, Exit, Layer, Option, pipe } from 'effect';
import type { PageServerLoad } from './$types';

class AlreadyAuthenticatedError {
  readonly _tag = 'AlreadyAuthenticatedError';
}

/**
 * Fail with an AlreadyAuthenticatedError if the user is already signed in,
 * otherwise succeed with no value.
 */
const program = AuthService.pipe(
  Effect.flatMap(({ isSignedIn }) => isSignedIn),
  Effect.flatMap(
    Boolean.match({
      onTrue: () => Effect.fail(new AlreadyAuthenticatedError()),
      onFalse: () => Effect.succeed<void>(undefined),
    }),
  ),
);

export const load: PageServerLoad = async (event) => {
  const MainLive = AuthServiceLive.pipe(
    Layer.provide(
      Layer.succeed(
        ServerLoadEvent, 
        ServerLoadEvent.of(event)
      )
    ),
  );

  /**
   * Redirect to the home page if the user is already signed in, otherwise
   * return no value.
   */
  return pipe(
    await Effect.runPromiseExit(Effect.provide(program, MainLive)),
    Exit.getOrElse((cause) =>
      cause.pipe(
        Cause.failureOption,
        Option.match({
          onNone: () => {},
          onSome: ({ _tag }) => {
            if (_tag === 'AlreadyAuthenticatedError') {
              redirect(303, '/');
            }
          },
        }),
      ),
    ),
  );
};
Was this page helpful?