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

feat(react-router): add SerializesTo brand type #12264

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from

Conversation

phryneas
Copy link

Apart from the turbo-stream support for ReadableStream, this is the only other change that we would need to add support for preloading Apollo Client data during SSR in loader functions.

The problem here is that Apollo Client uses a branded type QueryRef<TData, TVariables> that looks like this:

export interface QueryRef<TData = unknown, TVariables = unknown> {
  /** @internal */
  [QUERY_REF_BRAND]?(variables: TVariables): TData;
}

We are using an "imaginary" function here to preserve variance when passing around the type - TVariables should be contravariant, so it is referenced as a method argument, while TData is covariant, so it is passed as a method return value.

This function doesn't really exist on the transport object and no other properties on it are typed, since the user should never interact with the object apart from passing it into a consuming useReadQuery(queryRef) hook in the browser.

Unfortunately, currently that QueryRef above is turned into { [QUERY_REF_BRAND]?: undefined }, since Serialize removes all functions.

This SerializesTo type would be an escape hatch to allow it for e.g. library authors to pass around branded values like this by specifying what the "serialized" result type should be.

So the preloadQuery function that we provide for loaders would return something of the type SerializesTo<QueryRef<TData, TVariables>>.

Copy link

changeset-bot bot commented Nov 12, 2024

🦋 Changeset detected

Latest commit: 938d3d9

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
react-router Major
@react-router/architect Major
@react-router/cloudflare Major
@react-router/dev Major
react-router-dom Major
@react-router/express Major
@react-router/node Major
@react-router/serve Major
@react-router/fs-routes Major
@react-router/remix-routes-option-adapter Major
create-react-router Major

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@remix-cla-bot
Copy link
Contributor

remix-cla-bot bot commented Nov 12, 2024

Hi @phryneas,

Welcome, and thank you for contributing to React Router!

Before we consider your pull request, we ask that you sign our Contributor License Agreement (CLA). We require this only once.

You may review the CLA and sign it by adding your name to contributors.yml.

Once the CLA is signed, the CLA Signed label will be added to the pull request.

If you have already signed the CLA and received this response in error, or if you have any questions, please contact us at [email protected].

Thanks!

- The Remix team

@remix-cla-bot
Copy link
Contributor

remix-cla-bot bot commented Nov 12, 2024

Thank you for signing the Contributor License Agreement. Let's get this merged! 🥳

@MichaelDeBoey MichaelDeBoey changed the title Add SerializesTo brand type. feat(react-router): add SerializesTo brand type Nov 13, 2024
.changeset/sour-avocados-lick.md Outdated Show resolved Hide resolved
@phryneas
Copy link
Author

phryneas commented Nov 25, 2024

Okay, seems like a lot of things moved in the last two weeks, did some merging and reorganizing.

Verified with a local build in apollographql/apollo-client-nextjs@2b56da6 (#394) that the type still works as expected.

@phryneas
Copy link
Author

phryneas commented Jan 9, 2025

At this time, this feature is ready on the Apollo side, so I would ask you to please give this a review, or at least some feedback, as this type change is the "missing piece" for us.

The whole PR can be seen here: apollographql/apollo-client-nextjs#394
This would be used in userland like this: https://github.com/apollographql/apollo-client-nextjs/blob/pr/react-router-7/integration-test/react-router/app/routes/home.tsx
You can see this "live" here: https://apolloc-git-ab15ba-apollo-client-next-package-integration-tests.vercel.app/ - a multipart graphql request is started during SSR in a loader, and both in SSR and in the browser, the results are merged into a normalized cache. You can see multiple chunks coming in slightly delayed, and as it is a client-side normalized cache, it can be live manipulated and refetched on the client without another server roundtrip (but navigation can merge more loader data in in the future).

@pcattori pcattori self-assigned this Jan 9, 2025
@timdorr timdorr removed the request for review from MichaelDeBoey January 9, 2025 19:02
@phryneas
Copy link
Author

@pcattori is there anything I can do from my side to help this move forward? Are there any open questions that you need answered?

* in your application.
*/
export type SerializesTo<T> = {
$__RR_SerializesTo?: [T];
Copy link
Contributor

Choose a reason for hiding this comment

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

@phryneas I was expecting $__RR_SerializesTo?: T without the wrapping []. Does wrapping in [] come with any benefits over unwrapped T?

Copy link
Author

Choose a reason for hiding this comment

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

It's probably not a big deal, but It's slightly more safe around undefined:

{
  interface WithoutWrapping<T> {
    foo?: T;
  }

  type SerializesTo<T> = T extends WithoutWrapping<infer F> ? F : "other";

  type Test1 = SerializesTo<WithoutWrapping<number>>;
  //    ^?  type Test1 = number

  type Test2 = SerializesTo<WithoutWrapping<number|undefined>>;
  //    ^?  type Test2 = number | undefined

  // this could happen if for some reason the TS compiler inlines the `WithoutWrapping` type
  // when creating declarations for a third-party-package
  // an explicitly stated `undefined` would get lost
  type Test3 = SerializesTo<{ foo?: number|undefined }>;
  //    ^?  type Test3 = number
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Could you explain why the brand is optional in the first place?

Why not have:

export type SerializesTo<T> = {
  __ReactRouter_SerializesTo: T;
}

Copy link
Author

@phryneas phryneas Jan 24, 2025

Choose a reason for hiding this comment

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

For assignability reasons - if it were non-optional you'd need an as any or as unknown when using it (example is obviously oversimplified):

type SerializesTo<T> = {
  __ReactRouter_SerializesTo?: [T];
};


const foo: number & SerializesTo<string> = 5

type SerializesToNonOptional<T> = {
  __ReactRouter_SerializesTo: [T];
};

// this errors
const bar: number & SerializesToNonOptional<string> = 5

Copy link
Author

Choose a reason for hiding this comment

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

Also, just thinking of this - this is not actually there at runtime, so it keeps the type kinda "correct" in line with what you'd expect at runtime.

* in your application.
*/
export type SerializesTo<T> = {
$__RR_SerializesTo?: [T];
Copy link
Contributor

Choose a reason for hiding this comment

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

Is the $__ prefix a widely used convention? I was thinking of __ReactRouter_ prefix instead of $__RR_ just for increased clarity, but wasn't sure if there were conventions I'm unaware of

Copy link
Author

@phryneas phryneas Jan 24, 2025

Choose a reason for hiding this comment

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

I'm perfectly fine with __ReactRouter_SerializesTo, too - I just hadn't seen any precedence and wanted to be extra sure :)

We use the $ (even with a space) in GraphQL because it's not allowed per spec for field names and we avoid collisions, but here it's not really necessary.

I'll fix this up to be __ReactRouter_SerializesTo later!

Copy link
Author

Choose a reason for hiding this comment

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

Okay, made that change!

@phryneas phryneas requested a review from pcattori January 24, 2025 08:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants