eggjs / eggjs/egg

[RFC] egg-graphql支持apollo-server-koa

Open
#3,668 8 comments 10 reactions 1 assignee Claimed by @JasinYip View on GitHub
type: proposals
Dominant language
TypeScript
Stars
19k
Forks
1.8k
PR merge metrics
No merged PRs in 30d

Description

## 背景

> egg-graphql目前存在以下问题
1. 不支持[formatError ](https://github.com/eggjs/egg/issues/3560),[无法捕获异常](https://github.com/eggjs/egg/issues/3064)
2. 不支持文件上传
3. graphiql调试界面没有[graphql-playground](https://github.com/prisma/graphql-playground)好看
4. 不支持[apollo-server](https://www.apollographql.com/docs/apollo-server/api/apollo-server)的选项

## 思路
>修改lib/load_schema.js
```js
//增加
app.schemaConfig={
typeDefs:schemas,
resolvers:resolverMap,
directiveResolvers:directiveMap
}
```
>修改app/middleware/graphql.js
```js
const { ApolloServer } = require('apollo-server-koa')
const compose = require('koa-compose')
/**
* @param {Object} options The `options` of apollo-server.
* @return {Promise} The compose of middleware in apollo-server-koa.
*/

module.exports = (_, app) => {
let graphqlConfig=app.config.graphql
if(typeof graphqlConfig==='function'){
graphqlConfig=graphqlConfig(app)
}
const options = {...app.schemaConfig,...graphqlConfig}
const {graphiql=true,router,...ApolloServerConfig}=options
const server = new ApolloServer({
context: options=>options.ctx,
//不设置request.credentials 会导致请求不带cookie
playground:graphiql&&{
settings:{
"request.credentials": "include"
}
},
...ApolloServerConfig,
})

const middlewares = []
const proxyApp = {
use: m => {
middlewares.push(m)
},
}
server.applyMiddleware({
app: proxyApp,
path:router
})
return compose(middlewares)
}
```
## 修改后的优点
1. 支持apollo-server的options
2. **支持文件上传**.
3. **更漂亮的调试界面**.
## 修改后的问题
1. 不支持onPreGraphiQL,不过onPreGraphiQL只在开发阶段用
如果要支持onPreGraphQL的话,可以在app/middleware/graphql.js里添加
## 跟进

- [egg-apollo-server](https://github.com/supperchong/egg-apollo-server)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.