GraphQL con Golang: un análisis profundo de lo básico a lo avanzado

GraphQL se ha convertido en una palabra de moda en los últimos años después de que Facebook lo convirtió en código abierto. Probé GraphQL con Node.js, y estoy de acuerdo con todos los rumores sobre las ventajas y la simplicidad de GraphQL.

Entonces, ¿qué es GraphQL? Esto es lo que dice la definición oficial de GraphQL:

GraphQL es un lenguaje de consulta para API y tiempo de ejecución para completar esas consultas con sus datos existentes. GraphQL proporciona una descripción completa y comprensible de los datos en su API, brinda a los clientes el poder de pedir exactamente lo que necesitan y nada más, facilita la evolución de las API con el tiempo y habilita poderosas herramientas de desarrollo.

Recientemente me cambié a Golang para un nuevo proyecto en el que estoy trabajando (de Node.js) y decidí probar GraphQL con él. No hay muchas opciones de biblioteca con Golang, pero lo he probado con Thunder, graphql, graphql-go y gqlgen. Y tengo que decir que gqlgen está ganando entre todas las bibliotecas que he probado.

gqlgen todavía se encuentra en beta con la última versión 0.7.2 al momento de escribir este artículo, y está evolucionando rápidamente. Puede encontrar su hoja de ruta aquí. Y ahora 99designs los patrocina oficialmente, por lo que veremos una velocidad de desarrollo aún mejor para este increíble proyecto de código abierto. vektah y neelance son contribuyentes importantes, y neelance también escribió graphql-go.

Así que profundicemos en la semántica de la biblioteca asumiendo que tiene conocimientos básicos de GraphQL.

Destacar

Como dice su titular,

Esta es una biblioteca para crear rápidamente servidores GraphQL estrictamente tipados en Golang.

Creo que esto es lo más prometedor de la biblioteca: nunca verá map[string]interface{}aquí, ya que utiliza un enfoque estrictamente mecanografiado.

Aparte de eso, utiliza un primer enfoque de esquema : por lo que define su API utilizando el lenguaje de definición de esquema graphql. Esto tiene sus propias herramientas de generación de código poderosas que generarán automáticamente todo su código GraphQL y solo necesitará implementar la lógica central de ese método de interfaz.

He dividido este artículo en dos fases:

  • Conceptos básicos: configuración, mutaciones, consultas y suscripción
  • Lo avanzado: autenticación, cargadores de datos y complejidad de consultas

Fase 1: Conceptos básicos: configuración, mutaciones, consultas y suscripciones

Usaremos un sitio de publicación de videos como ejemplo en el que un usuario puede publicar un video, agregar capturas de pantalla, agregar una reseña y obtener videos y videos relacionados.

mkdir -p $GOPATH/src/github.com/ridhamtarpara/go-graphql-demo/

Cree el siguiente esquema en la raíz del proyecto:

Aquí hemos definido nuestros modelos básicos y una mutación para publicar nuevos videos, y una consulta para obtener todos los videos. Puede leer más sobre el esquema graphql aquí. También hemos definido un tipo personalizado (escalar), ya que por defecto graphql solo tiene 5 tipos escalares que incluyen Int, Float, String, Boolean e ID.

Entonces, si desea utilizar un tipo personalizado, puede definir un escalar personalizado schema.graphql(como lo hemos definido Timestamp) y proporcionar su definición en el código. En gqlgen, debe proporcionar métodos marshal y unmarshal para todos los escalares personalizados y asignarlos a gqlgen.yml.

Otro cambio importante en gqlgen en la última versión es que han eliminado la dependencia de los binarios compilados. Así que agregue el siguiente archivo a su proyecto en scripts / gqlgen.go.

e inicializar dep con:

dep init

Ahora es el momento de aprovechar la función de codegen de la biblioteca que genera todo el código esqueleto aburrido (pero interesante para algunos).

go run scripts/gqlgen.go init

que creará los siguientes archivos:

gqlgen.yml : archivo de configuración para controlar la generación de código.

generate.go : el código generado que es posible que no desee ver.

models_gen.go : todos los modelos para la entrada y el tipo de su esquema proporcionado.

resolver.go : debes escribir tus implementaciones.

server / server.go : punto de entrada con un http.Handler para iniciar el servidor GraphQL.

Echemos un vistazo a uno de los modelos generados del Videotipo:

Aquí, como puede ver, ID se define como una cadena y CreatedAt también es una cadena. Otros modelos relacionados se asignan en consecuencia, pero en el mundo real no desea esto; si está utilizando cualquier tipo de datos SQL, desea que su campo de ID sea int o int64, según su base de datos.

Por ejemplo, estoy usando PostgreSQL para la demostración, así que, por supuesto , quiero ID como int y CreatedAt como time.Time . Por lo tanto, debemos definir nuestro propio modelo e indicarle a gqlgen que use nuestro modelo en lugar de generar uno nuevo.

y actualice gqlgen para usar estos modelos como este:

Entonces, el punto focal son las definiciones personalizadas para ID y Timestamp con los métodos marshal y unmarshal y su mapeo en un archivo gqlgen.yml. Ahora, cuando el usuario proporciona una cadena como ID, UnmarshalID convertirá una cadena en un int. Al enviar la respuesta, MarshalID convertirá int en string. Lo mismo ocurre con la marca de tiempo o cualquier otro escalar personalizado que defina.

Ahora es el momento de implementar la lógica real. Abrir resolver.goy dar definición a mutación y consultas. Los stubs ya están generados automáticamente con una declaración de pánico no implementada, así que anulemos eso.

y golpea la mutación:

Ohh funcionó ... pero espera, ¿por qué mi usuario está vacío? Entonces, aquí hay un concepto similar como carga perezosa y ansiosa. Como graphQL es extensible, debe definir qué campos desea completar con entusiasmo y cuáles con pereza.

I have created this golden rule for my organization team working with gqlgen:

Don’t include the fields in a model which you want to load only when requested by the client.

For our use-case, I want to load Related Videos (and even users) only if a client asks for those fields. But as we have included those fields in the models, gqlgen will assume that you will provide those values while resolving video — so currently we are getting an empty struct.

Sometimes you need a certain type of data every time, so you don’t want to load it with another query. Rather you can use something like SQL joins to improve performance. For one use-case (not included in the article), I needed video metadata every time with the video which is stored in a different place. So if I loaded it when requested, I would need another query. But as I knew my requirements (that I need it everywhere on the client side), I preferred it to load eagerly to improve the performance.

So let’s rewrite the model and regenerate the gqlgen code. For the sake of simplicity, we will only define methods for the user.

So we have added UserID and removed User struct and regenerated the code:

go run scripts/gqlgen.go -v

This will generate the following interface methods to resolve the undefined structs and you need to define those in your resolver:

And here is our definition:

Now the result should look something like this:

So this covers the very basics of graphql and should get you started. Try a few things with graphql and the power of Golang! But before that, let’s have a look at subscription which should be included in the scope of this article.

Subscriptions

Graphql provides subscription as an operation type which allows you to subscribe to real tile data in GraphQL. gqlgen provides web socket-based real-time subscription events.

You need to define your subscription in the schema.graphql file. Here we are subscribing to the video publishing event.

Regenerate the code by running: go run scripts/gqlgen.go -v.

As explained earlier, it will make one interface in generated.go which you need to implement in your resolver. In our case, it looks like this:

Now, you need to emit events when a new video is created. As you can see on line 23 we have done that.

And it’s time to test the subscription:

GraphQL comes with certain advantages, but everything that glitters is not gold. You need to take care of a few things like authorizations, query complexity, caching, N+1 query problem, rate limiting, and a few more issues — otherwise it will put you in performance jeopardy.

Phase 2: The advanced - Authentication, Dataloaders, and Query Complexity

Every time I read a tutorial like this, I feel like I know everything I need to know and can get my all problems solved.

But when I start working on things on my own, I usually end up getting an internal server error or never-ending requests or dead ends and I have to dig deep into that to carve my way out. Hopefully we can help prevent that here.

Let’s take a look at a few advanced concepts starting with basic authentication.

Authentication

In a REST API, you have a sort of authentication system and some out of the box authorizations on particular endpoints. But in GraphQL, only one endpoint is exposed so you can achieve this with schema directives.

You need to edit your schema.graphql as follows:

We have created an isAuthenticated directive and now we have applied that directive to createVideo subscription. After you regenerate code you need to give a definition of the directive. Currently, directives are implemented as struct methods instead of the interface so we have to give a definition.

I have updated the generated code of server.go and created a method to return graphql config for server.go as follows:

We have read the userId from the context. Looks strange right? How was userId inserted in the context and why in context? Ok, so gqlgen only provides you the request contexts at the implementation level, so you can not read any of the HTTP request data like headers or cookies in graphql resolvers or directives. Therefore, you need to add your middleware and fetch those data and put the data in your context.

So we need to define auth middleware to fetch auth data from the request and validate.

I haven’t defined any logic there, but instead I passed the userId as authorization for demo purposes. Then chain this middleware in server.go along with the new config loading method.

Now, the directive definition makes sense. Don’t handle unauthorized users in your middleware as it will be handled by your directive.

Demo time:

You can even pass arguments in the schema directives like this:

directive @hasRole(role: Role!) on FIELD_DEFINITIONenum Role { ADMIN USER }

Dataloaders

This all looks fancy, doesn’t it? You are loading data when needed. Clients have control of the data, there is no under-fetching and no over-fetching. But everything comes with a cost.

So what’s the cost here? Let’s take a look at the logs while fetching all the videos. We have 8 video entries and there are 5 users.

query{ Videos(limit: 10){ name user{ name } }}
Query: Videos : SELECT id, name, description, url, created_at, user_id FROM videos ORDER BY created_at desc limit $1 offset $2Resolver: User : SELECT id, name, email FROM users where id = $1Resolver: User : SELECT id, name, email FROM users where id = $1Resolver: User : SELECT id, name, email FROM users where id = $1Resolver: User : SELECT id, name, email FROM users where id = $1Resolver: User : SELECT id, name, email FROM users where id = $1Resolver: User : SELECT id, name, email FROM users where id = $1Resolver: User : SELECT id, name, email FROM users where id = $1Resolver: User : SELECT id, name, email FROM users where id = $1

Why 9 queries (1 videos table and 8 users table)? It looks horrible. I was just about to have a heart attack when I thought about replacing our current REST API servers with this…but dataloaders came as a complete cure for it!

This is known as the N+1 problem, There will be one query to get all the data and for each data (N) there will be another database query.

This is a very serious issue in terms of performance and resources: although these queries are parallel, they will use your resources up.

We will use the dataloaden library from the author of gqlgen. It is a Go- generated library. We will generate the dataloader for the user first.

go get github.com/vektah/dataloadendataloaden github.com/ridhamtarpara/go-graphql-demo/api.User

This will generate a file userloader_gen.go which has methods like Fetch, LoadAll, and Prime.

Now, we need to define the Fetch method to get the result in bulk.

Here, we are waiting for 1ms for a user to load queries and we have kept a maximum batch of 100 queries. So now, instead of firing a query for each user, dataloader will wait for either 1 millisecond for 100 users before hitting the database. We need to change our user resolver logic to use dataloader instead of the previous query logic.

After this, my logs look like this for similar data:

Query: Videos : SELECT id, name, description, url, created_at, user_id FROM videos ORDER BY created_at desc limit $1 offset $2Dataloader: User : SELECT id, name, email from users WHERE id IN ($1, $2, $3, $4, $5)

Now only two queries are fired, so everyone is happy. The interesting thing is that only five user keys are given to query even though 8 videos are there. So dataloader removed duplicate entries.

Query Complexity

In GraphQL you are giving a powerful way for the client to fetch whatever they need, but this exposes you to the risk of denial of service attacks.

Let’s understand this through an example which we’ve been referring to for this whole article.

Now we have a related field in video type which returns related videos. And each related video is of the graphql video type so they all have related videos too…and this goes on.

Consider the following query to understand the severity of the situation:

{ Videos(limit: 10, offset: 0){ name url related(limit: 10, offset: 0){ name url related(limit: 10, offset: 0){ name url related(limit: 100, offset: 0){ name url } } } }}

If I add one more subobject or increase the limit to 100, then it will be millions of videos loading in one call. Perhaps (or rather definitely) this will make your database and service unresponsive.

gqlgen provides a way to define the maximum query complexity allowed in one call. You just need to add one line (Line 5 in the following snippet) in your graphql handler and define the maximum complexity (300 in our case).

gqlgen assigns fix complexity weight for each field so it will consider struct, array, and string all as equals. So for this query, complexity will be 12. But we know that nested fields weigh too much, so we need to tell gqlgen to calculate accordingly (in simple terms, use multiplication instead of just sum).

Just like directives, complexity is also defined as struct, so we have changed our config method accordingly.

I haven’t defined the related method logic and just returned the empty array. So related is empty in the output, but this should give you a clear idea about how to use the query complexity.

Final Notes

This code is on Github. You can play around with it, and if you have any questions or concerns let me know in the comment section.

Thanks for reading! A few (hopefully 50) claps? are always appreciated. I write about JavaScript, the Go Language, DevOps, and Computer Science. Follow me and share this article if you like it.

Reach out to me on @Twitter @Linkedin. Visit www.ridham.me for more.