Last active
October 30, 2024 17:34
-
-
Save heddendorp/a18078fb065857b869beca83bf96353b to your computer and use it in GitHub Desktop.
Example link that uses angular httpClient to run trpc calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { inject, InjectionToken } from '@angular/core'; | |
| import type { AppRouter } from '@evorto/server/appRouter'; | |
| import { HttpClient } from '@angular/common/http'; | |
| import { CreateTRPCClient, createTRPCClient, TRPCLink } from '@trpc/client'; | |
| import type { AnyRouter } from '@trpc/server'; | |
| import { observable } from '@trpc/server/observable'; | |
| import superjson, { SuperJSONResult } from 'superjson'; | |
| const TRPC_CLIENT = new InjectionToken<CreateTRPCClient<AppRouter>>( | |
| 'TRPC_CLIENT', | |
| ); | |
| export interface AngularLinkOptions { | |
| url: string; | |
| } | |
| const angularLink = (http: HttpClient) => { | |
| return <TRouter extends AnyRouter>( | |
| opts: AngularLinkOptions, | |
| ): TRPCLink<TRouter> => { | |
| return (runtime) => | |
| ({ op }) => | |
| observable((observer) => { | |
| const url = `${opts.url}/${op.path}`; | |
| switch (op.type) { | |
| case 'subscription': | |
| throw new Error('Subscriptions are not supported'); | |
| case 'query': { | |
| http | |
| .get<{ | |
| result: { data: SuperJSONResult }; | |
| }>(url, { params: { input: JSON.stringify(superjson.serialize(op.input)) } }) | |
| .subscribe((res) => { | |
| const parsedResponse = superjson.deserialize(res.result.data); | |
| observer.next({ | |
| result: { | |
| type: 'data', | |
| data: parsedResponse, | |
| }, | |
| }); | |
| observer.complete(); | |
| }); | |
| break; | |
| } | |
| case 'mutation': { | |
| http | |
| .post<{ | |
| result: { data: SuperJSONResult }; | |
| }>(url, superjson.serialize(op.input)) | |
| .subscribe((res) => { | |
| const parsedResponse = superjson.deserialize(res.result.data); | |
| observer.next({ | |
| result: { | |
| type: 'data', | |
| data: parsedResponse, | |
| }, | |
| }); | |
| observer.complete(); | |
| }); | |
| break; | |
| } | |
| } | |
| }); | |
| }; | |
| }; | |
| export const provideTrpcClient = () => { | |
| return { | |
| provide: TRPC_CLIENT, | |
| useFactory: (http: HttpClient) => { | |
| const link = angularLink(http); | |
| return createTRPCClient<AppRouter>({ | |
| links: [link({ url: '/trpc' })], | |
| }); | |
| }, | |
| deps: [HttpClient], | |
| }; | |
| }; | |
| export function injectTrpcClient() { | |
| return inject(TRPC_CLIENT); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment