Last active
January 12, 2023 08:45
-
-
Save esamattis/d38e1260733c99c19585dafb861a7259 to your computer and use it in GitHub Desktop.
tRPC local / test link for testing
This file contains 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
/** | |
* Terminating link that directly calls the tRPC router | |
*/ | |
export function createTestLink<TRouter extends AnyRouter>(opts: { | |
headers: () => Promise<Record<string, string>>; | |
router: TRouter; | |
}): TRPCLink<TRouter> { | |
return () => { | |
return (runtime) => { | |
return observable((observer) => { | |
const invokeRouter = async () => { | |
const headers = await opts.headers(); | |
const caller = opts.router.createCaller({ | |
request: new Request( | |
"http://test.invalid" + runtime.op.path, | |
{ headers }, | |
), | |
}) as any; | |
const res = await caller[runtime.op.path]( | |
runtime.op.input, | |
).catch((error: any) => { | |
console.log( | |
`tRPC Error in ${runtime.op.type}:${runtime.op.path}\n`, | |
error.stack, | |
); | |
throw new TRPCClientError( | |
error.message || "Unknown error", | |
{ | |
cause: error, | |
}, | |
); | |
}); | |
observer.next({ | |
result: { | |
data: res, | |
}, | |
}); | |
observer.complete(); | |
}; | |
invokeRouter().catch((error) => { | |
observer.error(error); | |
}); | |
}); | |
}; | |
}; | |
} |
This file contains 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
const client = createTRPCProxyClient<CLIRouterType>({ | |
links: [ | |
createTestLink({ | |
headers: myCreateHeadersFn, | |
router: TheTrpcRouter, | |
}), | |
], | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment