Cuándo (No) Crear un Servidor GraphQL

Rate this content
Bookmark

Cada desarrollador (frontend) está pidiendo una API GraphQL pero a menudo carece del conocimiento backend para crear un servidor eficiente. Hay muchos sabores diferentes para crear el servidor GraphQL perfecto, desde el enfoque de esquema primero hasta el enfoque de código primero o incluso soluciones generadas automáticamente. Permíteme mostrarte los pros y los contras de cada solución para que, después de esta charla, sepas cuál solución se ajustaría mejor a tu equipo.

8 min
09 Dec, 2021

Video Summary and Transcription

Construir un servidor GraphQL escalable puede ser desafiante. Hay múltiples razones para construir un servidor GraphQL, como optimizar las solicitudes del cliente y envolver microservicios. El servidor GraphQL basado en SDL te permite escribir tu esquema por separado de tus resolvers, dándote un control total. Puedes crear automáticamente una API GraphQL a partir de un esquema, simplificando el proceso y eliminando la necesidad de implementaciones manuales. El esquema puede vincular fuentes de datos y APIs de terceros, permitiendo una integración y personalización sencillas.

Available in English

1. Introducción al servidor GraphQL

Short description:

Construir un servidor GraphQL escalable puede ser desafiante. Hay múltiples razones para construir un servidor GraphQL, como optimizar las solicitudes del cliente y envolver microservicios. Hay diferentes formas y patrones para crear un servidor GraphQL, siendo el enfoque de código primero uno de ellos.

Hola a todos. Mi nombre es Roy y bienvenidos a mi charla, cuando no crear un servidor GraphQL. ¿Para quién es esto? Es muy fácil construir un servidor GraphQL, pero es realmente difícil hacer un servidor GraphQL escalable. La escalabilidad a veces te golpeará en el trasero cuando empieces a escribir un servidor GraphQL. Hay muchas bibliotecas para construir una API GraphQL y hay muchos patrones diferentes para construir una API GraphQL y los exploraremos todos en esta charla. También mostraremos una forma de crear un servidor GraphQL automáticamente basado en tus backends existentes.

Un poco sobre mí. Mi nombre es Roy. Soy ingeniero de software y orador público. Puedes encontrarme en Twitter con el nombre de usuario, AdGetHackTeam y he escrito muchos libros sobre React y también GraphQL, el último es full stack GraphQL.

Antes de sumergirnos en cómo construir un servidor GraphQL, también echemos un vistazo a por qué quieres construir un servidor GraphQL en primer lugar. Hay muchas razones para construir un servidor GraphQL y creo que la primera es optimizar las solicitudes del cliente. Tienes un cliente que consume una API, pero de alguna manera tu API REST o tal vez diferentes tipos de llamadas API no son tan eficientes. Quieres tener esa eficiencia y también quieres dar cierta autonomía al usuario. Entonces, GraphQL no solo está ahí para resolver el problema de M más uno donde podrías estar obteniendo o enviando demasiados GraphQL, demasiados puntos finales REST, sino que GraphQL también le da autonomía al usuario. Como cliente, tienes más control sobre los tipos, sobre los datos que fluyen en tu aplicación. Optimizar las solicitudes del cliente no es la única forma o la única razón para crear un servidor GraphQL. También podría ser para envolver tus microservicios, por lo que GraphQL es perfectamente adecuado para unir múltiples microservicios que pueden ser microservicios GraphQL, pero también microservicios construidos con otra tecnología. Y también es muy bueno para envolver servicios heredados con esa capa de datos GraphQL. Hay múltiples razones para construir un servidor GraphQL y estas son dos razones perfectamente válidas para construir uno.

Hay múltiples formas de crear un servidor GraphQL. Como mencioné al principio, no hay una forma correcta. Hay muchas formas diferentes y muchos patrones diferentes y bibliotecas que te ayudarán con eso. El primer patrón que tenemos aquí es un servidor GraphQL de código primero. Con un servidor GraphQL de código primero, siempre comienzas escribiendo resolvers. Y estos resolvers generalmente usan clases o si estás usando TypeScript, probablemente usen un sistema de tipos de TypeScript para definir los resultados que devuelven estos resolvers. Y en función de esos resultados, un servidor GraphQL de código primero generará un esquema basado en los resolvers. Y luego, por supuesto, creará un servidor para ti. Y hay una gran desventaja, puedes hacer todo programáticamente. Pero la desventaja es que es muy difícil tener una separación de preocupaciones.

2. Creación de una API GraphQL a partir de un esquema

Short description:

El servidor GraphQL SDL first te permite escribir tu esquema por separado de tus resolvers, dándote control total. Sin embargo, este enfoque requiere escribir tanto resolvers como esquemas, lo cual puede llevar tiempo. Como alternativa, puedes crear automáticamente una API GraphQL a partir de un esquema utilizando el paso 10. Esto simplifica el proceso al generar resolvers en la nube y conectarse a diversas fuentes de datos, como bases de datos, APIs REST u otras APIs GraphQL. La API GraphQL sin servidor resultante maneja la escalabilidad y el rendimiento, eliminando la necesidad de implementaciones manuales.

Literalmente, no hay separación de preocupaciones, porque tu esquema se crea a partir de resolvers, y los resolvers son el único código que tienes. Por lo tanto, no tienes control sobre cómo se verá el esquema en última instancia. Para solucionar esto, existe el servidor SDL first GraphQL, también conocido como servidor schema first GraphQL.

La idea aquí es que escribas tu esquema, ya sea en SDL de GraphQL, de ahí el servidor SDL first, o puedes hacerlo con algunas bibliotecas externas. Existe la biblioteca GraphQL JS, que te permite escribir servidores schema first GraphQL, pero no utilizando SDL, sino sus propios métodos. Pero la idea es simple, creas tu esquema, creas tus resolvers basados en este esquema y esto creará un servidor para ti. Así que tienes una separación de preocupaciones muy buena, tienes tus esquemas separados de tus resolvers y tienes control total sobre todo. Pero esto, por supuesto, tiene las principales desventajas y escribir tanto resolvers como esquemas es mucho trabajo.

Afortunadamente, hay una solución. También puedes crear automáticamente tu API GraphQL a partir de un esquema. Y esto se puede hacer con el paso 10, como ejemplo. Veamos cómo funciona. Crear una API de gráficos con el paso 10 es muy sencillo. Simplemente escribes tu esquema. Puedes definir todos los tipos que tienes. Y estos tipos estarán vinculados a una fuente de datos de la que provienen. Y esto puede ser cualquier backend, como veremos más adelante. Y nuestra CLI generará automáticamente resolvers en el servidor para ti, directamente en la nube. Así que se implementará sin servidor, no tienes que preocuparte por ninguna implementación o por la escalabilidad de tus resolvers. Puedes conectar cualquier fuente de datos. Pueden ser bases de datos, ya sea SQL o Postgres. Pueden ser APIs REST, pueden ser APIs GraphQL, puedes conectar literalmente cualquier otra fuente de datos. Y luego, en función de esta fuente de datos, se creará una API GraphQL completamente sin servidor y de alto rendimiento para ti. Ya no tenemos que preocuparnos por la escalabilidad, el rendimiento o las implementaciones, todo se hará por ti. Y esto utiliza solo el lenguaje de diseño de esquemas de GraphQL. Aquí tienes dos ejemplos para MySQL Postgres a la izquierda y REST a la derecha. Como puedes ver, se utilizan directivas personalizadas para vincularse a la fuente de datos. Así que desde tu esquema, utilizando solo el lenguaje de diseño de esquemas de GraphQL, puedes crear conexiones con cualquier backend o cualquier fuente de datos. Además de Postgres y REST, también puedes usar cualquier otra API GraphQL como fuente de datos, como veremos en este ejemplo. Lo que tenemos aquí es un esquema.

3. Vinculación de fuentes de datos y APIs de terceros

Short description:

El esquema vinculará las fuentes de datos por ti y creará un servidor en la nube. Se pueden agregar tipos adicionales como el idioma y vincularlos a los países. Se utilizará una directiva personalizada para conectar la información del idioma del país. La última versión del esquema siempre está disponible en los pasos. También se pueden integrar APIs de terceros y SaaS utilizando Step Send GraphQL Studio, una ID interactiva en tu navegador. Crea tu propia API seleccionando esquemas, ejecutando consultas e implementándola en la nube.

Y en el esquema, estaremos vinculando las data fuentes de datos por ti. Como puedes ver, simplemente puedes ejecutar step send start. Esto creará automáticamente un servidor para nosotros. Por lo tanto, se implementará en step send, lo que significa que se implementará en la cloud y luego estará disponible un punto de conexión.

Y luego, por supuesto, también podemos agregar más tipos aquí, como un idioma. Y este idioma puede estar vinculado al país. Entonces un país puede tener un idioma. Para esto, utilizaremos otra directiva personalizada y la vincularemos a una consulta existente. Entonces, para obtener el idioma del país, también se utilizará el IPL que conecta la información de un país. Y tan pronto como comencemos a guardar esto, se implementará automáticamente nuevamente. Por lo tanto, siempre tendrás la última versión de tu esquema en los pasos.

Y también puedes hacer esto con APIs de terceros o SaaS. Hace poco lanzamos un nuevo producto llamado Step Send GraphQL Studio. Puedes encontrarlo en graphql.stepsend.com. Y esto es una ID interactiva directamente en tu navegador donde puedes jugar con APIs de terceros, como step.to GitHub o Twitter, puedes vincularlos todos juntos, ya sea por separado o encontrando algunas combinaciones que hemos hecho para ti. Y directamente desde el navegador, puedes crear tu propia API seleccionando algunos esquemas, ejecutando algunas consultas, e implementándola también en la cloud. Entonces, si escaneas este código QR o vas a graphql.stepsend.com, ya puedes encontrar esto ahí mismo para ti.

Eso es principalmente todo. Tuvimos poco tiempo para cubrir todo. Mi nombre es Roy. Puedes encontrarme en Twitter como Edgate Hack Team. Puedes encontrar Stepsend en stepsend.com. Y también puedes encontrar nuestro producto GraphQL Studio en graphql.stepsend.com. Gracias, y espero verte por aquí.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
We all love GraphQL, but it can be daunting to get a server up and running and keep your code organized, maintainable, and testable over the long term. No more! Come watch as I go from an empty directory to a fully fledged GraphQL API in minutes flat. Plus, see how easy it is to use and create directives to clean up your code even more. You're gonna love GraphQL even more once you make things Redwood Easy!
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.
React Summit Remote Edition 2021React Summit Remote Edition 2021
43 min
RedwoodJS: The Full-Stack React App Framework of Your Dreams
Top Content
Tired of rebuilding your React-based web framework from scratch for every new project? You're in luck! RedwoodJS is a full-stack web application framework (think Rails but for JS/TS devs) based on React, Apollo GraphQL, and Prisma 2. We do the heavy integration work so you don't have to. We also beautifully integrate Jest and Storybook, and offer built-in solutions for declarative data fetching, authentication, pre-rendering, logging, a11y, and tons more. Deploy to Netlify, Vercel, or go oldschool on AWS or bare metal. In this talk you'll learn about the RedwoodJS architecture, see core features in action, and walk away with a sense of wonder and awe in your heart.

Workshops on related topic

GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
JSNation 2023JSNation 2023
174 min
Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
Featured WorkshopFree
This SvelteKit workshop explores the integration of 3rd party services, such as Storyblok, in a SvelteKit project. Participants will learn how to create a SvelteKit project, leverage Svelte components, and connect to external APIs. The workshop covers important concepts including SSR, CSR, static site generation, and deploying the application using adapters. By the end of the workshop, attendees will have a solid understanding of building SvelteKit applications with API integrations and be prepared for deployment.
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura