mirror of
https://github.com/vale981/apollo-server
synced 2025-03-05 17:51:40 -05:00
Merge branch 'version-2' into refactor-2.0
This commit is contained in:
parent
1a305eb5a8
commit
db3316cbac
11 changed files with 284 additions and 110 deletions
|
@ -14,7 +14,7 @@
|
|||
"hexo-renderer-less": "0.2.0",
|
||||
"hexo-renderer-marked": "0.3.2",
|
||||
"hexo-server": "0.3.2",
|
||||
"meteor-theme-hexo": "1.0.9"
|
||||
"meteor-theme-hexo": "1.0.13"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "npm run build && chexo apollo-hexo-config -- server",
|
||||
|
|
|
@ -3,27 +3,71 @@ title: "API Reference: apollo-server"
|
|||
sidebar_title: apollo-server
|
||||
---
|
||||
|
||||
This API reference documents the exports from the `apollo-server`, and `apollo-server/{variant}` packages (e.g. `apollo-server/express`). Both the root module and the module sub-paths export the same functionality.
|
||||
This API reference documents the exports from the `apollo-server`.
|
||||
|
||||
## `ApolloServer`
|
||||
|
||||
The core of an Apollo Server implementation. For a complete example, see the [Building a server](../essentials/server.html) section within "Essentials".
|
||||
The core of an Apollo Server implementation. For an example, see the [Building a server](../essentials/server.html) section within "Essentials".
|
||||
|
||||
### `constructor(options)`: <`ApolloServer`>
|
||||
|
||||
#### Parameters
|
||||
|
||||
* `options`: <`Object`>
|
||||
|
||||
* `typeDefs`: <`String` inside [`gql`](#gql) tag> _(required)_
|
||||
|
||||
This is a string representation of your GraphQL Schema Definition Language (SDL).
|
||||
|
||||
String representation of GraphQL schema in the Schema Definition Language (SDL).
|
||||
|
||||
* `resolvers`: <`Object`> _(required)_
|
||||
|
||||
Type: `Object`
|
||||
A map of resolvers for the types defined in `typeDefs`. The key should be the type name and the value should be a `Function` to be executed for that type.
|
||||
|
||||
This should be a map of resolvers for the types defined in `typeDefs`. The key should be the type name and the value should be a `Function` to be executed for that type.
|
||||
* `context`: <`Object`> | <`Function`>
|
||||
|
||||
An object or function called with the current request that creates the context shared across all resolvers
|
||||
|
||||
```js
|
||||
new ApolloServer({
|
||||
typeDefs,
|
||||
resolvers,
|
||||
context: ({ req }) => ({
|
||||
authScope: getScope(req.headers.authorization)
|
||||
}),
|
||||
});
|
||||
```
|
||||
|
||||
* `mocks`: <`Object`> | <`Boolean`>
|
||||
|
||||
A boolean enabling the default mocks or object that contains definitions
|
||||
|
||||
* `schemaDirectives`: <`Object`>
|
||||
|
||||
Contains definition of schema directives used in the `typeDefs`
|
||||
|
||||
* `introspection`: <`Boolean`>
|
||||
|
||||
Enables and disables schema introspection
|
||||
|
||||
* `debug`: <`Boolean`>
|
||||
|
||||
Enables and disables development mode helpers. Defaults to `true`
|
||||
|
||||
* `validationRules`: <`Object`>
|
||||
|
||||
Schema validation rules
|
||||
|
||||
* `tracing`, `cacheControl`: <`Boolean`>
|
||||
|
||||
Add tracing or cacheControl meta data to the GraphQL response
|
||||
|
||||
* `formatError`, `formatResponse`, `formatParams`: <`Function`>
|
||||
|
||||
Functions to format the errors and response returned from the server, as well as the parameters to graphql execution(`runQuery`)
|
||||
|
||||
* `schema`: <`Object`>
|
||||
|
||||
An executable GraphQL schema that will override the `typeDefs` and `resolvers` provided
|
||||
|
||||
#### Returns
|
||||
|
||||
|
@ -35,24 +79,35 @@ The core of an Apollo Server implementation. For a complete example, see the [B
|
|||
|
||||
* `options`: <`Object`>
|
||||
|
||||
Most parameters which are supported by Node.js' [`net.Server.listen`](https://nodejs.org/api/net.html#net_server_listen_options_callback) method are supported, including:
|
||||
* `http`: <`Object`>
|
||||
|
||||
* `port`: <`String`> | <`Number`>
|
||||
* `path`: <`String`>
|
||||
* `backlog`: <`Number`>
|
||||
* `exclusive`: <`Boolean`>
|
||||
All parameters which are supported by Node.js' [`net.Server.listen`](https://nodejs.org/api/net.html#net_server_listen_options_callback) method are supported, including:
|
||||
|
||||
// Engine launcher options
|
||||
`engineLauncherOptions?: EngineLauncherOptions;`
|
||||
* `port`: <`String`> | <`Number`>
|
||||
* `path`: <`String`>
|
||||
* `backlog`: <`Number`>
|
||||
* `exclusive`: <`Boolean`>
|
||||
|
||||
// WebSocket options
|
||||
`keepAlive?: number;`
|
||||
`onConnect?: (
|
||||
connectionParams: Object,
|
||||
websocket: WebSocket,
|
||||
context: ConnectionContext,
|
||||
) => any;
|
||||
onDisconnect?: (websocket: WebSocket, context: ConnectionContext) => any;`
|
||||
or
|
||||
|
||||
* `handler`: <`Object`>
|
||||
* `backlog`: <`Number`>
|
||||
|
||||
Engine launcher options
|
||||
|
||||
* `engineLauncherOptions` : [<`Object`>](https://www.apollographql.com/docs/engine/setup-node.html#api-engine.listen)
|
||||
* `engineProxy`: [<`Object`>](https://www.apollographql.com/docs/engine/proxy-config.html)
|
||||
|
||||
WebSocket options
|
||||
|
||||
* `subscriptions`: <`Object`> | <`String`> | false
|
||||
|
||||
String defining the path for subscriptions or an Object to customize the subscriptions server. Set to false to disable subscriptions
|
||||
|
||||
* `path`: <`String`>
|
||||
* `keepAlive`: <`Number`>
|
||||
* `onConnect`: <`Function`>
|
||||
* `onDisconnect`: <`Function`>
|
||||
|
||||
#### Returns
|
||||
|
||||
|
@ -65,29 +120,28 @@ The `registerServer` method is from `apollo-server-express`. Middleware registra
|
|||
### Parameters
|
||||
|
||||
* `options`: <`Object`>
|
||||
|
||||
* `app`: <`HttpServer`> _(required)_
|
||||
|
||||
Pass the handle to your nexpress server here.
|
||||
Pass the handle to your nexpress server here.
|
||||
|
||||
* `server`: <`ApolloServer`> _(required)_
|
||||
|
||||
Pass the instance of Apollo Server
|
||||
Pass the instance of Apollo Server
|
||||
|
||||
* `path` : <`String`>
|
||||
|
||||
Specify a custom path. It defaults to `/graphql` if no path is specified.
|
||||
Specify a custom path. It defaults to `/graphql` if no path is specified.
|
||||
|
||||
* `cors`: <`Object`>
|
||||
|
||||
Pass the cors options.
|
||||
|
||||
|
||||
Pass the cors options.
|
||||
|
||||
## `gql`
|
||||
|
||||
The `gql` is a [template literal tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates). Template literals were introduced in recent versions of ECMAScript to provide embedded expressions (i.e. `` `A string with interpolated ${variables}` ``) and template literal tags exist to provide additional functionality for what would otherwise be a normal template literal.
|
||||
The `gql` is a [template literal tag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates). Template literals were introduced in recent versions of ECMAScript to provide embedded expressions (i.e. `` `A string with interpolated ${variables}` ``) and template literal tags exist to provide additional functionality for what would otherwise be a normal template literal.
|
||||
|
||||
In the case of GraphQL, the `gql` tag is used to surround GraphQL operation and schema language (which are represented as `String`s), and makes it easier to differentiate from ordinary strings. This is particularly useful when performing static analysis on GraphQL language (e.g. to enable syntax highlighting, code generation, etc.) and avoids need for tools to "guess" if a string contains GraphQL language.
|
||||
In the case of GraphQL, the `gql` tag is used to surround GraphQL operation and schema language (which are represented as `String`s), and makes it easier to differentiate from ordinary strings. This is particularly useful when performing static analysis on GraphQL language (e.g. to enable syntax highlighting, code generation, etc.) and avoids need for tools to "guess" if a string contains GraphQL language.
|
||||
|
||||
### Usage
|
||||
|
||||
|
@ -97,7 +151,7 @@ Import the `gql` template literal tag into the current context from the `apollo-
|
|||
const { gql } = require('apollo-server');
|
||||
```
|
||||
|
||||
Then, place GraphQL schema definitions (SDL), queries or other operations into the `gql` template literal tag. Keep in mind that template literals use the grave accent (`` ` ``) and not normal quotation marks (e.g. not `"` or `'`):
|
||||
Then, place GraphQL schema definitions (SDL), queries or other operations into the `gql` template literal tag. Keep in mind that template literals use the grave accent (`` ` ``) and not normal quotation marks (e.g. not `"` or `'`):
|
||||
|
||||
```js
|
||||
const typeDefs = gql`
|
||||
|
@ -120,7 +174,7 @@ The `makeExecutableSchema` method is re-exported from apollo-server as a conveni
|
|||
* `allowUndefinedInResolve` = false
|
||||
* `resolverValidationOptions` = {}
|
||||
* `directiveResolvers` = null
|
||||
* `schemaDirectives` = null
|
||||
* `schemaDirectives` = null
|
||||
* `parseOptions` = {}
|
||||
* `inheritResolversFromInterfaces` = false
|
||||
|
||||
|
@ -135,6 +189,7 @@ If preserveResolvers is set to true, existing resolve functions will not be over
|
|||
### Parameters
|
||||
|
||||
* `options`: <`Object`>
|
||||
|
||||
* `schema`: <`GraphQLSchema`> _(required)_
|
||||
|
||||
Pass an executable schema (`GraphQLSchema`) to be mocked.
|
||||
|
@ -157,7 +212,6 @@ If preserveResolvers is set to true, existing resolve functions will not be over
|
|||
|
||||
### Usage
|
||||
|
||||
|
||||
```js
|
||||
const { addMockFunctionsToSchema } = require('apollo-server');
|
||||
|
||||
|
|
|
@ -95,21 +95,19 @@ Every resolver function is called according to the nesting of the query. To unde
|
|||
|
||||
The context is how you access your shared connections and fetchers in resolvers to get data.
|
||||
|
||||
The `context` is the third argument passed to every resolver. It is useful for passing things that any resolver may need, like [authentication scope](), database connections([mongo](), [postgres](), etc), and custom fetch functions. Additionally, if you're using [dataloaders to batch requests](../best-practices/performance.html#Batching-data-lookups) across resolvers, you can attach them to the `context` as well.
|
||||
The `context` is the third argument passed to every resolver. It is useful for passing things that any resolver may need, like [authentication scope](https://dev-blog.apollodata.com/authorization-in-graphql-452b1c402a9), database connections, and custom fetch functions. Additionally, if you're using [dataloaders to batch requests](../best-practices/performance.html#Batching-data-lookups) across resolvers, you can attach them to the `context` as well.
|
||||
|
||||
As a best practice, `context` should be the same for all resolvers, no matter the particular query or mutation, and resolvers should never modify it. This ensures consistency across resolvers, and helps increase development velocity.
|
||||
|
||||
To provide a `context` to your resolvers, add a `context` object to the Apollo Server constructor. This constructor gets called with every request, so you can set the context based off the details of the request (like HTTP headers).
|
||||
|
||||
For specific examples, follow the [backend]() instructions.
|
||||
|
||||
```
|
||||
const server = new ApolloServer(req => ({
|
||||
const server = new ApolloServer({
|
||||
typeDefs,
|
||||
resolvers,
|
||||
context: {
|
||||
context: ({ req }) => ({
|
||||
authScope: getScope(req.headers.authorization)
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
// resolver
|
||||
|
|
|
@ -614,45 +614,3 @@ As its name suggests, the `SchemaDirectiveVisitor` abstraction is specifically d
|
|||
While directive syntax can also appear in GraphQL queries sent from the client, implementing query directives would require runtime transformation of query documents. We have deliberately restricted this implementation to transformations that take place when you call the `makeExecutableSchema` function—that is, at schema construction time.
|
||||
|
||||
We believe confining this logic to your schema is more sustainable than burdening your clients with it, though you can probably imagine a similar sort of abstraction for implementing query directives. If that possibility becomes a desire that becomes a need for you, let us know, and we may consider supporting query directives in a future version of these tools.
|
||||
|
||||
## What about `directiveResolvers`?
|
||||
|
||||
Before `SchemaDirectiveVisitor` was implemented, the `makeExecutableSchema` function took a `directiveResolvers` option that could be used for implementing certain kinds of `@directive`s on fields that have resolver functions.
|
||||
|
||||
The new abstraction is more general, since it can visit any kind of schema syntax, and do much more than just wrap resolver functions. However, the old `directiveResolvers` API has been [left in place](directive-resolvers.html) for backwards compatibility, though it is now implemented in terms of `SchemaDirectiveVisitor`:
|
||||
|
||||
```typescript
|
||||
function attachDirectiveResolvers(
|
||||
schema: GraphQLSchema,
|
||||
directiveResolvers: IDirectiveResolvers<any, any>,
|
||||
) {
|
||||
const schemaDirectives = Object.create(null);
|
||||
|
||||
Object.keys(directiveResolvers).forEach(directiveName => {
|
||||
schemaDirectives[directiveName] = class extends SchemaDirectiveVisitor {
|
||||
public visitFieldDefinition(field: GraphQLField<any, any>) {
|
||||
const resolver = directiveResolvers[directiveName];
|
||||
const originalResolver = field.resolve || defaultFieldResolver;
|
||||
const directiveArgs = this.args;
|
||||
field.resolve = (...args: any[]) => {
|
||||
const [source, /* original args */, context, info] = args;
|
||||
return resolver(
|
||||
async () => originalResolver.apply(field, args),
|
||||
source,
|
||||
directiveArgs,
|
||||
context,
|
||||
info,
|
||||
);
|
||||
};
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
SchemaDirectiveVisitor.visitSchemaDirectives(
|
||||
schema,
|
||||
schemaDirectives,
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Existing code that uses `directiveResolvers` should probably consider migrating to `SchemaDirectiveVisitor` if feasible, though we have no immediate plans to deprecate `directiveResolvers`.
|
||||
|
|
|
@ -170,4 +170,4 @@ server.listen().then(({ url }) => {
|
|||
|
||||
## API
|
||||
|
||||
Under the hood, Apollo Sever uses a library for building GraphQL servers, called `graphql-tools`. The mocking functionality is provided by the function [`addMockFunctionsToSchema`](../api/graphql-tools#addMockFunctionsToSchema). The `mocks` object is passed directly to the function and `preserveResolvers` is always true. [`MockList`](../api/graphql-tools#MockList) is exported directly from the `graphql-tools` library.
|
||||
Under the hood, Apollo Sever uses a library for building GraphQL servers, called `graphql-tools`. The mocking functionality is provided by the function [`addMockFunctionsToSchema`](../api/graphql-tools.html#addMockFunctionsToSchema). The `mocks` object is passed directly to the function and `preserveResolvers` is always true. [`MockList`](../api/graphql-tools.html#MockList) is exported directly from the `graphql-tools` library.
|
||||
|
|
|
@ -9,7 +9,7 @@ The `graphql-tools` package provides several related tools for managing schema d
|
|||
|
||||
* [Remote schemas](./remote-schemas.html) - turning a remote GraphQL endpoint into a local schema
|
||||
* [Schema transforms](./schema-transforms.html) - modifying existing schemas to make delegation easier
|
||||
* [Schema stitching](./schema-stitching) - merging multiple schemas into one
|
||||
* [Schema stitching](./schema-stitching.html) - merging multiple schemas into one
|
||||
|
||||
Delegation is performed by one function, `delegateToSchema`, called from within a resolver function of the parent schema. The `delegateToSchema` function sends the query subtree received by the parent resolver to a subschema that knows how to execute it, then returns the result as if the parent resolver had executed the query.
|
||||
|
||||
|
@ -158,4 +158,4 @@ Delegation preserves aliases that are passed from the parent query. However that
|
|||
|
||||
## API
|
||||
|
||||
Under the hood, Apollo server uses the `graphql-tools` library, which includes [`delegateToSchema`](../api/graphql-tools#delegateToSchema) by default.
|
||||
Under the hood, Apollo server uses the `graphql-tools` library, which includes [`delegateToSchema`](../api/graphql-tools.html#delegateToSchema) by default.
|
||||
|
|
|
@ -232,7 +232,7 @@ const mergedSchema = mergeSchemas({
|
|||
|
||||
<h2 id="using-with-transforms">Using with Transforms</h2>
|
||||
|
||||
Often, when creating a GraphQL gateway that combines multiple existing schemas, we might want to modify one of the schemas. The most common tasks include renaming some of the types, and filtering the root fields. By using [transforms](./schema-transforms) with schema stitching, we can easily tweak the subschemas before merging them together.
|
||||
Often, when creating a GraphQL gateway that combines multiple existing schemas, we might want to modify one of the schemas. The most common tasks include renaming some of the types, and filtering the root fields. By using [transforms](./schema-transforms.html) with schema stitching, we can easily tweak the subschemas before merging them together.
|
||||
|
||||
Before, when we were simply merging schemas without first transforming them, we would typically delegate directly to one of the merged schemas. Once we add transforms to the mix, there are times when we want to delegate to fields of the new, transformed schemas, and other times when we want to delegate to the original, untransformed schemas.
|
||||
|
||||
|
|
|
@ -30,7 +30,7 @@ In this step, we'll use your terminal (e.g. Terminal, iTerm, PowerShell) to crea
|
|||
|
||||
npm init --yes
|
||||
|
||||
> We use `npm`, the default package manager which ships with Node.js. Other package managers, such as [Yarn](//yarnpkg.com), offer similar functionality, but will not be covered in this guide.
|
||||
> We use `npm`, the default package manager which ships with Node.js. Other package managers, such as [Yarn](http://yarnpkg.com), offer similar functionality, but will not be covered in this guide.
|
||||
|
||||
If the above steps all completed successfully, there should be a new `package.json` file in the directory. You can verify this by running `ls` (list files).
|
||||
|
||||
|
|
|
@ -7,7 +7,7 @@ The Apollo Server 2.0 beta dramatically simplifies the API for building a GraphQ
|
|||
|
||||
While it's possible to migrate an existing server to the 2.0 beta without any changes, we recommend changing to new patterns we're suggesting in order to take advantage of all the latest Apollo Server features, reduce the boilerplate, and enable future flexibility. To learn how to migrate to the 2.0 beta from version 1.0, please read the following guide.
|
||||
|
||||
> **Note:** In the beta of Apollo Server 2.0 only Express is supported. Additional middleware variants will be implemented in the official 2.0 release.
|
||||
> **Note:** In the beta of Apollo Server 2.0 only Express and Hapi are supported. Additional middleware integrations will be implemented in the official 2.0 release.
|
||||
|
||||
### Recommending the `gql` tag
|
||||
|
||||
|
@ -127,7 +127,7 @@ server.listen().then(({ url }) => {
|
|||
|
||||
If you are simply focused on running a production-ready GraphQL server quickly, Apollo Server 2.0 ships with a built-in server and starting your own server (e.g. Express, Koa, etc.) is no longer necessary.
|
||||
|
||||
For these cases, it's possible to remove the existing `apollo-server-{variant}` package and add the new `apollo-server` beta. If using Express, this can be done by running:
|
||||
For these cases, it's possible to remove the existing `apollo-server-{integrations}` package and add the new `apollo-server` beta. If using Express, this can be done by running:
|
||||
|
||||
npm uninstall --save apollo-server-express
|
||||
|
||||
|
|
|
@ -2,11 +2,13 @@
|
|||
title: What's new?
|
||||
---
|
||||
|
||||
This section of the ApolloServer docs is an announcement page where it is easy to find and share big changes to the ApolloServer package, or the Apollo server side ecosystem. For a more detailed list of changes, check out the [Changelog](https://github.com/apollographql/apollo-server/blob/version-2/CHANGELOG.md).
|
||||
This section of the Apollo Server docs is an announcement page where it is easy to find and share big changes to the ApolloServer package, or the Apollo server side ecosystem. For a more detailed list of changes, check out the [Changelog](https://github.com/apollographql/apollo-server/blob/version-2/CHANGELOG.md).
|
||||
|
||||
## 2.0
|
||||
|
||||
ApolloServer 2.0 is a new effort targeted in making the most powerful and production ready GraphQL app easier than ever to build. Instead of providing all of the tools to figure out how to make a great GraphQL backend, the 2.0 brings everything together that we think you should be doing when building a GraphQL app. It is an opinionated, production focused, GraphQL server that works with any backend.
|
||||
Apollo Server 2.0 makes building the most powerful and production ready GraphQL app easy. Apollo Server 1.x provided all of the tools necessary to make a great GraphQL backend, allowing the developer to pick and choose from a set of unopinionated tools. Building on 1.x and fully backwards compatible, 2.0's defaults bake in the best practices and patterns gathered from two years of community feedback and iteration. It is an opinionated, production focused, GraphQL server that works with any backend.
|
||||
|
||||
The following code snippet demonstrates the creation of Apollo Server 2.0 and a few of the new features.
|
||||
|
||||
```js
|
||||
const { ApolloServer, gql } = require('apollo-server');
|
||||
|
@ -32,9 +34,13 @@ const server = new ApolloServer({
|
|||
mocks: true,
|
||||
onHealthCheck: () => fetch('https://fourtonfish.com/hellosalut/?mode=auto'),
|
||||
});
|
||||
|
||||
server.listen().then(({ url }) => {
|
||||
console.log(`🚀 Server ready at ${url}`)
|
||||
});
|
||||
```
|
||||
|
||||
This is just the beginning. We have published a [roadmap](https://github.com/apollographql/apollo-server/blob/master/ROADMAP.md) for all of the features we will be bringing to ApolloServer soon and we would love your help! If you have any interest, you can get involved on [Github](https://github.com/apollographql/apollo-server) or by joining the [Apollo Slack](https://www.apollographql.com/slack) and going to the #apollo-server channel.
|
||||
This is just the beginning. We have published a [roadmap](https://github.com/apollographql/apollo-server/blob/master/ROADMAP.md) for all of the features we will be bringing to Apollo Server soon and we would love your help! If you have any interest, you can get involved on [Github](https://github.com/apollographql/apollo-server) or by joining the [Apollo Slack](https://www.apollographql.com/slack) and going to the #apollo-server channel.
|
||||
|
||||
## [Errors](./features/errors.html)
|
||||
|
||||
|
@ -134,3 +140,136 @@ server.listen().then(({ url }) => {
|
|||
});
|
||||
```
|
||||
|
||||
## GraphQL Playground
|
||||
|
||||
Apollo Server 2.0 creates a single GraphQL endpoint that provides data and a gui explorer depending on how the endpoint is accessed. In browser, Apollo Server returns GraphQL playground. For other cases, Apollo server returns the data for a GraphQL requests from other clients, such as Apollo Client, curl, Postman, or Insomnia.
|
||||
|
||||
```js
|
||||
const { ApolloServer, gql } = require('apollo-server');
|
||||
|
||||
const typeDefs = gql`
|
||||
type Query {
|
||||
hello: String
|
||||
}
|
||||
`;
|
||||
|
||||
const resolvers = {
|
||||
Query: {
|
||||
hello: () => 'hello'
|
||||
}
|
||||
};
|
||||
|
||||
const server = new ApolloServer({
|
||||
typeDefs,
|
||||
resolvers,
|
||||
});
|
||||
|
||||
server.listen().then(({ url }) => {
|
||||
console.log(`🚀 Server ready at ${url}`)
|
||||
});
|
||||
```
|
||||
|
||||
To start production mode, set the NODE_ENV environment variables to `production`. The Apollo Server constructor accepts `introspection` as a boolean, which can overwrite the default for the environment.
|
||||
|
||||
## File Uploads
|
||||
|
||||
For server integrations that support file uploads(express, hapi, koa, etc), Apollo Server enables file uploads by default. To enable file uploads, reference the `Upload` type in the schema passed to the Apollo Server construction.
|
||||
|
||||
```js
|
||||
const { ApolloServer, gql } = require('apollo-server');
|
||||
|
||||
const typeDefs = gql`
|
||||
type File {
|
||||
filename: String!
|
||||
mimetype: String!
|
||||
encoding: String!
|
||||
}
|
||||
|
||||
type Query {
|
||||
uploads: [File]
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
singleUpload(file: Upload!): File!
|
||||
}
|
||||
`;
|
||||
|
||||
const resolvers = {
|
||||
Query: {
|
||||
uploads: (parent, args) => {},
|
||||
},
|
||||
Mutation: {
|
||||
singleUpload: (parent, args) => {
|
||||
|
||||
return args.file.then(file => {
|
||||
//Contents of Upload scalar: https://github.com/jaydenseric/apollo-upload-server#upload-scalar
|
||||
//file.stream is a node stream that contains the contents of the uploaded file
|
||||
//node stream api: https://nodejs.org/api/stream.html
|
||||
return file;
|
||||
})
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const server = new ApolloServer({
|
||||
typeDefs,
|
||||
resolvers,
|
||||
});
|
||||
|
||||
server.listen().then(({ url }) => {
|
||||
console.log(`🚀 Server ready at ${url}`);
|
||||
});
|
||||
```
|
||||
|
||||
> Note: Apollo Server adds the Upload scalar to the schema, so any existing declaration of `scalar Upload` in the schema should be removed
|
||||
|
||||
## [Subscriptions](/docs/graphql-subscriptions/)
|
||||
|
||||
Subscriptions are enabled by default in integrations that support persistent connections.
|
||||
|
||||
```js
|
||||
const { ApolloServer, gql, PubSub } = require('apollo-server');
|
||||
|
||||
const pubsub = new PubSub();
|
||||
const SOMETHING_CHANGED_TOPIC = 'something_changed';
|
||||
|
||||
const typeDefs = `
|
||||
type Query {
|
||||
hello: String
|
||||
}
|
||||
type Subscription {
|
||||
newMessage: String
|
||||
}
|
||||
`;
|
||||
|
||||
const resolvers = {
|
||||
Query: {
|
||||
hello: () => 'hello',
|
||||
},
|
||||
Subscription: {
|
||||
newMessage: {
|
||||
subscribe: () => pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const server = new ApolloServer({
|
||||
typeDefs,
|
||||
resolvers,
|
||||
});
|
||||
|
||||
server.listen().then(({ url }) => {
|
||||
console.log(`🚀 Server ready at ${url}`);
|
||||
});
|
||||
|
||||
//publish events every second
|
||||
setInterval(
|
||||
() =>
|
||||
pubsub.publish(SOMETHING_CHANGED_TOPIC, {
|
||||
newMessage: new Date().toString(),
|
||||
}),
|
||||
1000,
|
||||
);
|
||||
```
|
||||
|
||||
> Note: to disable subscriptions, set `subscriptions` to `false` in the options passed to `listen`
|
||||
|
|
|
@ -8,44 +8,69 @@ description: Setting up Apollo Server with Express.js or Connect
|
|||
This is the Express and Connect integration of GraphQL Server. Apollo Server is a community-maintained open-source GraphQL server that works with all Node.js HTTP server frameworks: Express, Connect, Hapi, Koa and Restify. [Read the docs](https://www.apollographql.com/docs/apollo-server/). [Read the CHANGELOG.](https://github.com/apollographql/apollo-server/blob/master/CHANGELOG.md)
|
||||
|
||||
```sh
|
||||
npm install apollo-server-express
|
||||
npm install apollo-server@beta apollo-server-express@beta
|
||||
```
|
||||
|
||||
## Express
|
||||
|
||||
```js
|
||||
import express from 'express';
|
||||
import bodyParser from 'body-parser';
|
||||
import { graphqlExpress } from 'apollo-server-express';
|
||||
const express = require('express');
|
||||
const { registerServer } = require('apollo-server-express');
|
||||
const { ApolloServer, gql } = require('apollo-server');
|
||||
|
||||
const myGraphQLSchema = // ... define or import your schema here!
|
||||
const PORT = 3000;
|
||||
// Construct a schema, using GraphQL schema language
|
||||
const typeDefs = gql`
|
||||
type Query {
|
||||
hello: String
|
||||
}
|
||||
`;
|
||||
|
||||
// Provide resolver functions for your schema fields
|
||||
const resolvers = {
|
||||
Query: {
|
||||
hello: () => 'Hello world!',
|
||||
},
|
||||
};
|
||||
|
||||
const server = new ApolloServer({ typeDefs, resolvers });
|
||||
|
||||
const app = express();
|
||||
registerServer({ server, app });
|
||||
|
||||
// bodyParser is needed just for POST.
|
||||
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: myGraphQLSchema }));
|
||||
|
||||
app.listen(PORT);
|
||||
server.listen().then(({ url }) => {
|
||||
console.log(`🚀 Server ready at ${url}`);
|
||||
});
|
||||
```
|
||||
|
||||
## Connect
|
||||
|
||||
```js
|
||||
import connect from 'connect';
|
||||
import bodyParser from 'body-parser';
|
||||
import { graphqlConnect } from 'apollo-server-express';
|
||||
import http from 'http';
|
||||
const { registerServer } = require('apollo-server-express');
|
||||
const { ApolloServer, gql } = require('apollo-server');
|
||||
|
||||
const PORT = 3000;
|
||||
// Construct a schema, using GraphQL schema language
|
||||
const typeDefs = gql`
|
||||
type Query {
|
||||
hello: String
|
||||
}
|
||||
`;
|
||||
|
||||
// Provide resolver functions for your schema fields
|
||||
const resolvers = {
|
||||
Query: {
|
||||
hello: () => 'Hello world!',
|
||||
},
|
||||
};
|
||||
|
||||
const server = new ApolloServer({ typeDefs, resolvers });
|
||||
|
||||
const app = connect();
|
||||
registerServer({ server, app });
|
||||
|
||||
// bodyParser is needed just for POST.
|
||||
app.use('/graphql', bodyParser.json());
|
||||
app.use('/graphql', graphqlConnect({ schema: myGraphQLSchema }));
|
||||
|
||||
http.createServer(app).listen(PORT);
|
||||
server.listen().then(({ url }) => {
|
||||
console.log(`🚀 Server ready at ${url}`);
|
||||
});
|
||||
```
|
||||
|
||||
## Principles
|
||||
|
|
Loading…
Add table
Reference in a new issue