Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type-safe context state #5

Merged
merged 3 commits into from
May 16, 2024
Merged

Add type-safe context state #5

merged 3 commits into from
May 16, 2024

Conversation

EthanThatOneKid
Copy link
Contributor

@EthanThatOneKid EthanThatOneKid commented May 9, 2024

Changes

Adds state to class Router.

const statefulRouter = createRouter(
  (r) =>
    r
      .get(
        "/*",
        async (ctx) => {
          ctx.state.user = { name: "Alice" };
          return await ctx.next();
        },
      )
      .get<"name">(
        "/:name",
        (ctx) => {
          if (ctx.state.user === null) {
            return new Response("Unauthorized", { status: 401 });
          }

          if (ctx.state.user.name !== ctx.params.name) {
            return new Response("Forbidden", { status: 403 });
          }

          return new Response(`Hello, ${ctx.params.name}!`);
        },
      ),
  (): { user: User | null } => ({ user: null }),
);

interface User {
  name: string;
}

Implications of updated Router.fetch API

  • Possible disadvantage: internal variables exposed to library user. The fetch method is intended to be called with its first argument, request, so url, state, i are intended for internal use only, despite allowing developers to pass their own values.
  • Advantage: The values of the arguments url, state, and i are only evaluated as necessary; the values are preserved in subsequent recursive calls.

@EthanThatOneKid EthanThatOneKid linked an issue May 9, 2024 that may be closed by this pull request
rt.ts Show resolved Hide resolved
rt.ts Show resolved Hide resolved
rt.ts Show resolved Hide resolved
@EthanThatOneKid EthanThatOneKid marked this pull request as ready for review May 16, 2024 01:24
@EthanThatOneKid EthanThatOneKid merged commit ef23e24 into main May 16, 2024
1 check passed
@EthanThatOneKid EthanThatOneKid deleted the state branch May 16, 2024 01:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Modify state of context
1 participant