Skip to content

Middleware: swap context - #915

Merged
KATT merged 15 commits into
mainfrom
mk/infer-ctx
Sep 9, 2021
Merged

KATT merged 15 commits into
mainfrom
mk/infer-ctx

Conversation

@mmkal

@mmkal mmkal commented Sep 9, 2021 •

Copy link
Copy Markdown
Contributor

From #818

@KATT I created a new PR because I made a lot of (type-level) changes.

  • Added TInputContext to Router and Procedure
  • Tests to make sure context-swapping works and doesn't have unexpected side-effects
  • Removed swapContext method for now - can be added later, but the use-case is supported via return next({ ctx: ... })
  • Replaced MiddlewareFunctionKeepContext and MiddlewareFunctionSwapContext with a single MiddlewareFunction type with an overloaded next input
  • Made next({ ctx: ... }) a function which can pass anything to ctx. The type passed is inferred as the TContext for the middleware's return value - this gets the expectTypeOf test added in the previous PR working
  • Removed a bunch of = any in type args. It was hard to keep track of what needed to be changed when defaults were used. I don't think any were internal so I've left them like that, but worth taking a look
  • Added a swap-context example to the docs

Notes for the future:

  • The types in procedure.ts are a bit loose. It's internal, so that's ok as long as it's covered by tests, but I think the crux is that it uses a middlewares array. I haven't tried this at all, but I think we could get more type safety by requiring that a procedure has exactly one middleware, and adding some helpers which compose middlewares. That way we can properly keep track of input and output contexts, instead of procedures having a list of unknown -> unknown middlewares.
  • Having ProcedureWithInput and ProcedureWithoutInput made this a bit harder than it feels like it should be. Maybe Procedure instances could always have inputs, where for convenience you can add queries/mutations/subscriptions to a router without, but the "input" defaults to () => undefined (which is a valid ProcedureInputParserCustomValidatorEsque, I believe)
  • When classes/interfaces start having loads of generics like here, something I've tried before is to have a single generic with properties, so you can do something like class Router<T extends TRouterOptions>{ ... }. Then to get the context you do T['context'], to get queries it'd be T['queries']. This can make it easier to write helper functions and refactor things without having to duplicate the ever-growing <TInputContext, TContext, TQueries, TMutations, TSubscriptions, TGodKnowsWhatElse> typearg lists, or fall back on potentially dangerous any defaults.

KATT and others added 4 commits August 22, 2021 12:43
Tests to make sure context-swapping works and doesn't have unexpected side-effects.

Remove swapContext method for now - can be added later, but the use-case is supported via `return next({ ctx: ... })`.
@vercel

vercel Bot commented Sep 9, 2021 •

Copy link
Copy Markdown

@mmkal
mmkal requested a review from KATT September 9, 2021 11:50
@KATT

KATT commented Sep 9, 2021

Copy link
Copy Markdown
Member

Wow, awesome! 🤩 Will review properly soon, right now just responding to your text!

@KATT I created a new PR because I made a lot of (type-level) changes.

👌

  • Added TInputContext to Router and Procedure
  • Should we see this as a breaking change or not? I've had issues before when libs changing type defs without major deps. Haven't reflected in detail if it'd cause any issues.
  • Haven't played with it yet, will ASAP - can I merge two a router with a router that has swapped the context? I also thought about the input/output context approach, I guess it should solve that.
  • Tests to make sure context-swapping works and doesn't have unexpected side-effects

💚 ✅

  • Removed swapContext method for now - can be added later, but the use-case is supported via return next({ ctx: ... })
  • Replaced MiddlewareFunctionKeepContext and MiddlewareFunctionSwapContext with a single MiddlewareFunction type with an overloaded next input

💯 - rip them out - I just had those there as a work in progress kinda thing.

  • Made next({ ctx: ... }) a function which can pass anything to ctx. The type passed is inferred as the TContext for the middleware's return value - this gets the expectTypeOf test added in the previous PR working

Yay!!

  • Removed a bunch of = any in type args. It was hard to keep track of what needed to be changed when defaults were used. I don't think any were internal so I've left them like that, but worth taking a look

👌

  • Added a swap-context example to the docs

👌 👌

  • The types in procedure.ts are a bit loose. It's internal, so that's ok as long as it's covered by tests, but I think the crux is that it uses a middlewares array. I haven't tried this at all, but I think we could get more type safety by requiring that a procedure has exactly one middleware, and adding some helpers which compose middlewares. That way we can properly keep track of input and output contexts, instead of procedures having a list of unknown -> unknown middlewares.

Agree with you - it's loose but it's kinda okay for now. The things we do in tRPC are possible thanks to TypeScript not being 100% pure and we are able to typecast stuff.

  • Having ProcedureWithInput and ProcedureWithoutInput made this a bit harder than it feels like it should be. Maybe Procedure instances could always have inputs, where for convenience you can add queries/mutations/subscriptions to a router without, but the "input" defaults to () => undefined (which is a valid ProcedureInputParserCustomValidatorEsque, I believe)

I'm impressed you worked this out on your own though, it was a bit of a bitch to make and I agree there should be a simpler approach.

  • When classes/interfaces start having loads of generics like here, something I've tried before is to have a single generic with properties, so you can do something like class Router<T extends TRouterOptions>{ ... }. Then to get the context you do T['context'], to get queries it'd be T['queries']. This can make it easier to write helper functions and refactor things without having to duplicate the ever-growing <TInputContext, TContext, TQueries, TMutations, TSubscriptions, TGodKnowsWhatElse> typearg lists, or fall back on potentially dangerous any defaults.

YES. I love options objects and I don't know why I haven't thought about doing this with generics!

@KATT KATT added @trpc/server 🧙🏻 typescript wizardry if you want a typescript-challenge, look at these labels Sep 9, 2021
# Conflicts:
#	packages/server/src/router.ts

@KATT KATT left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a failing test in 9d2f4ef

@KATT
KATT marked this pull request as draft September 9, 2021 13:01
@mmkal

mmkal commented Sep 9, 2021

Copy link
Copy Markdown
Contributor Author

@KATT good catch, hadn't tried merging routers. Hope it doesn't get crazy.

I added c99e345 to expose LegacyRouter as a subclass with the old type signature. The "main" router is called VNextRouter, and LegacyRotuer is exported in src/index.ts as Router so anyone using it via import { Router } from '@trpc/server' will still get the same signature. I added a test to verify it behaves as expected at runtime and compile-time. I think that's sufficient to make it backwards-compatible? I haven't deprecated it, because we could switch to the typearg-options-bag that way without confusing users.

@mmkal
mmkal requested a review from KATT September 9, 2021 14:22
@KATT KATT mentioned this pull request Sep 9, 2021
25 of 60 tasks

@KATT KATT left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some last few comments then I think it's good to go

Comment thread packages/server/src/router.ts Resolved
Comment thread packages/server/src/router.ts Resolved
Comment thread packages/server/src/index.ts Resolved
@KATT
KATT marked this pull request as ready for review September 9, 2021 15:10

@KATT KATT left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work - I did the last tweak in 741c90e - feel free to smash the merge button!

@KATT
KATT merged commit 919758d into main Sep 9, 2021
@KATT
KATT deleted the mk/infer-ctx branch September 9, 2021 16:24
@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Oct 10, 2022

This branch was successfully deployed

2 active deployments
Preview – www — 741c90e7 Deployed Sep 9, 2021 by vercel[bot]
Preview – todomvc — 741c90e7 Deployed Sep 9, 2021 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

♻️ autoupdate @trpc/server 🧙🏻 typescript wizardry if you want a typescript-challenge, look at these

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants