如何使用koa-graphql设置graphql-upload?

问题描述

当前使用koa-graphql设置带有koa路由器的graphql服务器,尝试将graphql-upload连接到它,以便我可以上传文件,但是在通过突变发送文件时出现空对象

server.js

import '@babel/polyfill';
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import Router from 'koa-router';
import graphqlHTTP from 'koa-graphql';
import schema from './../graphql/schema';
import rootValue from './../graphql/resolvers/index';

const port = parseInt(process.env.PORT,10) || 3000;

const server = new Koa();
const router = new Router();
server.use(bodyParser({jsonLimit: '50mb'})); 
router.all('/graphql',graphqlHTTP({schema,rootValue}));
server.use(router.allowedMethods());
server.use(router.routes());
server.listen(port,() => console.log(`Running on PORT ${port}`));

schema.js

import {buildSchema} from 'graphql';

export default buildSchema(`
  scalar Upload

  type Obj {
    _id: ID!
    image: String!
    title: String!
  }

  type RootQuery {
    objs: [Obj]!
  }

  type RootMutation {
    createObj(obj: ObjInput!): String!
  }

  input ObjInput {
    title: String!
    image: Upload!
  }

  schema {
    query: RootQuery
    mutation: RootMutation
  }
`);

解析器

import rootQuery from './query';
import rootMutation from './mutations';
import {GraphQLUpload} from 'graphql-upload';

export default {
  Upload: GraphQLUpload,...rootQuery,...rootMutation
};

https://www.npmjs.com/package/koa-graphql

https://www.npmjs.com/package/graphql-upload

解决方法

graphql-upload setup instructions中所述,您需要实现graphqlUploadKoa中的graphql-upload中间件。

示例:

import { graphqlUploadKoa } from 'graphql-upload';
// Ideally set this up for POST requests on the `/graphql` route,before GraphQL server middleware runs.
koaApp.use(graphqlUploadKoa({ maxFileSize: 10000000,maxFiles: 10 }))
,

来自 graphql-upload npm 文档 https://www.npmjs.com/package/graphql-upload 中的指南。

import  { GraphQLUpload,graphqlUploadKoa } from 'graphql-upload'

new Koa().use(graphqlUploadKoa({ maxFileSize: 10000000,maxFiles: 10 }))

在您的架构中,将此添加到顶部

typeDefs: /* GraphQL */ `
    scalar Upload
  `,

在你的解析器中

  resolvers: {
    Upload: GraphQLUpload,},

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...