Launching Visual Studio

If nothing happens, download the thienmaonline.vn extension for Visual Studio and try again.

Bạn đang xem: Prisma là gì

Go back

*

graphql-yoga

*
*

Fully-featured GraphQL Server with focus on easy setup, performance & great developer experience

OverviewEasiest way to run a GraphQL server: Sensible defaults & includes everything you need with minimal setup.Includes Subscriptions: Built-in support for GraphQL subscriptions using WebSockets.Compatible: Works with all GraphQL clients (Apollo, Relay…) and fits seamless in your GraphQL workflow.graphql-yoga is based on the following libraries & tools:

FeaturesGraphQL spec-compliantFile uploadGraphQL SubscriptionsTypeScript typingsGraphQL PlaygroundExtensible via Express middlewareSchema directivesApollo TracingAccepts both application/json and application/graphql content-typesRuns everywhere: Can be deployed via now, up, AWS Lambda, Heroku etc.Supports middleware out of the box.

Install

Usage

Quickstart (Hosted demo)

import { GraphQLServer } from “graphql-yoga”https:// … 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.

APIGraphQLServerconstructor(props: Props): GraphQLServerThe props argument accepts the following fields:

KeyTypeDefaultNote
typeDefsString or Function or DocumentNode or array of previousnullContains GraphQL type definitions in SDL or file path to type definitions (required if schema is not provided *)
resolversObjectnullContains resolvers for the fields specified in typeDefs (required if schema is not provided *)
resolverValidationOptionsObjectnullObject which controls the resolver validation behaviour (see “Generating a schema”) for more information
schemaObjectnullAn instance of GraphQLSchema (required if typeDefs and resolvers are not provided *)
mocksObject or BooleannullApplies 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.
contextObject 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 **
schemaDirectivesObjectnullApollo Server schema directives that allow for transforming schema types, fields, and arguments
middlewaresarray of MiddlewareA list of GraphQLMiddleware middleware.

(*) There are two major ways of providing the schema information to the constructor:

Provide the schema directly and omit typeDefs and resolvers.

(**) Notice that the req argument is an object of the shape { request, response, connection } which either carries a request: Request property (when it”s a Query/Mutation resolver), response: Response property (when it”s a Query/Mutation resolver), or a connection: SubscriptionOptions property (when it”s a Subscription resolver). Request is imported from Express.js. Response is imported from Express.js aswell. SubscriptionOptions is from the graphql-subscriptions package. SubscriptionOptions are getting the connectionParams automatically injected under SubscriptionOptions.context.

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)): PromiseOnce 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:

KeyTypeDefaultNote
corsObjectnullContains configuration options for cors
tracingBoolean 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”)
portNumber or String4000Determines the port your server will be listening on (note that you can also specify the port by setting the PORT environment variable)
endpointString“/”Defines the HTTP endpoint of your server
subscriptionsObject 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
playgroundString or false“/”Defines the endpoint where you can invoke the Playground; setting to false disables the playground endpoint
defaultPlaygroundQueryStringundefinedDefines default query displayed in Playground.

Xem thêm: Mua Chung Cư Vinhome – Bán Chung Cư Vinhomes Central Park

uploadsUploadOptions or false or undefinednullProvides 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
httpsHttpsOptions or undefinedundefinedEnables HTTPS support with a key/cert
getEndpointString or BooleanfalseAdds a graphql HTTP GET endpoint to your server (defaults to endpoint if true). Used for leveraging CDN level caching.
deduplicatorBooleantrueEnables graphql-deduplicator. Once enabled sending the header X-GraphQL-Deduplicate will deduplicate the data.
bodyParserOptionsBodyParserJSONOptionsBodyParserJSONOptions DefaultsAllows pass through of body-parser options

Additionally, the options object exposes these apollo-server options:

KeyTypeNote
cacheControlBooleanEnable extension that returns Cache Control data in the response
formatErrorNumberA 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
logFunctionLogFunctionA function called for logging events such as execution times
rootValueanyRootValue passed to GraphQL execution
validationRulesArray of functionsAdditional GraphQL validation rules to be applied to client-specified queries
fieldResolverGraphQLFieldResolverSpecify a custom default field resolver function
formatParamsFunctionA function applied to each query in a batch to format parameters before execution
formatResponseFunctionA function applied to each response after execution
debugbooleanPrint 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.`, ),)
PubSubSee the original documentation in graphql-subscriptions.

mockingMocking the schema is straight forward, along wit

import { GraphqlServer, MockList } from “graphql-yoga”const typeDefs = ` type Query { hello(name: String): String! listOfStrings: }`const mocks = { Query: () => ({ hello: () => “Hello World”, listOfStrings: () => new MockList(), }),}const server = new GraphQLServer({ typeDefs, mocks })

Endpoints

Examples

There are three examples demonstrating how to quickly get started with graphql-yoga:

WorkflowOnce 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.)

*

Deployment

now

To deploy your graphql-yoga server with now, follow these instructions:Navigate to the root directory of your graphql-yoga serverRun now in your terminal

HerokuTo deploy your graphql-yoga server with Heroku, follow these instructions:

Log in to the Heroku CLI with heroku loginNavigate to the root directory of your graphql-yoga serverCreate the Heroku instance by executing heroku createDeploy your GraphQL server by executing git push heroku master

up (Coming soon ???? )

AWS Lambda (Coming soon ???? )

FAQ

How does 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.

Can”t I just setup my own GraphQL server using 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.

How to eject from the standard 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.

Xem thêm: Coding Convention Là Gì – Chuẩn Coding Convention Trong Php Với Psr

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.

Help & Community

*

Join our Slack community if you run into issues or have questions. We love talking to you!
Chuyên mục: Hỏi Đáp