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

exploration for Apollo Client integration #2698

Draft
wants to merge 15 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions examples/react/start-basic-apollo-client/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
node_modules
package-lock.json
yarn.lock

.DS_Store
.cache
.env
.vercel
.output
.vinxi

/build/
/api/
/server/build
/public/build
.vinxi
# Sentry Config File
.env.sentry-build-plugin
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
4 changes: 4 additions & 0 deletions examples/react/start-basic-apollo-client/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
**/build
**/public
pnpm-lock.yaml
routeTree.gen.ts
72 changes: 72 additions & 0 deletions examples/react/start-basic-apollo-client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Welcome to TanStack.com!

This site is built with TanStack Router!

- [TanStack Router Docs](https://tanstack.com/router)

It's deployed automagically with Vercel!

- [Vercel](https://vercel.com/)

## Development

From your terminal:

```sh
pnpm install
pnpm dev
```

This starts your app in development mode, rebuilding assets on file changes.

## Editing and previewing the docs of TanStack projects locally

The documentations for all TanStack projects except for `React Charts` are hosted on [https://tanstack.com](https://tanstack.com), powered by this TanStack Router app.
In production, the markdown doc pages are fetched from the GitHub repos of the projects, but in development they are read from the local file system.

Follow these steps if you want to edit the doc pages of a project (in these steps we'll assume it's [`TanStack/form`](https://github.com/tanstack/form)) and preview them locally :

1. Create a new directory called `tanstack`.

```sh
mkdir tanstack
```

2. Enter the directory and clone this repo and the repo of the project there.

```sh
cd tanstack
git clone git@github.com:TanStack/tanstack.com.git
git clone git@github.com:TanStack/form.git
```

> [!NOTE]
> Your `tanstack` directory should look like this:
>
> ```
> tanstack/
> |
> +-- form/
> |
> +-- tanstack.com/
> ```
> [!WARNING]
> Make sure the name of the directory in your local file system matches the name of the project's repo. For example, `tanstack/form` must be cloned into `form` (this is the default) instead of `some-other-name`, because that way, the doc pages won't be found.
3. Enter the `tanstack/tanstack.com` directory, install the dependencies and run the app in dev mode:
```sh
cd tanstack.com
pnpm i
# The app will run on https://localhost:3000 by default
pnpm dev
```
4. Now you can visit http://localhost:3000/form/latest/docs/overview in the browser and see the changes you make in `tanstack/form/docs`.

> [!NOTE]
> The updated pages need to be manually reloaded in the browser.
> [!WARNING]
> You will need to update the `docs/config.json` file (in the project's repo) if you add a new doc page!
12 changes: 12 additions & 0 deletions examples/react/start-basic-apollo-client/app.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { defineConfig } from '@tanstack/start/config'
import tsConfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
vite: {
plugins: [
tsConfigPaths({
projects: ['./tsconfig.json'],
}),
],
},
})
6 changes: 6 additions & 0 deletions examples/react/start-basic-apollo-client/app/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {
createStartAPIHandler,
defaultAPIFileRouteHandler,
} from '@tanstack/start/api'

export default createStartAPIHandler(defaultAPIFileRouteHandler)
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { ApolloClient as _ApolloClient } from '@apollo/client-react-streaming'
import { streamingLink } from './StreamLink'
import { ensureHydrated } from './createQueryPreloader'
import type { ApolloLink } from '@apollo/client/index.js'
import type { HookWrappers } from '@apollo/client/react/internal'

function id<T>(x: T): T {
return x
}

const WRAPPERS = Symbol.for('apollo.hook.wrappers')

export class ApolloClient extends _ApolloClient {
constructor(options: ConstructorParameters<typeof _ApolloClient>[0]) {
super(options)
this.setLink(this.link)

const queryManager = this['queryManager'] as { [WRAPPERS]: HookWrappers }

const origWrappers = { ...queryManager[WRAPPERS] }

queryManager[WRAPPERS] = {
...origWrappers,
useReadQuery: (originalHook) => (queryRef) => {
return (origWrappers.useReadQuery || id)(originalHook)(
ensureHydrated(queryRef, this),
)
},
useQueryRefHandlers: (originalHook) => (queryRef) => {
return (origWrappers.useQueryRefHandlers || id)(originalHook)<any, any>(
ensureHydrated(queryRef, this),
)
},
} satisfies HookWrappers
}

setLink(newLink: ApolloLink) {
_ApolloClient.prototype.setLink.call(this, streamingLink.concat(newLink))
}
}
102 changes: 102 additions & 0 deletions examples/react/start-basic-apollo-client/app/apollo/ApolloProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import {
DataTransportContext,
WrapApolloProvider,
} from '@apollo/client-react-streaming'
import { useRouter } from '@tanstack/react-router'
import { useCallback, useEffect, useId, useMemo, useRef } from 'react'
import type { QueryEvent } from '@apollo/client-react-streaming'

const APOLLO_EVENT_PREFIX = '@@apollo.event/'
const APOLLO_HOOK_PREFIX = '@@apollo.hook/'

const handledEvents = new WeakSet<object>()

export const ApolloProvider = (props: React.PropsWithChildren) => {
const router = useRouter()
return (
<WrappedApolloProvider
makeClient={() => router.options.context.apolloClient}
>
{props.children}
</WrappedApolloProvider>
)
}

const WrappedApolloProvider = WrapApolloProvider((props) => {
const router = useRouter()

const consumeBackPressure = useCallback(() => {
for (const key of router.streamedKeys) {
if (key.startsWith(APOLLO_EVENT_PREFIX)) {
const streamedValue = router.getStreamedValue(key)
if (
streamedValue &&
typeof streamedValue === 'object' &&
!handledEvents.has(streamedValue) &&
props.onQueryEvent
) {
handledEvents.add(streamedValue)
props.onQueryEvent(streamedValue as QueryEvent)
}
}
}
}, [router, props.onQueryEvent])

if (router.isServer) {
props.registerDispatchRequestStarted!(({ event, observable }) => {
router.streamValue(
`${APOLLO_EVENT_PREFIX}${event.id}/${event.type}`,
event satisfies QueryEvent,
)
observable.subscribe({
next(event) {
router.streamValue(
`${APOLLO_EVENT_PREFIX}${event.id}/${event.type}`,
event satisfies QueryEvent,
)
},
})
})
} else {
// this needs to happen synchronously before the render continues
// so "loading" is kicked off before the respecitve component is rendered
consumeBackPressure()
}

useEffect(() => {
consumeBackPressure()
return router.subscribe('onStreamedValue', ({ key }) => {
if (!key.startsWith(APOLLO_EVENT_PREFIX)) return
const streamedValue = router.getStreamedValue(key)
if (streamedValue && props.onQueryEvent) {
handledEvents.add(streamedValue)
props.onQueryEvent(streamedValue as QueryEvent)
}
})
}, [consumeBackPressure, router, props.onQueryEvent])

const dataTransport = useMemo(() => ({ useStaticValueRef }), [])

return (
<DataTransportContext.Provider value={dataTransport}>
{props.children}
</DataTransportContext.Provider>
)
})

function useStaticValueRef<T>(value: T) {
const router = useRouter()
const key = APOLLO_HOOK_PREFIX + useId()
const dataValue =
!router.isServer && router.streamedKeys.has(key)
? (router.getStreamedValue(key) as T)
: value
const dataRef = useRef(dataValue)

if (router.isServer) {
if (!router.streamedKeys.has(key)) {
router.streamValue(key, value)
}
}
return dataRef
}
84 changes: 84 additions & 0 deletions examples/react/start-basic-apollo-client/app/apollo/StreamLink.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { ApolloLink, Observable } from '@apollo/client/index.js'
import type { FetchResult } from '@apollo/client/index.js'

export type StreamLinkEvent =
| { type: 'next'; value: FetchResult }
| { type: 'completed' }
| { type: 'error' }

export const streamingLink = new ApolloLink((operation, forward) => {
const context = operation.getContext()

const injectIntoStream = context.__injectIntoStream as
| undefined
| ReadableStreamDefaultController<StreamLinkEvent>

if (injectIntoStream) {
return new Observable((observer) => {
const subscription = forward(operation).subscribe({
next: (result) => {
injectIntoStream.enqueue({ type: 'next', value: result })
observer.next(result)
},
error: (error) => {
injectIntoStream.enqueue({ type: 'error' })
injectIntoStream.close()
observer.error(error)
},
complete: () => {
injectIntoStream.enqueue({ type: 'completed' })
injectIntoStream.close()
observer.complete()
},
})

return () => {
subscription.unsubscribe()
}
})
}

const eventSteam = context.__eventStream as
| ReadableStream<StreamLinkEvent>
| undefined
if (eventSteam) {
return new Observable((observer) => {
let aborted = false
const reader = eventSteam.getReader()
consumeReader()

return () => {
aborted = true
reader.cancel()
}

async function consumeReader() {
let event: ReadableStreamReadResult<StreamLinkEvent> | undefined =
undefined
while (!aborted && !event?.done) {
event = await reader.read()
if (aborted as boolean) break
if (event.value) {
switch (event.value.type) {
case 'next':
observer.next(event.value.value)
break
case 'completed':
observer.complete()
break
case 'error':
observer.error(
new Error(
'Error from event stream. Redacted for security concerns.',
),
)
break
}
}
}
}
})
}

return forward(operation)
})
Loading