Guides
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.
That's it! We've successfully combined data from two APIs, 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.