我正在尝试使用 graphql 设置我的 koa 服务器,我这样做的方式是为路由“graphql”传递中间件,但我得到了标题中所述的错误。 我不确定为什么它以未定义的形式返回 _graphql。
这是我的 app.js 文件,它定义了服务器和服务器期望的路由。其中之一是我计划最初测试的 graphql 路线。
app.js
class Server {
constructor(_config) {
this.middleware = new Middleware(_config)
this.knex = Knex({
client: "mysql2",
connection: {
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database,
port: config.mysql.port || 3306,
ssl: config.mysql.ssl || false,
},
pool: { min: 0, max: 20 },
})
// Tracker middleware
let middleware = new Middleware({
knex: this.knex,
config: _config,
})
// define router
const router = new Router()
router.all("/graphql", middleware.graphql.bind(middleware), (ctx) => {
ctx.body = ctx.graphql
})
app.use(router.routes()).use(router.allowedMethods())
app.silent = false
app.on("error", (err, ctx) => {
// TODO: // Log error
console.log(err)
ctx.status = 500
ctx.body = {
message: err.message,
status: err.statusCode,
type: err.type || "UNDEFINED",
info: err.info,
}
})
}
}
index.js
这是在它自己的文件中定义的所有中间件的文件,但是中间件是通过 koa 的ctx
传递下来的。
import { Cars } from "../models/cars.js"
import { Parkings } from "../models/parkings.js"
import { Transactions } from '../models/transactions.js'
import { CarInputSchema, ParkingInputSchema, TransactionInputSchema } from "./schema.js"
import { graphqlHTTP } from 'koa-graphql'
import { CarType, ParkingType, TransactionsType } from './graphql-schema.js'
import { GraphQLObjectType, GraphQLNonNull, GraphQLString, GraphQLInt, GraphQLID } from "graphql"
class Middleware {
constructor(params) {
this.knex = params.knex
this.car = new Cars(params)
this.parkings = new Parkings(params)
this.transactions = new Transactions(params)
}
async graphql(ctx, next) {
const schema = {
query: new GraphQLObjectType({
name: "Query",
fields: {
cars: {
type: CarType,
args: {
id: { type: GraphQLID },
},
resolve: (root, args, ctx, info) => {
const { id } = args
return this.car.getById(id)
},
},
},
}),
}
ctx.graphql = await graphqlHTTP({
schema:schema,
graphiql: true,
})
await next()
}
my car schema 在
graphql-schema.js
中定义
const CarType = new GraphQLObjectType({
name: "Car",
fields: () => ({
id: { type: new GraphQLNonNull(GraphQLString), resolve: (root, args, context, info) => root.id },
createAt: { type: GraphQLString },
updatedAt: { type: GraphQLString },
inactiveAt: { type: GraphQLString },
fbUserId: { type: GraphQLString, resolve: (root, args, context, info) => root.fbUserId },
carPlate: { type: GraphQLString, resolve: (root, args, context, info) => root.carPlate },
carInfo: { type: GraphQLString, resolve: (root, args, context, info) => root.carInfo },
}),
})
export { CarType }