简体   繁体   中英

Apollo server file upload from apollo angular

I am trying to upload a file from Angular using apollo-angular to apollo server but the documentation is confusing and the information i found in genera is not updated to latest versions of apollo angular and apollo server.

In the front end i have:

Mutation

export const Save_UserMutation = gql`
  mutation SaveUserMutation ($data: UsersInput!, $file: Upload) {
   createUser(data: $data, file: $file) {
     user
   }
  }
`

Service

  save(_userData: User, emitMessage?: boolean) {
    let file = _userData.profilePicture
    _userData.profilePicture = (_userData.profilePicture as File).name

    const saveUser$ = this.apollo.mutate({
      mutation: Save_UserMutation,
      variables: {
        data: _dataUsuario,
        file
      },
      context: {
        useMultipart: true
      }
    }).subscribe()
  }

In the backend:

Server

const server = new ApolloServer({
  schema,
  context: createContext,
  uploads: false
})

Uploads set to false just like docs says https://www.apollographql.com/docs/apollo-server/data/file-uploads/#gatsby-focus-wrapper

Mutation written with nexus

export const UsersMutation = extendType({
    type: 'Mutation',
    definition(t) {

        t.nonNull.field('createUser', {
            type: 'Users',
            args: {
                data: nonNull(arg({ type: 'UsersInput' })),
                file: arg({
                    type: GraphQLUpload
                })
            },
            async resolve(parent, args, ctx) {
              
                if (args.file) {
                    const { createReadStream, filename, mimetype, encoding } = await args.file
                    const stream = createReadStream()
                    const pathName = path.join(__dirname, 'public', 'profilePictures') + `/${filename}`
                    await stream.pipe(fs.createWriteStream(pathName))
                    args.data.profilePicture == pathName
                }

                args.data.password = await bcrypt.hash(args.data.password, 10)
                return ctx.prisma.users.create({
                    data: args.data
                })
            }
        }),
})

When i try to upload the file I get the following error.

POST body missing. Did you forget use body-parser middleware?

Finally I found how make it work reading on details the graphql-upload library documentation.

In the Setup heading it says.

Use the graphqlUploadKoa or graphqlUploadExpress middleware just before GraphQL middleware. Alternatively, use processRequest to create custom middleware.

I was not implementing none of the options so the request was not processed.

I changed from Apollo Server to apollo server express and added graphqlUploadExpress as a middleware

server.ts

import { ApolloServer } from 'apollo-server-express'
import { createContext } from './context'
import { schema } from './schema'
import express from 'express'
import { graphqlUploadExpress } from 'graphql-upload';
import path from 'path';
import dotenv from 'dotenv'

dotenv.config()

const app = express();
const PORT = process.env.PORT || 4000

const server = new ApolloServer({
  schema,
  context: createContext,
  uploads: false
})

let publicPath = path.join(__dirname, '..', 'public')

app.use(express.static(publicPath))

app.use(
  '/graphql',
  graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 })
)

server.applyMiddleware({ app })

app.listen({ port: PORT }, () => {
  console.log(`Server running on port ${PORT}`)
})

As I am using nexus, then in my schema definition file i defined a scalar:

Schema Definition File

export const Upload = scalarType({
    name: GraphQLUpload.name,
    asNexusMethod: 'upload', // We set this to be used as a method later as `t.upload()` if needed
    description: GraphQLUpload.description,
    serialize: GraphQLUpload.serialize,
    parseValue: GraphQLUpload.parseValue,
    parseLiteral: GraphQLUpload.parseLiteral,
});

And then I used the Upload Type in the mutation arguments to access file information and save it on the file system.

  t.nonNull.field('createUser', {
            type: 'userMutationResponse',
            args: {
                data: nonNull(arg({ type: 'UsersInput' })),
                file: arg({ type: 'Upload' })
            },
            async resolve(parent, args, ctx) {

                if (args.file) {
        const { createReadStream, filename, mimetype, encoding } = await file
        const stream = createReadStream()
        let newFilename = modFilename(filename)
        const pathName = path.join(__dirname, '..', '..', 'public', 'profilePictures') + `/${newFilename}`
        await stream.pipe(fs.createWriteStream(pathName))


                }

                args.data.password = await bcrypt.hash(args.data.password, 10)

                const userCreated = await ctx.prisma.users.create({ data: args.data })

                userCreated.profilePicture = new URL('profilePictures/' + userCreated.profilePicture, process.env.URI).toString()

                return userCreated                }
        }),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM