TypeSafe API Integrations with TypeScript Operations & GraphQL
If you're looking for a solution to combine data from multiple APIs, you might have already stumbled upon our JOIN feature. This feature allows you to combine data from multiple APIs in a single query, just using GraphQL.
However, sometimes it takes a bit more than just doing a JOIN. You might also want to add some custom business logic, e.g. to transform the data.
In this guide, we'll show you how to do this with TypeScript Operations.
Setup
Let's add two APIs to the wundergraph.config.ts
, weather and countries, so we've got something to work with.
We put each API into its own namespace, this way there will be no collisions.
Defining two GraphQL Operations
Next, we'll define one GraphQL Operation for each API to be able to combine them later.
Let's start with the Country Operation:
This operation will fetch the weather for a given city. Second, we'll define the Weather Operation:
This operation will fetch the weather for a given city.
Combining two GraphQL Operations using a TypeScript Operation
Now, we'll combine the two GraphQL Operations using a TypeScript Operations.
Using the combined GraphQL Operation from the client
In the final step, we'll use the combined GraphQL Operation from our NextJS frontend.
Type-safe Error Handling
In TypeScript Operations you can create custom errors which will be available to the client in the code
field of the error. This allows you to have typed errors on the client side, which can be used to handle errors in a more granular way. Custom errors are defined by extending the OperationError
class and passed to the errors
field of the handler definition. The statusCode
field is optional and defines the final response status code (defaults to 500
).
Now, when we call this operation with b
being 0
, we'll get the following error:
Conclusion
That's it! We've successfully combined data from two APIs and handled error cases fully type-safe.
Bonus points: Access the user through the context
As a bonus, I just wanted to show you that you can also access the user through the context.
WunderGraph supports various authentication methods out of the box, the most common one is OpenID Connect (OIDC). Let's assume that we're using an OIDC provider that returns the user's city in the location
claim.
We can leverage this to create an Operation that returns the weather for the user's city.
We've also set requireAuthentication: true
to make sure that the user is authenticated. With that, we've implemented a simple way to present the user with the weather for their city.
That's it for now! I hope you enjoyed this guide and learned something new.