Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Announcing GraphQL Yoga 2.0!
The Guild profile imageTheGuildBot
TheGuildBot forThe Guild

Posted on • Originally published atthe-guild.dev

     

Announcing GraphQL Yoga 2.0!

This article was published on 2022-03-29 byCharly Poly @The Guild Blog

Today we are incredibly excited to share with you the new GraphQL Yoga! This release was made possible with your contributions, issues, and feedback.

The Guild took over the development of GraphQL Yoga fromPrisma in early 2021, and with the growing community of tools in the GraphQL space, most recentlyEnvelop, we were able to rewrite GraphQL Yoga 2.0 from scratch with easy setup, performance, and developer experience at the core.

GraphQL Yoga continues to boast a "convention over configuration" approach and the freedom to use your favorite libraries, from HTTP to schema-building.

No longer are you required to install dozens of dependencies to get features such as subscriptions, file uploads, CORS, error masking, and more.

Building a GraphQL Yoga server requires a single import and only a few lines of code to start serving an API. And you also getGraphiQL for making development even easier.

// 1. Import GraphQL Yogaimport{createServer}from'@graphql-yoga/node'// 2. Create your serverconstserver=createServer({schema:{typeDefs:/* GraphQL */`      type Query {        hello: String      }    `,resolvers:{Query:{hello:()=>'Hello Hello Hello'}}}})// 3. Serve the API and GraphiQLserver.start()
Enter fullscreen modeExit fullscreen mode

 

The Yoga v2 experience

Your stack and habits

The main goal of Yoga v2 is toallow you to leverage all the GraphQL ecosystem by being compatible with most of the existing schema-design, HTTP server libraries, and deployment environments.

Built on top of amodular and extendable GraphQL Server, Yoga v2 allows you to use your preferred schema design approach and HTTP server library.

For example, Yoga v2 is fully compatible with Express and Nexus, with no additional packages:

importexpressfrom'express'import{makeSchema,queryType}from'nexus'import{createServer}from'@graphql-yoga/node'constQuery=queryType({definition(t){t.string('hello',{resolve:()=>'hello world!'})}})constschema=makeSchema({types:[Query]})constgraphQLServer=createServer({schema})constapp=express()// Bind GraphQL Yoga to the `/graphql` endpoint// Here it takes the request and response objects and handles them internallyapp.use('/graphql',graphQLServer)app.listen(4000,()=>{console.log('Running a GraphQL API server at http://localhost:4000/graphql')})
Enter fullscreen modeExit fullscreen mode

The same applies toGraphQL Tools, Pothos, Nexus, TypeGraphQL, SDL first schema-design approaches,graphql-js, Apollo Tools, Fastify, Koa, Next.js, SvelteKit, and Deno.

Beyond the compatibility of schema-design and HTTP server libraries, Yoga v2 makesdeploying a GraphQL API to any environment seamless (Vercel Functions, Cloudflare Workers, AWS Lambda and more).

Here, a GraphQL API built with GraphQL Modules, deployed on Cloudflare Workers:

import{createServer}from'@graphql-yoga/common'import{createApplication}from'graphql-modules'import{helloWorldModule}from'./helloWorld'constapplication=createApplication({modules:[helloWorldModule]})constserver=createServer({schema:application.schema})server.start()
Enter fullscreen modeExit fullscreen mode

 

Productivity at your fingertips

Batteries-included

Yoga v2 comes withsensible defaults to make development faster, all withcomplete TypeScript support.

Features common to modern GraphQL APIs such as file-uploads, subscription support, advanced error handling, or CORScome built-in with Yoga:

import{createServer,GraphQLYogaError}from'@graphql-yoga/node'// Provide your schemaconstserver=createServer({schema:{typeDefs:/* GraphQL */`      # adding this custom scalar enables file upload support      scalar Upload      type Query {        hello: String      }      type Subscription {        countdown(from: Int!): Int!      }      type Mutation {        readTextFile(file: Upload!): String      }    `,resolvers:{Query:{hello:()=>'world'},Subscription:{countdown:{// This will return the value on every 1 sec until it reaches 0subscribe:asyncfunction*(_,{from}){for(leti=from;i>=0;i--){awaitnewPromise((resolve)=>setTimeout(resolve,1000))yield{countdown:i}}}}},Mutation:{readTextFile:async(_,{file}:{file:File})=>{lettextContent=nulltry{textContent=awaitfile.text()}catch(e){// return an error visible by the clientthrownewGraphQLYogaError(`Failed to parse file`)}returntextContent}}}}})// We now serve a GraphQL API with Subscriptions (over SSE), CORS,// and File uploads support!server.start()
Enter fullscreen modeExit fullscreen mode

Yoga v2 also provides APIs to handlelogging, advanced Subscriptions use-cases (over WS, Pub/Sub), ApolloFederation Support,and more.

 

Easily extend your API with Envelop plugins

GraphQL Yoga supportsEnvelop out of the box, which gives you greater control, and the ability to hook into the GraphQL execution phases.

Here, we are building a full-featured GraphQL API with security rules, a response cache and sentry error reporting with only a few lines of code:

import{createServer}from'@graphql-yoga/node'import{useDepthLimit}from'@envelop/depth-limit'import{useResponseCache}from'@envelop/response-cache'import{useSentry}from'@envelop/sentry'import{schema}from'./schema'constserver=createServer({schema:{typeDefs:/* GraphQL */`      type Query {        hello: String      }    `,resolvers:{Query:{hello:()=>'Hello Hello Hello'}}},plugins:[useDepthLimit({// set up some security rulesmaxDepth:10}),useResponseCache(),// speed up our server with a response cacheuseSentry()// report unexpected errors to sentry]})// Start the server and explore http://localhost:4000/graphqlserver.start()
Enter fullscreen modeExit fullscreen mode

The Envelop Plugin currentlyproposes more than 35+ plugins covering most of the standard GraphQL APIs features you need in production.

Ultimately, you candevelop custom Envelop plugins to create reusable behaviors that hook on to the GraphQL lifecycle.

 

Production-ready

GraphQL Yoga v2 has been built in production for production usage.

Built-in real-world conditions within our projects (e.g.GraphQL Mesh) and with some ofour clients, performance was highly prioritised.
The core of Yoga is as performant as possible, and we continuously keep track and improve it.

Also, the Yoga V2 repository runs performance checks on every commit and Pull Request, so we can always capture any performance regression.

Last but not least, every commit is ensured to run on all deployment targets such as AWS Lambda or Cloudflare workers through an End-To-End testing suite!

We continue our effort of pushing GraphQL Yoga to more production environments with the imminent release ofRedwood 1.0 that uses Yoga 2.0 as its default GraphQL server.

 

A standards-compliant GraphQL Server

In the same way that TypeScript aims to stay aligned with ECMAScript, GraphQL Yoga is based on several official and recognized specs:

GraphQL features from the future

Yoga v2 supports some experimental GraphQL features such as@defer and@stream, allowing you to get a taste of the future of GraphQL (with compatible clients such asURQL).

Also, thanks to the Envelop plugin system, Yoga v2 can also act as"Babel for GraphQL", giving you the option to use features that are not yet in the GraphQL spec but are very useful in production today, like defer and stream andOneOf.

 

Get started with Yoga v2

Yoga v2 provides the best GraphQL experience while giving you the freedom to use your preferred stack and tools.

Get started from scratch with our new tutorial ...

Want to try it? Giveour brand new tutorial a try! It will guide you in building a full-featured, modern API with GraphQL Yoga.

Episode #24 ofgraphql.wtf is a also great introduction to GraphQL Yoga 2.0:

... or migrate your existing GraphQL server to Yoga

All Yoga v2's featuresare well documented on the website and we also havesome migration guides (from v1, Apollo Server and Express GraphQL).

 

What's next

Yoga v2 is the biggest and most important project we released to date; still, it is just the beginning of our GraphQL server vision.

We can't wait to get yourquestions, user feedback, and feature requests/PRs, and we already plan for new features such as an Enhanced Plugin System that will provide features similar to Envelop but at the request level.

Don't hesitate to reach out to us on Twitter and support us bysharing this article!

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
westernal profile image
Ali Navidi
Maybe a Frontend Developer

Interesting!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

More fromThe Guild

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp