未验证 提交 a6c7ab97 编写于 作者: L Lukáš Huvar 提交者: GitHub

Example for GraphQL server with API routes (#7804)

* Example for GraphQL server with API routes

* Update examples/api-routes-graphql/pages/index.js
Co-Authored-By: NLuis Fernando Alvarez D. <luis@zeit.co>
上级 b013e11b
# API routes with GraphQL server
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example api-routes-graphql api-routes-graphql-app
# or
yarn create next-app --example api-routes-graphql api-routes-graphql-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/api-routes-graphql
cd api-routes-graphql
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
Next.js ships with [API routes](https://github.com/zeit/next.js#api-routes), which provide an easy solution to build your own `API`. This example shows their usage alongside [apollo-server-micro](https://github.com/apollographql/apollo-server/tree/master/packages/apollo-server-micro) to provide simple GraphQL server consumed by Next.js app.
{
"name": "api-routes-graphql",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"apollo-server-micro": "2.6.7",
"graphql": "14.4.2",
"isomorphic-unfetch": "3.0.0",
"next": "9.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"license": "ISC"
}
import { ApolloServer, gql } from 'apollo-server-micro'
const typeDefs = gql`
type Query {
users: [User!]!
}
type User {
name: String
}
`
const resolvers = {
Query: {
users (parent, args, context) {
return [{ name: 'Nextjs' }]
}
}
}
const apolloServer = new ApolloServer({ typeDefs, resolvers })
export const config = {
api: {
bodyParser: false
}
}
export default apolloServer.createHandler({ path: '/api/graphql' })
import fetch from 'isomorphic-unfetch'
const Index = ({ users }) => (
<div>
{users.map((user, i) => (
<div key={i}>{user.name}</div>
))}
</div>
)
Index.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/api/graphql', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ query: '{ users { name } }' })
})
const {
data: { users }
} = await response.json()
return { users }
}
export default Index
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册