👾 Update docs with content from Glitch.

This commit is contained in:
Jesse Rosenberger 2018-04-19 14:17:39 +03:00
parent 582c3cdb99
commit 8d5a37f1f0
No known key found for this signature in database
GPG key ID: C0CCCF81AA6C08D8
36 changed files with 611 additions and 89 deletions

View file

@ -15,10 +15,11 @@ sidebar_categories:
- essentials/queries
- essentials/mutations
Schema Development:
- schemas/organization
- schemas/types
- schemas/directives
- schemas/resolvers
- schemas/context
- schemas/organizing-code
Running a Server:
- server/index
- server/middleware
@ -27,9 +28,11 @@ sidebar_categories:
- server/secrets
Best Practices:
- best-practices/authentication
- best-practices/permissions
- best-practices/schema-design
- best-practices/subscriptions
- best-practices/performance
- best-practices/security
- best-practices/caching
- best-practices/monitoring
- best-practices/versioning
@ -42,6 +45,8 @@ sidebar_categories:
- backends/mongodb
- backends/rest
- backends/prisma
Advanced:
- advanced/query-mechanics
API Reference:
- api/apollo-server
- api/graphql-subscriptions

View file

@ -0,0 +1,18 @@
---
title: Query mechanics
---
## How Query is turned into result?
https://dev-blog.apollodata.com/graphql-explained-5844742f195e
* Query execution
* Parse
* Validate
* Execute
## Introspection Query
The introscpection query is a special type of query defined by the GraphQL specification that enables users to request infromation about the schema on a particular GraphQL server. With no additional effort, Apollo Server supports all introspection. Many developers are concerned with ensuring that the shape of their GraphQL data is not leaked. To understand how to ensure that data access is properly ensure, read over the [section on authentication]().
TODO go here for more info/
http://graphql.org/learn/introspection/

View file

@ -2,3 +2,5 @@
title: Connecting and Fetching
description: How to connect as many data sources as you need to your schema
---
GraphQL is the best way to work with data from **any** backend that your product needs. It is not a mapping of your database, but rather a graph of the data sources and shapes your product is made of. Works with multiple data sources (first party or third)

View file

@ -2,3 +2,6 @@
title: MongoDB
description: Turning your collections and documents into responses
---
* fetching collections
* example project/code

View file

@ -2,3 +2,5 @@
title: Prisma
description: Working with GraphQL as a service tools
---
Maybe we can get Prisma team to help us advise

View file

@ -2,3 +2,7 @@
title: REST
description: Ship new features without waiting on backend changes
---
* graphql + rest is great
* fetching from remote endpoints
* example project/code

View file

@ -2,3 +2,6 @@
title: SQL
description: Working with relational databases and GraphQL
---
* when and how to do joins
* example project/code

View file

@ -1,4 +0,0 @@
---
title: Architecture
description: Two battle tested ways to run your app
---

View file

@ -2,3 +2,11 @@
title: Authentication and Authorization
description: Securing your app and serving your users
---
Intro note about authentication vs authorization and how you don't need to throw everything out
## Autenticating users
## Authorizing mutations
## Should I send a password in a mutation?

View file

@ -2,3 +2,11 @@
title: Caching
description: Caching your operations and your resources
---
Caching is super great, you should be doing it... Add note about distributed vs in memory
### Whole query caching
### CDN
### Resource caching

View file

@ -5,10 +5,6 @@ description: Deploying your new Apollo Server into the world
Deploying your Apollo Server is super easy with a lot of modern tools. Though you may need to customize it to your infrastructure, there are some tools to make it reliable and secure.
<h2 id="aws">AWS</h2>
## TODO
<h2 id="heroku">Heroku</h2>
<h2 id="now">Now</h2>
<h2 id="serverless">Serverless</h2>
> (Jesse) I'm of the belief that these deployment techniques will look much better, index better in our (and Google) search, and generally be more helpful if they are on separate pages. I feel like this page will be just too long otherwise. And likely too hard to digest.

View file

@ -0,0 +1,5 @@
---
title: Infrastructure
---
TODO In short, small horiztonal apps, scaled as needed, setup caching and CDN support

View file

@ -1,4 +1,13 @@
---
title: Monitoring
description: Using Apollo Engine to keep an eye on your app
---
Intro about what to watch for?
## ENGINE
## formatError
## logFunction?
* logFunction should be documented https://github.com/apollographql/apollo-server/blob/master/packages/apollo-server-core/src/runQuery.ts#L64

View file

@ -2,3 +2,11 @@
title: Performance
description: Reduce requests and speed up your app
---
Intro about what is important with GraphQL performance.
## Improving data loading times
## Improving response times
## Scaling your app

View file

@ -3,7 +3,23 @@ title: Schema Design
description: The best way to fetch data, update it, and keep things running for a long time
---
<h2 id="mutations">Mutation design</h2>
<h2 id="unique-ids">Uniqe ids</h2>
<h2 id="node">The node interface</h2>
<h2 id="pagination">Pagination</h2>
GraphQL schemas are at their best when they are designed around the need of the users interaction points, instead of the shape of how the data is stored. Often times teams will create schemas that are literal mappings on top of their collections or tables with CRUD like root fields. While this may be a fast way to get up and running, a strong long term GraphQL schema is built around the products usage.
## Naming
One of the classic problems in computer science, how to name types and fields is a common question for teams getting started with GraphQL. While there is a ton of flexiblity, by design, with the specification, here are a few recommendations that have proven themselves in production applications:
- field names should be camelCase since the majority of consumers will be in client applications written in JavaScript
- type names should be PascalCase
- enums should be PascalCase and their values should be `ALL_CAPS` to denote a special value
Into note about schema's being for products, not for databases
## Node interface
## Mutation Response
## Pagignation
## Field naming / CRUD

View file

@ -0,0 +1,9 @@
---
title: Security
---
## Injection prevention
## rate limiting
## depth/complexity analysis

View file

@ -0,0 +1,13 @@
---
title: Testing
---
Intro section about seperation of concerns making GraphQL ideal for unit testing as well integration testing
> (James) Add API for ApolloServer to make it easy to run integration tests against? Dependency injection anyone?
## Unit testing resolvers
## Integration testing operations
## Using your schema to mock data for client testing

View file

@ -2,3 +2,9 @@
title: Versioning
description: How to add and remove parts of your schema without breaking your clients
---
tl;dr don't. Use a tool like Engine (one day) to help you itterate
## Why versioning isn't needed
## Practical examples of field rollovers

View file

@ -3,10 +3,35 @@ title: Building a schema
description: The why, what, and how of building a schema
---
The schema is the core of your GraphQL service. It validates operations, routes queries to data, powers next generation develoment tools, and is the contract between clients and your service. With Apollo Server, building a schema is as easy ad describing your schema and joining it with some simple functions to return the data.
## Prerequisites
<h2 id="type-definitions">Type Definitions</h2>
* `TODO` Types? (Query = type, so might be better)
<h2 id="resolvers">Resolvers</h2>
## Overview
<h2 id="viewing">Viewing your schema</h2>
Every Apollo Server has a GraphQL schema, which describes the data and actions that are accessible by the client. It contains types, which correspond to tangible items or category, such as an `Author` or a `Book`. To define those types, the schema provides relationships. By defining relationships between entities, a GraphQL schema describes the structure of data without providing the actual data, just like the menu at a cafeteria, which describes the food without the deliciousness.
## Schema Definition Language (SDL)
A GraphQL schema is written in a human-readable Schema Definition Language (or SDL for short) that defines the common language between the client and server. The SDL mirrors JSON and JavaScript's syntax, providing the ability to define membership, such as a `Book` needs a title an `Author` has a name. These memberships can be mutual, since an `Author` writes mutliple `Book`s and a `Book` has one primary author. A schema to describe the previously mentioned releationships could look something like this:
```
type Book {
title: String
author: Author
}
type Author {
books: [Book]
}
```
Take not that the schema is based upon the real world relationships between objects rather than the underlying data store. This real world basis provides the most intuitive interaction for the frontend. In addition, it ensures that the server understands what data will be retreived together and can stay perfomrant.
Wether designing a new application or creating a GraphQL layer over your existing backend, this basis in logical connections is the most important consideration is to define your schema. It is tempting to define a schema based on the current layout of your database, microservices, or REST endpoints. Your GraphQL schema is going to be used across your entire organization and should faciliate the organization of your backend services as well as enable frontend developers to easily discover what data can and should be retreived together.
> Often times mature architectures have been battle tested and optimized for certain views. There is a temptation to translate this data directly into the SDL. This can be an effective migration path provided there is a way to add new GraphQL schema types for new use cases. Often times, since these are newer features with less critical performance garuntees, it is acceptable to retreive a portion of fields for agiven field from the optized backend
## Execution Instructions (resolvers)
In addition to the SDL describing the interface and types, a complete schema includes functions that provide the implementation of how the SDL is executed on the server.

View file

@ -3,8 +3,26 @@ title: Mutations
description: Updating data the Apollo way
---
<h2 id="creating">Creating a mutation</h2>
## Prerequisites
<h2 id="writing">Writing data to a backend</h2>
* A basic understanding of a GraphQL schema ([Schema]())
<h2 id="returning">Returning data from a mutation</h2>
## Overview
Mutations are operations sent to the server to create, update or delete data. Those familiar with REST-based communication verbs would associate these with the `PUT`, `POST`, `PATCH` and `DELETE` methods.
* Mutations are the main entry point to make updates to the data backing Queries
* Here is what one looks like coming from the client
* Here is the corresponding server schema
* A mutation can contain arguments and fields
* Input types are passed to Apollo Server and inform it how to make the updata
* The fields describe the object that is retuned by a mutation, often times the object that was created or the entire collection that was modified. Or a confirmation of deletion
* Here is what the return looks like from the previous mutation call
**Actually writing resolvers for your mutations is found in server/mutations**
## Why mutations exist?
* Mutations exist because they have special argument types called Input types
* Input types only contain scalar types and cannot have any other input types
* ensures that data from the client is always serializable and we don't lose any information, since circular references don't survive network call

View file

@ -3,10 +3,30 @@ title: Queries
description: Turning queries into data
---
Once you have a working schema, you need to load some actual data for your app! Using resolvers you can fetch data from your backend, select and rename the results from your data sources, and link different information together. Learn how flexible GraphQL is in how it can translate requests into data with resolvers.
## Prerequisites
<h2 id="fetching">Fetching data</h2>
* A basic understanding of a GraphQL schema ([Schema]())
<h2 id="shaping">Shaping results</h2>
## Overview
<h2 id="linking">Linking data sources</h2>
A GraphQL query is for reading data. The schema defines the types of queries which are available to the clients connecting to your server.
## Material
* GraphQL query defines the shape of data that will be returned by a particular request
* This is what an author + books query looks like coming from the client
* make sure it has arguments
* This query is then checked agains the server's schema
* looks like this:
* "root" level queries define the main entry points
* Each of those root queries returns a type
**Actually writing resolvers for your queries is found in server/queries**
> TODO: The below headings were left over from the other document. Do we want to remove them?
## Fetching data
## Shaping results
## Linking data sources

View file

@ -1,10 +1,9 @@
---
title: Getting started
---
## Overview
> Estimated time: About 10 minutes.
In this guide, we'll walk you through the process of creating a GraphQL server in JavaScript. By the end of the guide you should expect to:
@ -122,8 +121,8 @@ The example code will utilize a static collection of two books. In a more compl
// This `listen` method launches a web-server. Existing apps
// can utilize middleware options, which we'll discuss later.
server.listen(({ url }) => {
console.log(`Visit ${url}/graphiql to run queries!`);
server.listen().then(({ url }) => {
console.log(`Visit ${url} to run queries!`);
});
```
@ -157,7 +156,7 @@ At this point, you'll be able to start sending queries to the GraphQL server usi
Since we're trying to obtain books...
> WIP / TODO ^
> TODO ^
## Next steps
@ -172,12 +171,3 @@ This application should be a great starting point for any GraphQL server, but th
### GitHub Repository
The code from the above examples can be accessed in our [getting started example repository](.) on GitHub, which also includes instructions on how to get started in its [readme](.).
<!--stackedit_data:
eyJoaXN0b3J5IjpbMTQxMDEwMDk1NiwtMjU0NDk1NjAwLC00MD
E0OTg0ODIsLTY1MTY5NDU5LC02OTM1MTk2NzQsLTE2ODY0NTMx
NzEsLTMwNjE4OTAzNCwxMDQ0ODgzMzQxLDM2NDc5MTY3NCwtNz
A0OTQ1ODQ4LC0xMjI3OTAzMjE5LDE1NDc5MTY3MjAsMTUwMDkx
NDM2OSwxODg3NDYyMjIyLC04ODc3MTkxNTksMTE2OTA0NDU1MS
wxNjE5MDI3NDQyLDE5OTc5NTU4NzEsMTgyMDI4NDk1OCwtMTk1
Mjc0NDExXX0=
-->

View file

@ -15,9 +15,30 @@ Apollo Server supports the entire GraphQL Spec and can be queried from any Graph
These docs will help you go from getting started with Apollo to becoming an expert in no time!
<h2 id="get-started">Getting Started</h2>
## Overview
The docs for Apollo Server are mainly written using the [Express integration](./XXX-link-me), but most of the examples work no matter what server library you use. The docs are broken into six distinct sections to make it easy to find your way around:
This documentation aims to provide a complete guide of how to build a GraphQL server by providing easy-to-understand overviews, in-depth guides and comprehensive best-practices.
The documentation is organized with basic concepts and design decisions first and more advanced topics later on.
* Intro as documentation for how to write a GraphQL server
* what a gql server is
* covers GraphQL concepts in server context, will not explain concepts in depth or the theory behind them/
* why is GraphQL more effective on the server
* Each section will have prereqs to get the most out of it
* After finishing you will know
* what requests a gql server will receive
* Queries
* Mutations
* advanced subscriptions
* how a gql server defines an api and creates reponses to those requests
* best practices for designing server
* auth
* schema design, etc
## Getting Started
The docs for Apollo Server are mainly written using the [Express integration](), but most of the examples work no matter what server library you use. The docs are broken into six distinct sections to make it easy to find your way around:
1. **Essentials**, which oultines everything you know in order to get started quickly
2. **Schema Development**, which goes over just what a GraphQL schema is, and how to write one
@ -28,6 +49,6 @@ The docs for Apollo Server are mainly written using the [Express integration](./
Getting started is as simple as installing a few libraries from [npm](./XXX-link-me)! The [setup](./XXX-link-me) is a good place to start your adventure with Apollo Server!
<h2 id="productive-development">Productive GraphQL API Development</h2>
## Productive GraphQL Development
Apollo Server, and the rest of the Apollo ecosystem, give you a powerful set of tools to rapidly stand up a GraphQL API on top of your exsiting, or new, backends. It does this by focusing on a schema-first approach where you build your schema with a concise, declarative syntax, and fill in the logic with data fetching resolver functions. It is easy to get started with [one-step mocking](./XXX-link-here) while you fill out your data and build your UI. With powerful tools like [schema directives](./XXX-link-here), [tracing and cache control](./XXX-link-here), and [schema stitching](./XXX-link-here), you can build the service of your dreams without writing a line of code more than you need.
Apollo Server, and the rest of the Apollo ecosystem, give you a powerful set of tools to rapidly stand up a GraphQL API on top of your exsiting, or new, backends. It does this by focusing on a schema-first approach where you build your schema with a concise, declarative syntax, and fill in the logic with data fetching resolver functions. It is easy to get started with [one-step mocking]() while you fill out your data and build your UI. With powerful tools like [schema directives](), [tracing and cache control](), and [schema stitching](), you can build the service of your dreams without writing a line of code more than you need.

View file

@ -3,8 +3,63 @@ title: Using Context
description: How to use context to make your app faster, easier to test, and contained
---
<h2 id="creating-context">Creating a context</h2>
> (Evans) With resolvers folded into essentials, I could see this section split between essentials/resolvers and server/secrets or server/connections or backends/general
<h2 id="using-context">Using the context</h2>
## What is?
<h2 id="context-best-practices">Getting the most out of your context</h2>
The `context` is the third positional argument passed to every resolver. `context` references the same object across all resolvers, so no resolver should modify the contents. Additionally, it is best to ensure that the contents of `context` does not change depending on the particular query or mutation.
The common uses of the `context` are storing [authentication scope](), database connections([mongo](), [postgres](), etc), and custom fetch functions. Additionally when batching requests across different resolvers to avoid the n+1 problem, you will attach your instances of [dataloader](best-practice) to the `context`.
> (Evans) not sure if this idea of a constant context is completely true/a best-practice, expecially if making a connection is costly, so you only start the operation if certain fields are requested
### todo: talk about state?
## How to use?
To provide a `context` to your resolvers, add an object to the Apollo Server constructor. For specific examples, follow the [backend/]() instructions.
```
const server = new ApolloServer(req => ({
typeDefs,
resolvers,
context: {
authScope: getScope(req)
}
}));
//resolver
(parent, _, context) => {
if(context.authScope !== ADMIN) throw AuthenticationError('not admin');
...
}
```
The context can also be created asynchronous, allowing database connections and other operations to complete.
```
context: async () => ({
db: await client.connect(),
})
//resolver
(parent, _, context) => {
return context.db.query('SELECT * FROM table_name');
}
```
## Material Summary
* The context is shared by all resolvers during a single query or mutation
* setup the context on every request
* Great place to store authentication (but this will be covered in authentication)
* database connections
* mongo
* postgress
* fetch functions
* N+1 problem
* A consideration for dataloader.
* Here's how you add it to Apollo Server
* State
* BEST practice: keep your context code the same regardless of query/mutation that is coming in

View file

@ -0,0 +1,3 @@
---
title: Directives
---

View file

@ -0,0 +1,19 @@
---
title: Organization
description: Scaling your Apollo Server from a single file to your entire team
---
## Prerequisites
* Understanding of GraphQL types including queries, and mutations
## Overview
The most simply GraphQL schema may only
> (Evans) think this might not be necessary, or could be put in the best-practices section
> (Jesse) Agree++ with the above ^
* First question? Single file or muliple > start with a single file and then break it up into multiple files by real world category when things get too large
* we'll cover how to do this in the [schema stitching section]()
* Place your Queries and mutations next to each other, often at the top or bottom of your schema
* Move your Input types near to Mutations

View file

@ -1,10 +0,0 @@
---
title: Organizing Code
description: Scaling your Apollo Server from a single file to your entire team
---
<h2 id="application-structure">Structuring your application</h2>
<h2 id="splitting-types">Isolating types</h2>
<h2 id="loading-typedefs">Loading type definitions</h2>

View file

@ -3,8 +3,130 @@ title: Resolvers
description: How to fetch data, select fom the results, and join types together
---
<h2 id="args">Arguments</h2>
> (Evans) If we decide that schema/types should be api reference, then this should be in the essentials section.
<h2 id="merging">Merging resolvers</h2>
## Prerequisites
<h2 id="abstractions">Resolver abstractions</h2>
* understand Query and Mutation types
* what query/mutation looks like coming from the client
* selection set? > understand it means the data requested by a client query/mutation
*
## Servicing Requests
Now that we understand the structure of Queries and Mutations, we need to undestand how to service those requests. Queries and mutations define the data they require, so the servicing of the operations uses this structure to organize the servers work. Every field in a GraphQL schema has a corresponding resolver. When a query or mutation requests a field, then the fields resolver is called and the returned value is placed under the field in the server response.
### Basic Resolver
With the following schema, a client could request `query { key }`.
```graphql
type Query {
key: String
}
```
In order to service this request, we would provide the following resolvers, which enable to server to respond with `{ data: { key: 'major' } }`.
```js
resolvers = {
Query: {
key:() => 'major'
}
}
```
### Nested Types and Resolvers
In addition to returning scalar types, such as Strings, Queries can request nested objects with different typese. An example of a nested query would be:
```graphql
query {
parent {
child
}
}
//Start schema
type Parent {
child: String
}
type Query {
parent: Parent
}
```
Followng the previous example, a first implementation of these resolvers might be:
https://launchpad.graphql.com/lk308wpxnq
```js
resolvers = {
Query: {
parent: () => ({})
}
Parent: {
child: () => 'son'
}
}
```
These resolvers can be simplified taking advantage of two features: parameters provided to every resolver and the implicit resolvers implemted by all GraphQL frameworks. The first parameter to each resolver is the result of their parent resolver, following the query's structure. In this case, `child`'s resolver will receive the result of `parent`'s resolver. In addition, when no resolver is provided, the default function returns the field name's value from the parent resolver's result.
```js
resolvers = {
Query: {
parent: () => ({child: 'son'})
}
// Implicitly provided by the framework:
// Parent: {
// child: (parent) => parent.child
// }
}
```
You'll notice how this implementation makes your resolvers more simple. In practice, you should fetch data in parent resolvers when retreival is cheap. For more complicated cases where some fields are more expensive to request, read [this section on performance]() to learn how to optimize your data fetching.
### Resolver Signature
In addition to the parent resolvers value, resolvers receive a couple more arguments. The full resolver function signature contains four positional arguments: `(parent, args, context, info)` and can return an object or [Promise](https://codeburst.io/javascript-learn-promises-f1eaa00c5461). Once a promise resolves, then the childern resolvers will continue executing. This is usefull for fetching data from a [backend]().
The resolver parameters generally follow this naming convention and are described in detail:
1. `parent`: The object that contains the result returned from the resolver on the parent field, or, in the case of a top-level `Query` field, the `rootValue` passed from the [server configuration](/docs/apollo-server/setup.html). This argument enables the nested nature of GraphQL queries.
2. `args`: An object with the arguments passed into the field in the query. For example, if the field was called with `query{ key(arg: "you meant") }`, the `args` object would be: `{ "arg": "you meant" }`.
3. `context`: This is an object shared by all resolvers in a particular query, and is used to contain per-request state, including authentication information, dataloader instances, and anything else that should be taken into account when resolving the query. Read [this section]() for an explaination of when and how to use context.
4. `info`: This argument should only be used in advanced cases, but it contains information about the execution state of the query, including the field name, path to the field from the root, and more. It's only documented in the [GraphQL.js source code](https://github.com/graphql/graphql-js/blob/c82ff68f52722c20f10da69c9e50a030a1f218ae/src/type/definition.js#L489-L500).
In addition to returning GraphQL defined [scalars](), you can return [custom scalars]() for special use cases, such as JSON or big integers.
## Material Summary
* The work to service Queries and Mutations is done by resolvers
* resolvers are functions that return the data requested by a query or mutation
* in the case of a mutation, it will have some side-effects
* resolvers always correspond to a field in type, which can be the Query, Mutation, or a user defined type
* example on root Query with just functions -> no arguments
* resolver on user defined type
* resolver for parent is needed since the default would return null
* this indicates the best practice for resolvers to al
* The resolver function signature is `(parent, args, context, info)`
* parent contains the data returned by parent field's resolver
* client query with parent and child labelled
* default resolver returns parent['field-name']
* for fields of the Query type, parent is null
* args come from the query arguments access them, like so:
* BEST PRACTICE warning: The option to define a resolver for the parent or child resolver is a "solved" question
* use the parent and allow the default resolvers to run for children
* follows the waterfall of resolver execution and does not skip intermediate steps as in the first parent child example
* Mention that resolvers support promises.
* child resolvers will not run until parent is resolved
* Mention that resolvers can also be custom scalar implementations.
* point at advanced/custom-scalars

View file

@ -3,10 +3,89 @@ title: Schema Types
description: How to write your types, expose your data, and keep it all working great
---
<h2 id="root-types">Query, Mutation, and Subscription</h2>
> (Jesse) I am proposing that types should be explained before queries, since a query is a type.
> (Evans) This could possibly be just a reference section, especially if the essentials section gives just enough info for someone to start writing resolvers. Honestly The only type necessary to start is String ;)
<h2 id="object-types">Object types</h2>
## Overview
<h2 id="interfaces">Interfaces</h2>
GraphQL is a strongly typed language and the concept of "types" is a fundamental part of GraphQL. Types define the capabilities of a GraphQL server and allow GraphQL operations to be easily validated.
While in the most basic sence, you could have a GraphQL server return a single, scalar type, combining these types provides the ability to build GraphQL servers of varying complexities.
## Core scalar types
The default, scalar types which GraphQL offers are:
* `Int`
* `Float`
* `String`
* `Boolean`
* `ID` (a special type of `String`)
These primative types
## Object types
The object type is the most common type used in a schema and represents a group of fields. In turn, each field maps to another type, allowing nested types and circular references in a schema design.
```graphql
type Query {
fieldA: String
fieldB: Boolean
fieldC: Int
}
```
## Non-nullable types
By default, each of the core scalar types can also be null. That is to say, they can either return a value of the specified type or they can have no value.
In order to specify that a type _must_ be defined, an exclamation mark (`!`) can be appended to a type to ensure the presence of the value in return results. For example, a `String` which could not be missing a value would be identified as `String!`.
By using the exclamation mark to declare a field as non-nullable, the contract with the client can be simplified since clients will not have to check to see whether a field contains a value or not.
On the other hand, marking fields as non-nullable might make it more difficult to iterate into a schema which makes a field optional, since existing client code would need to be made aware of this new requirement, and adjust their logic accordingly.
## Union type
The `Union` type indicates that a field can return more than one object type, but doesn't define specific fields itself. Therefore, a query being made on a field which is union-typed must specify the object types containing the fields it wants.
## Enum type
The `Enum` type
## `Query` type
The `Query` type is a special object type used to organize other fields.
* special type to define entry points to server to get data
* often called the root query type
* How to add arguments
* backed by a resolver, which is a function that provides the data requested by a query
* essential/queries for info on what queries look like from client/on server
* server/queries for details to implement them
## `Mutation` type
* special type to define operations to change server data
* backed by a resolver that performs the backend modification
* look at essenitals/mutations for mutation shape from client and appearance on server
* server/mutations for implementation information
## `Subscription` type
* special type to define operations that listen to events
* disclaimer that you'll want to setup your server with queries and mutations before adding in subscriptions
* backed by a resolver that calls `subscribe` or something 🤷‍♂️
* look at advanced/subscriptions for mutation shape from client and appearance on server and implementation information
For more information, see the subscription section
## Custom scalar types
The core types provide functionality for most of the common cases an application will have, but it's also possible to define custom types.
For more information, see the advanced section on [custom scalar types]().
<h2 id="enums-and-scalars">Enums and scalars</h2>

View file

@ -2,3 +2,7 @@
title: Apollo Engine
description: Go into production with speed and confidence with Apollo Engine
---
## Overview
Apollo Engine is a GraphQL gateway

View file

@ -1,11 +1,10 @@
---
title: ApolloServer
description: All of the things you need with no config needed!
---
## Overview
Apollo Server provides an easy way for a brand new application to get up and running quickly by providing an integrated web-server with minimal configuration.
> Running a dedicated GraphQL server is a great choice for many deployments, however, if you're looking to add Apollo Server functionality to an **existing webserver**, follow the [Middleware](./middleware.html) installation instructions instead.
@ -31,14 +30,14 @@ To install, run:
### Importing
Start by importing the `ApolloServer` class:
```js
const { ApolloServer } = require('apollo-server');
```
### Import your type definitions
We recommend keeping your type definitions in a separate file. In this example, we'll import them from a file called `schema` which lives alongside the server.
For this example, we'll import type definitions and resolvers from a file called `schema` which lives alongside the main server code.
```js
// Make sure you've created this file and defined type
@ -57,7 +56,7 @@ const server = new ApolloServer({
});
```
> See the [API Reference]() for additional options which can be passed to the `ApolloServer` constructor.
> See the [API Reference]() for additional options which can be passed to the `ApolloServer` constructor and instructions for creating the options based on the incoming request.
### Listening for requests
@ -67,16 +66,13 @@ Finally, when you're ready to start accepting connections, call the `listen` met
server.listen({ port: 3000 });
```
> If the `port` is omitted, port 3000 will be used. The [API reference]() explains additional functionality of the `listen` method.
> If the `port` is omitted, port 4000 will be used. For additional options available on the `listen` method, see the [API reference]().
## Next steps
Once you have a GraphQL server up and running, there are a number of configurable options you might consider. Some great resources for additional information are:
Once you have a GraphQL server up and running, there are a number of configurable options worth considering. Some great resources for additional information are:
* [API documentation]()
* [Schema design]()
* [Schema directives]()
* [Deploying]()
<!--stackedit_data:
eyJoaXN0b3J5IjpbMTA5NjI4MjM1NywxMDQxMzQzNzI0LDM4Nj
k2NTIxOCwtMTUyOTQzODMwNl19
-->
* [Deploying]()

View file

@ -2,3 +2,9 @@
title: Middleware
description: Plugging Apollo into your app in a few lines of code
---
## TODO
* Evans thinks this should go into advanced/as an anti pattern
* best practice dictates that you should have your GraphQL server separate from other services and have a single endpoint
* the advanced section could talk about this in the case that you are doing something special, such as SSR

View file

@ -0,0 +1,3 @@
---
title: Mutations
---

View file

@ -2,3 +2,57 @@
title: Queries
description: How to execute, debug, and connect to your Apollo Server
---
## Prerequisites
* What a query looks like essentials/queries
* Query type schema/types
* How resolvers work schema/resolvers
## Implementing Queries in Apollo Server
> (Evans) this section feels very similar to resolvers
Now that we understand the Query type, GraphQL types, and resolvers, we can explain the following code to define our schema and resolvers. This example shows the
```js
const { ApolloServer } = require('apollo-server');
const typeDefs = `
type Process {
params: [String]
program: String
}
type Query {
process: Process
argv: [String]
}
`;
// Resolvers define the technique for fetching the types in the
// schema. We'll retrieve books from the "books" array above.
const resolvers = {
Process: {
params: (parent) => parent.argv.slice(1)
program: (parent) => parent.argv[0]
url: (_,_,context) => context.req.baseUrl
}
Query: {
process: () => process
argv: () => process.argv
},
};
new ApolloServer({ typeDefs, resolvers, context: { req } })
.listen()
.then(({ url }) => {
console.log(`Visit ${url} to run queries!`);
});
```
## Material to include
* This section ties all of the information in the prereqs to show you how to implement Queries with the Apollo Server
* esentially copy and paste code that you can then add onto

View file

@ -1,6 +1,13 @@
---
title: What's new
description: For all the latest annoucements and features with Apollo Server.
title: What's new?
---
XXX document new APIs, including graphql-tools, engine, and subscriptions
This section of the ApolloServer docs is an annoucement 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]().
## 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.
TODO code example
This is just the beginning. We have published a [roadmap]() 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]() or by joining the [Apollo Slack]() and going to the #apollo-server channel.

View file

@ -1,11 +1,10 @@
---
title: Why Apollo Server?
description: Why choose Apollo Server to power your apps?
title: Why Apollo?
---
Building APIs shouldn't have to be so tricky. If you are concerned about performance, security, or just building a service that will make your product easier to build and maintain, you've found the right place! Through practical examples inspired by real world uses, you'll learn how Apollo Server's schema first design and declarative approach to data loading can help you ship faster while writing less code. Lets build the API of your dreams! 🚀
<h2 id="schema-first">Schema first design</h2>
## Schema first design
We think GraphQL's greatest asset is the schema. Think of it like the rosetta stone of the data your app needs. Schema's represent the toch point of your frontends with the data that powers them. We recommend using the schema definition language, also called the SDL, to easily write out the data and relationships that your app needs to be succesful. Unlike REST APIs, GraphQL schemas shouldn't be a one to one mapping of your database, but rather a representation of how your app works with the data it needs. Let's see what this looks like in practice with Apollo Server:
@ -35,23 +34,23 @@ const resolvers = {
};
const server = new ApolloServer({ typesDefs, resolvers });
server.listen(({ url }) => console.log(`Apollo Server is ready at ${url}`));
server.listen().then(({ url }) => console.log(`Apollo Server is ready at ${url}`));
```
In the example above, we are describing the shapes of our data, how they relate to each other, and how to fetch what our client needs from our data source. Apollo Server uses simple functions called [resolvers](./XXX-link-here) to bring to live the schema described in SDL type definitions. When a request comes in to `/graphql`, Apollo Server will translate that request into what it takes to execute the query, will run the resolvers for you to load your data, and return the result in JSON so your app can render it out easily!
In the example above, we are describing the shapes of our data, how they relate to each other, and how to fetch what our client needs from our data source. Apollo Server uses simple functions called [resolvers]() to bring to live the schema described in SDL type definitions. When a request comes in to `/graphql`, Apollo Server will translate that request into what it takes to execute the query, will run the resolvers for you to load your data, and return the result in JSON so your app can render it out easily!
Apollo Server takes care of every step of translating the query your client asks for, into the data it needs. It is designed to give you the maximum control over how you load the data while taking care of everything else for you! You don't need to worry about parsing the request, validating the query, delivering the response, or even profiling your app. Instead, all you have to do is describe the shape of your data and how to find it; Apollo Server does the rest! 💪
Unlike ad-hoc REST endpoints or complex middleware, Apollo Server will make it easy to delete a ton of code needed to build your app. While you may write less code with Apollo Server, you still get the most powerful GraphQL app possible.
<h2 id="works-with-your-data">Works with your data</h2>
## Works with your data
Learning and implementing a new way to manage your data can be scary and risky. Instead of waiting on a brand new project or rewritting your app from scratch, Apollo Server makes is simple to get started immediately. Whether you have a REST API you want to build on top of, existing database to connect to, or third party data sources to wrangle, Apollo works with your data from day one. You can easily start a new server, or integrate it with your current app in a couple lines of code without sacrificing any of the amazing benefits it can provide. Apollo Server is the fastest way to bring GraphQL to your products out there.
<h2 id="case-studies">Case Studies</h2>
## Case Studies
Companies ranging from enterprise to startups trust Apollo Server to power their most critical applications. If you'd like to learn more about how transitioning to GraphQL And Apollo improved their engineer's workflows and improved their products, check out these case studies:
XXX INSERT CASE STUDIES HERE
TODO INSERT CASE STUDIES HERE
If your company is using Apollo Server in production, we'd love to feature a case study on the Apollo blog! Please get in touch via Slack so we can learn more about how you're using Apollo. Alternatively, if you already have a blog post or a conference talk that you'd like to feature here, please send a [PR](./XXX-link-here)
If your company is using Apollo Server in production, we'd love to feature a case study on the Apollo blog! Please get in touch via Slack so we can learn more about how you're using Apollo. Alternatively, if you already have a blog post or a conference talk that you'd like to feature here, please send a [PR]()