Fully-featured GraphQL Server with focus on easy setup, performance & great developer experience
graphql-yoga
is based on the following libraries & tools:
express
/apollo-server
: Performant, extensible web server frameworkgraphql-subscriptions
/subscriptions-transport-ws
: GraphQL subscriptions servergraphql.js
/graphql-tools
: GraphQL engine & schema helpersgraphql-playground
: Interactive GraphQL IDEapplication/json
and application/graphql
content-typesnow
, up
, AWS Lambda, Heroku etc.yarn add graphql-yoga
import { GraphQLServer } from 'graphql-yoga'
// ... or using `require()`
// const { GraphQLServer } = require('graphql-yoga')
const typeDefs = `
type Query {
hello(name: String): String!
}
`
const resolvers = {
Query: {
hello: (_, { name }) => `Hello ${name || 'World'}`,
},
}
const server = new GraphQLServer({ typeDefs, resolvers })
server.start(() => console.log('Server is running on localhost:4000'))
To get started with
graphql-yoga
, follow the instructions in the READMEs of the examples.
GraphQLServer
constructor(props: Props): GraphQLServer
The props
argument accepts the following fields:
Key | Type | Default | Note |
---|---|---|---|
typeDefs |
String or Function or DocumentNode or array of previous |
null |
Contains GraphQL type definitions in SDL or file path to type definitions (required if schema is not provided *) |
resolvers |
Object | null |
Contains resolvers for the fields specified in typeDefs (required if schema is not provided *) |
resolverValidationOptions |
Object | null |
Object which controls the resolver validation behaviour (see "Generating a schema") for more information |
schema |
Object | null |
An instance of GraphQLSchema (required if typeDefs and resolvers are not provided *) |
mocks |
Object or Boolean | null |
Applies mocks to schema. Setting this to true will apply a default mock, however you can pass an object to customize the mocks similar to the resolvers map. |
context |
Object or Function | {} |
Contains custom data being passed through your resolver chain. This can be passed in as an object, or as a Function with the signature (req: ContextParameters) => any ** |
schemaDirectives |
Object | null |
Apollo Server schema directives that allow for transforming schema types, fields, and arguments |
middlewares |
array of Middleware |
[] |
A list of GraphQLMiddleware middleware. |
(*) There are two major ways of providing the schema information to the
constructor
:
- Provide
typeDefs
andresolvers
and omit theschema
, in this casegraphql-yoga
will construct theGraphQLSchema
instance usingmakeExecutableSchema
fromgraphql-tools
.- Provide the
schema
directly and omittypeDefs
andresolvers
.
(**) Notice that the
req
argument is an object of the shape{ request, response, connection }
which either carries arequest: Request
property (when it's aQuery
/Mutation
resolver),response: Response
property (when it's aQuery
/Mutation
resolver), or aconnection: SubscriptionOptions
property (when it's aSubscription
resolver).Request
is imported from Express.js.Response
is imported from Express.js aswell.SubscriptionOptions
is from thegraphql-subscriptions
package.SubscriptionOptions
are getting theconnectionParams
automatically injected underSubscriptionOptions.context.[CONNECTION_PARAMETER_NAME]
Here is example of creating a new server:
const typeDefs = `
type Query {
hello(name: String): String!
}
`
const resolvers = {
Query: {
hello: (_, { name }) => `Hello ${name || 'World'}`,
},
}
const server = new GraphQLServer({ typeDefs, resolvers })
start(options: Options, callback: ((options: Options) => void) = (() => null)): Promise<void>
Once your GraphQLServer
is instantiated, you can call the start
method on it. It takes two arguments: options
, the options object defined above, and callback
, a function that's invoked right before the server is started. As an example, the callback
can be used to print information that the server has started.
The options
object has the following fields:
Key | Type | Default | Note |
---|---|---|---|
cors |
Object | null |
Contains configuration options for cors |
tracing |
Boolean or TracingOptions | 'http-header' |
Indicates whether Apollo Tracing should be enabled or disabled for your server (if a string is provided, accepted values are: 'enabled' , 'disabled' , 'http-header' ) |
port |
Number or String | 4000 |
Determines the port your server will be listening on (note that you can also specify the port by setting the PORT environment variable) |
endpoint |
String | '/' |
Defines the HTTP endpoint of your server |
subscriptions |
Object or String or false |
'/' |
Defines the subscriptions (websocket) endpoint for your server; accepts an object with subscription server options path , keepAlive , onConnect and onDisconnect ; setting to false disables subscriptions completely |
playground |
String or false |
'/' |
Defines the endpoint where you can invoke the Playground; setting to false disables the playground endpoint |
defaultPlaygroundQuery |
String | undefined |
Defines default query displayed in Playground. |
uploads |
UploadOptions or false or undefined |
null |
Provides information about upload limits; the object can have any combination of the following three keys: maxFieldSize , maxFileSize , maxFiles ; each of these have values of type Number; setting to false disables file uploading |
https |
HttpsOptions or undefined |
undefined |
Enables HTTPS support with a key/cert |
getEndpoint |
String or Boolean | false |
Adds a graphql HTTP GET endpoint to your server (defaults to endpoint if true ). Used for leveraging CDN level caching. |
deduplicator |
Boolean | true |
Enables graphql-deduplicator. Once enabled sending the header X-GraphQL-Deduplicate will deduplicate the data. |
bodyParserOptions |
BodyParserJSONOptions | BodyParserJSONOptions Defaults | Allows pass through of body-parser options |
Additionally, the options
object exposes these apollo-server
options:
Key | Type | Note |
---|---|---|
cacheControl |
Boolean | Enable extension that returns Cache Control data in the response |
formatError |
Number | A function to apply to every error before sending the response to clients. Defaults to defaultErrorFormatter. Please beware, that if you override this, requestId and code on errors won't automatically be propagated to your yoga server |
logFunction |
LogFunction | A function called for logging events such as execution times |
rootValue |
any | RootValue passed to GraphQL execution |
validationRules |
Array of functions | Additional GraphQL validation rules to be applied to client-specified queries |
fieldResolver |
GraphQLFieldResolver | Specify a custom default field resolver function |
formatParams |
Function | A function applied to each query in a batch to format parameters before execution |
formatResponse |
Function | A function applied to each response after execution |
debug |
boolean | Print additional debug logging if execution errors occur |
const options = {
port: 8000,
endpoint: '/graphql',
subscriptions: '/subscriptions',
playground: '/playground',
}
server.start(options, ({ port }) =>
console.log(
`Server started, listening on port ${port} for incoming requests.`,
),
)
PubSub
See the original documentation in graphql-subscriptions
.
mocking
Mocking the schema is straight forward, along wit
import { GraphqlServer, MockList } from 'graphql-yoga'
const typeDefs = `
type Query {
hello(name: String): String!
listOfStrings: [String]
}
`
const mocks = {
Query: () => ({
hello: () => 'Hello World',
listOfStrings: () => new MockList([2, 6]),
}),
}
const server = new GraphQLServer({ typeDefs, mocks })
There are three examples demonstrating how to quickly get started with graphql-yoga
:
hello
query.create-react-app
demonstrating how to query data from graphql-yoga
with Apollo Client 2.0.Once your graphql-yoga
server is running, you can use GraphQL Playground out of the box – typically running on localhost:4000
. (Read here for more information.)
now
To deploy your graphql-yoga
server with now
, follow these instructions:
graphql-yoga
servernow
in your terminalTo deploy your graphql-yoga
server with Heroku, follow these instructions:
heroku login
graphql-yoga
serverheroku create
git push heroku master
up
(Coming soon
graphql-yoga
compare to apollo-server
and other tools?As mentioned above, graphql-yoga
is built on top of a variety of other packages, such as graphql.js
, express
and apollo-server
. Each of these provides a certain piece of functionality required for building a GraphQL server.
Using these packages individually incurs overhead in the setup process and requires you to write a lot of boilerplate. graphql-yoga
abstracts away the initial complexity and required boilerplate and lets you get started quickly with a set of sensible defaults for your server configuration.
graphql-yoga
is like create-react-app
for building GraphQL servers.
express
and graphql.js
?graphql-yoga
is all about convenience and a great "Getting Started" experience by abstracting away the complexity that comes when you're building your own GraphQL server from scratch. It's a pragmatic approach to bootstrap a GraphQL server, much like how create-react-app
removes friction when first starting out with React.
Whenever the defaults of graphql-yoga
are too tight a corset for you, you can simply eject from it and use the tooling it's built upon - there's no lock-in or any other kind of magic going on preventing you from doing this.
express
setup?The core value of graphql-yoga
is that you don't have to write the boilerplate required to configure your express.js application. However, once you need to add more customized behaviour to your server, the default configuration provided by graphql-yoga
might not suit your use case any more. For example, it might be the case that you want to add more custom middleware to your server, like for logging or error reporting.
For these cases, GraphQLServer
exposes the express.Application
directly via its express
property:
server.express.use(myMiddleware())
Middleware can also be added specifically to the GraphQL endpoint route, by using:
server.express.post(server.options.endpoint, myMiddleware())
Any middleware you add to that route, will be added right before the apollo-server-express
middleware.
Join our Slack community if you run into issues or have questions. We love talking to you!
GraphQL 最佳入门实战 高性能服务器开发 5天前 前言 痛点:网上找的资料,文章, GraphQL的官网,一看就是很‘自我’的大神写的(太烂了)完全管读者能不能看懂,举例子只讲用法!不告诉代码怎么实现的(但是当你学完这一篇你就可以看懂了), 并且从来不晒出整体代码,导致根本不知道他们怎么玩的,有被冒犯到!!可以说那些资料都不适合入门。 定位:GraphQL并不是必须用的技术, 但它是必须会的
以下内容基于graphql-yoga,它是基于apollo graphql server,并整合了 graphql-subscriptions/subscriptions-transport-ws: GraphQL subscriptions server graphql.js/graphql-tools: GraphQL engine & schema helpers graphql-playg
转自官方文档 In the last article, we discussed the ins and outs of remote (executable) schemas. These remote schemas are the foundation for a set of tools and techniques referred to as schema stitching. S
快速开始 GraphQL 是一种用于 API 的查询语言。这是 GraphQL 和 REST 之间一个很好的比较 (译者注: GraphQL 替代 REST 是必然趋势)。在这组文章中, 我们不会解释什幺是 GraphQL, 而是演示如何使用 @nestjs/GraphQL 模块。 GraphQLModule 只不过是 Apollo 服务器的包装器。我们没有造轮子, 而是提供一个现成的模块, 这让
GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。 GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。 向你的 API 发出一个 GraphQL 请求就能准确获得你想要的数据,不多不少。 GraphQL 查询总是返回可预测
Graphql editor 是一款 Graphql 的可视化编辑器和 IDE,帮助用户更容易理解 GraphQL 模式,通过使用可视化块系统创建模式。GraphQL Editor 将把它们转化为代码。通过 GraphQL Editor,用户可以在不写任何代码的情况下创建可视化的图表,或者以一种很好的方式呈现其模式。 GraphQL View Code Editor View Hierarchy View
GraphQL CLI Help us to improve new GraphQL CLI. Check out the new structure and commands below!Feel free to contact us in Discord channel. We would love to hear your feedback. Features Helpful command
Fullstack GraphQL Simple Demo Application API built with Node + Express + GraphQL + Sequelize (supports MySQL, Postgres, Sqlite and MSSQL). WebApp built with React + Redux. Written in ES6 using Babel
Hasura GraphQL Engine Hasura is an open source product that accelerates API development by 10x by giving you GraphQL or REST APIs with built in authorization on your data, instantly. Read more at hasu