问题描述
嘿,我开始通过做 Frontend Masters' course Introduction to GraphQL (repo) 来学习 graphQL。 我会从上下文开始,但我到处看,什么也没有,我也试图改变它,但它总是相同的输出。如果有人能提供帮助,我将非常非常感激。
import { ApolloServer } from 'apollo-server'
import { loadTypeSchema } from './utils/schema'
import { authenticate } from './utils/auth'
import { merge } from 'lodash'
import config from './config'
import { connect } from './db'
import product from './types/product/product.resolvers'
import coupon from './types/coupon/coupon.resolvers'
import user from './types/user/user.resolvers'
const types = ['product','coupon','user']
export const start = async () => {
const rootSchema = `
type Cat {
name: String
}
type _Query {
myCat: Cat
}
schema {
query: _Query
mutation: Mutation
}
`
const schemaTypes = await Promise.all(types.map(loadTypeSchema))
const server = new ApolloServer({
typeDefs: [rootSchema,...schemaTypes],resolvers: {
_Query: {
myCat(){
console.log('Hello there')
return {name:'Ivar'}
}
},async context({ req }) {
const user = await authenticate(req)
return { user }
}
}
}
)
await connect(config.dbUrl)
const {url} = await server.listen({port: config.port})
console.log(`GQL server ready at ${url}`)
}
import mongoose from 'mongoose'
import options from './config'
export const connect = (url = options.dbUrl,opts = {}) =>
{ return mongoose .connect(url,{
useNewUrlParser: true,useCreateIndex: true,useUnifiedTopology: true })
.then(() => console.log('Database Connected'))
.catch(err => console.log(err))
}
奇怪的是,在某些时候它运行良好,我进行了更改,但并不重要。
控制台输出是这样的:
...
$ node dist/index.js
(node:17124) UnhandledPromiseRejectionWarning: Error: "context" defined in resolvers,but not in schema (Use `node --trace-warnings ...` to show where the warning was created)
(node:17124) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:17124) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[nodemon] clean exit - waiting for changes before restart
解决方法
context
是您传递给 ApolloServer
的配置对象的一部分,而不是其 .resolvers
对象的一部分。
const server = new ApolloServer({
typeDefs: [rootSchema,...schemaTypes],resolvers: {
_Query: {
myCat(){
console.log('Hello there')
return {name:'Ivar'}
}
},},async context({ req }) {
const user = await authenticate(req)
return { user }
},})