optimism
optimism copied to clipboard
feat(common-ts): Make base service v2 api typesafe by default with trpc
I add trpc which is the best way to create APIs with typescript that are meant to be consumed by other typescript services or UI. The cool thing is with 0 boilerplate typesafe functions are created that you can call on any client. They even include nice features such as caching and automatic request batching.
- Create an API object with BaseServiceV2
const trpcApi = BaseServiceV2.createApi()
- Register a unique endpoint on it
const trpcApi = BaseServiceV2.query('user', {
})
- Each query takes in json object as parameter. Use zod to validate it and to automatically infer typescript types
const trpcApi = BaseServiceV2.createAPI().query('user', {
input: z.object({
id: z.string(),
}),
})
- Add a resolver and you are done! You created an endpoint that can be consumed on the frontend with no further boilerplate! The entire feature will be typesafe e2e.
const trpcApi = BaseServiceV2.createAPI().query('user', {
/**
* Zod will validate input and also allow typescript to infer types
*/
input: z.object({
id: z.string(),
}),
// Resolve the endpoint here
resolve: async (req) => {
// this request will be typesafe
return users.getFromDb<User>(req.id)
},
})
The client can then import the Router type. This only imports the typescript type and no actual server code is included. From the typescript type, the client can safely call the API with the correct params and be guaranteed to be in sync with the server. This will make it stupidly quick and simple for any dev to build a full stack feature.
🦋 Changeset detected
Latest commit: daf5b6a87366455eaea538b9f6dcfbc31baa5a21
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 6 packages
| Name | Type |
|---|---|
| @eth-optimism/common-ts | Major |
| @eth-optimism/data-transport-layer | Patch |
| @eth-optimism/drippie-mon | Patch |
| @eth-optimism/fault-detector | Patch |
| @eth-optimism/message-relayer | Patch |
| @eth-optimism/replica-healthcheck | Patch |
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
This PR changes implementation code, but doesn't include a changeset. Did you forget to add one?
No rush to review this can wait til after devcon
trpc version 10 though in beta is much better than version 9 and has a lot of breaking changes. Putting this in draft because we should start with version 10 instead
This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days.