0

Currently using koa-graphql to set up a graphql server with koa router, attempting to connect graphql-upload to it so I can upload files, however I'm getting an empty object when sending a file through a mutation

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
  }
`);

resolvers

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

Kevin Mangal
  • 230
  • 1
  • 3
  • 14

2 Answers2

0

As mentioned in the graphql-upload setup instructions, you need to implement the graphqlUploadKoa middleware from graphql-upload.

Example:

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 }))
Jayden Seric
  • 71
  • 2
  • 7
0

From the guide found in the graphql-upload npm documentation https://www.npmjs.com/package/graphql-upload .

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

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

In your schema, add this uptop

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

In your resolver

  resolvers: {
    Upload: GraphQLUpload,
  },
padaleiana
  • 955
  • 1
  • 14
  • 23