From 5577f54577aae039dabde0b919eb9d49088271cc Mon Sep 17 00:00:00 2001 From: Evans Hauser Date: Tue, 22 May 2018 17:14:52 -0700 Subject: [PATCH 1/5] docs: flesh out api documentation for apollo-server --- docs/source/api/apollo-server.md | 84 ++++++++++++++++++++++++-------- 1 file changed, 63 insertions(+), 21 deletions(-) diff --git a/docs/source/api/apollo-server.md b/docs/source/api/apollo-server.md index 09bf15d2..35566d99 100644 --- a/docs/source/api/apollo-server.md +++ b/docs/source/api/apollo-server.md @@ -16,14 +16,47 @@ The core of an Apollo Server implementation. For a complete example, see the [B * `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`> | <`Fucntion`> + + An object or function called with the current request that creates the context shared across all resolvers + + * `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 +68,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 @@ -81,8 +125,6 @@ The `registerServer` method is from `apollo-server-express`. Middleware registra 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. From 20a41163c11b01fac36b388f7682632b8c632565 Mon Sep 17 00:00:00 2001 From: Evans Hauser Date: Tue, 22 May 2018 17:38:41 -0700 Subject: [PATCH 2/5] docs: remove dead links from essentials data and fix context creation --- docs/source/essentials/data.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/docs/source/essentials/data.md b/docs/source/essentials/data.md index 86aadc81..6d857078 100644 --- a/docs/source/essentials/data.md +++ b/docs/source/essentials/data.md @@ -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 From 531162c69358240397c296270ace595a72085d6d Mon Sep 17 00:00:00 2001 From: Evans Hauser Date: Tue, 22 May 2018 17:39:19 -0700 Subject: [PATCH 3/5] docs: fix dead links --- docs/source/features/mocking.md | 2 +- docs/source/features/schema-delegation.md | 4 ++-- docs/source/features/schema-stitching.md | 2 +- docs/source/getting-started.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/source/features/mocking.md b/docs/source/features/mocking.md index d3cd4cf7..ff1c0de2 100644 --- a/docs/source/features/mocking.md +++ b/docs/source/features/mocking.md @@ -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. diff --git a/docs/source/features/schema-delegation.md b/docs/source/features/schema-delegation.md index b59272f6..52377192 100644 --- a/docs/source/features/schema-delegation.md +++ b/docs/source/features/schema-delegation.md @@ -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. diff --git a/docs/source/features/schema-stitching.md b/docs/source/features/schema-stitching.md index f73e09f4..d4cc1867 100644 --- a/docs/source/features/schema-stitching.md +++ b/docs/source/features/schema-stitching.md @@ -232,7 +232,7 @@ const mergedSchema = mergeSchemas({

Using with Transforms

-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. diff --git a/docs/source/getting-started.md b/docs/source/getting-started.md index 185a355c..d52031cd 100644 --- a/docs/source/getting-started.md +++ b/docs/source/getting-started.md @@ -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). From d84061b148e8d8c6143f188ceb6651255e9ccb42 Mon Sep 17 00:00:00 2001 From: Evans Hauser Date: Tue, 22 May 2018 17:39:37 -0700 Subject: [PATCH 4/5] docs: remove old way of adding schema directives --- docs/source/features/creating-directives.md | 42 --------------------- 1 file changed, 42 deletions(-) diff --git a/docs/source/features/creating-directives.md b/docs/source/features/creating-directives.md index 86fec433..b403fec5 100644 --- a/docs/source/features/creating-directives.md +++ b/docs/source/features/creating-directives.md @@ -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, -) { - const schemaDirectives = Object.create(null); - - Object.keys(directiveResolvers).forEach(directiveName => { - schemaDirectives[directiveName] = class extends SchemaDirectiveVisitor { - public visitFieldDefinition(field: GraphQLField) { - 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`. From a1084059c7cb7768b96ef88462b305624ccde5dc Mon Sep 17 00:00:00 2001 From: Evans Hauser Date: Tue, 22 May 2018 17:47:48 -0700 Subject: [PATCH 5/5] docs: add code snippet example to context api reference --- docs/source/api/apollo-server.md | 70 +++++++++++++++++++------------- 1 file changed, 41 insertions(+), 29 deletions(-) diff --git a/docs/source/api/apollo-server.md b/docs/source/api/apollo-server.md index 35566d99..8e8ead79 100644 --- a/docs/source/api/apollo-server.md +++ b/docs/source/api/apollo-server.md @@ -3,60 +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`, and `apollo-server/{variant}` packages (e.g. `apollo-server/express`). Both the root module and the module sub-paths export the same functionality. ## `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)_ String representation of GraphQL schema in the Schema Definition Language (SDL). * `resolvers`: <`Object`> _(required)_ - 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. + 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`> | <`Fucntion`> + * `context`: <`Object`> | <`Function`> An object or function called with the current request that creates the context shared across all resolvers - * `mocks`: <`Object`> | <`Boolean`> +```js +new ApolloServer({ + typeDefs, + resolvers, + context: ({ req }) => ({ + authScope: getScope(req.headers.authorization) + }), +}); +``` - A boolean enabling the default mocks or object that contains definitions +* `mocks`: <`Object`> | <`Boolean`> - * `schemaDirectives`: <`Object`> + A boolean enabling the default mocks or object that contains definitions - Contains definition of schema directives used in the `typeDefs` +* `schemaDirectives`: <`Object`> - * `introspection`: <`Boolean`> + Contains definition of schema directives used in the `typeDefs` - Enables and disables schema introspection +* `introspection`: <`Boolean`> - * `debug`: <`Boolean`> + Enables and disables schema introspection - Enables and disables development mode helpers. Defaults to `true` +* `debug`: <`Boolean`> - * `validationRules`: <`Object`> + Enables and disables development mode helpers. Defaults to `true` - Schema validation rules +* `validationRules`: <`Object`> - * `tracing`, `cacheControl`: <`Boolean`> + Schema validation rules - Add tracing or cacheControl meta data to the GraphQL response +* `tracing`, `cacheControl`: <`Boolean`> - * `formatError`, `formatResponse`, `formatParams`: <`Function`> + Add tracing or cacheControl meta data to the GraphQL response - Functions to format the errors and response returned from the server, as well as the parameters to graphql execution(`runQuery`) +* `formatError`, `formatResponse`, `formatParams`: <`Function`> - * `schema`: <`Object`> + Functions to format the errors and response returned from the server, as well as the parameters to graphql execution(`runQuery`) - An executable GraphQL schema that will override the `typeDefs` and `resolvers` provided +* `schema`: <`Object`> + + An executable GraphQL schema that will override the `typeDefs` and `resolvers` provided #### Returns @@ -109,27 +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 @@ -139,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` @@ -162,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 @@ -177,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. @@ -199,7 +212,6 @@ If preserveResolvers is set to true, existing resolve functions will not be over ### Usage - ```js const { addMockFunctionsToSchema } = require('apollo-server');