How to convert TypeScript types to GraphQL types: better serverless functions

What if you could write TypeScript functions and that was enough to make a fully typed API in GraphQL? And while we’re at it, can we get better serverless functions?

Write this...

... and get this...

type Email {
  id: Int!
  address: String!
  body: String!
}

type Mutation {
  sendEmail(address: String!, body: String!): number!
  sendEmailWithSignature(address: String!, body: String!): number!
  getEmail(id: Int!): Email!
}


These aren't just types – we can get a full API.

How it works

Here's the code that makes getting a fully typed API possible: https://github.com/hasura/ndc-typescript-deno

The gist of it is parsing the TypeScript code (the TypeScript compiler exposes libraries for this), and then building out the GraphQL API.

Hasura v3 has a connector architecture, where the engine (that receives and executes the query) uses connectors to connect different data sources to the graph. In Hasura, the TypeScript code is run by a connector, and the engine is configured by way of Hasura metadata (a data modeling tool) with the types and models that are backed by the functions

We can literally just write TypeScript functions and run a few commands to get a GraphQL API. To me, this is the most compelling implementation of serverless functions. Other serverless functions today don't really run functions as much as they get you to implement http servers. The advantage of defining only functions is that the engine can now expose different APIs on top of it, be it GraphQL, RPC, or any other. Functions also compose far better than http endpoints, which allows for building semantic graphs.

Conclusion

Hasura wants to empower TypeScript developers to deploy their work and make it usable for a wide audience. Larger organizations can incorporate the functions into their supergraph implementations.

We believe in a declarative future, to bring maximum power to domain engineers, and the Hasura TypeScript connector is a big part of that story – by allowing architects to extend their model-based supergraph with custom logic and side-effects.

Resources

Build TypeScript connectors: https://github.com/hasura/ndc-typescript-deno

A real example that integrates with Sendgrid: https://github.com/hasura/ndc-sendgrid-deno

Blog
08 Nov, 2023
Email
Subscribe to stay up-to-date on all things Hasura. One newsletter, once a month.
Loading...
v3-pattern
Accelerate development and data access with radically reduced complexity.