Type-safe JavaScript API clients on all projects!
Every Gadget project comes with a rich, autogenerated GraphQL API that you use to query and mutate data stored in Gadget. However, interacting with a raw GraphQL API can be burdensome. You need to implement authentication, data hydration, pagination and, for TypeScript users, type generation.
To address these challenges, we’re announcing that, starting today, every Gadget project has its own purpose-built, type safe Javascript API client library. Your application’s API client can be installed as an npm module or sourced with a <script/> tag. This API gives you easy functions for running queries and mutations on your data.
Your client will
- Hydrate data on its way to or from your app, letting you work with JS objects like <inline-code>Date<inline-code> instead of dates as strings
- Paginate any list of records from your app with one simple <inline-code>nextPage()<inline-code> or <inline-code>.previousPage()<inline-code> call
- Authenticate using any of Gadget’s supported authentication schemes
- Make bulk API calls to your backend
- Typecheck inputs parameters and query responses against the schema defined in your Gadget application
Let’s take a look at an example. For my simple blog application, I can install the generated JavaScript client by adding Gadget’s npm registry, and then installing my module:
Once I have my client, I’ll instantiate it and start making API calls:
Like GraphQL, the generated client supports dynamic selections of different properties when querying data. For example, let’s say that our Post model Belongs To an Author model in our blog. if you want to select the blog post’s id, the post title, and author’s name of each post, you can use the <inline-code>select<inline-code> option:
This query will return just the fields you selected, just like GraphQL, ensuring minimal, fast communication between the server and the client.
Unlike most other clients, our selections are fully typed with TypeScript! If you’re using an editor that supports TypeScript, your editor will know what fields are present on the returned records, and can warn you if your properties aren’t part of the selection :
The <inline-code>select<inline-code> option is typed, preventing you from selecting fields that don’t exist:
As a developer using Gadget, you no longer need to configure a code generator or build step to get this type safety. Your API client package has these types built in, ready to use, just like that.