简体   繁体   中英

Handling file upload with nexus-prisma graphql

I'm trying to upload a file from my frontend app to my server but I keep getting this weird error and have no idea why its happening

Error is frontend:

Variable "$file" got invalid value {}; Expected type Upload. Upload value invalid.

Error in backend:

GraphQLError: Upload value invalid.
at GraphQLScalarType.parseValue (/app/backend/node_modules/graphql-upload/lib/GraphQLUpload.js:66:11)

this is how I added the Upload scalar


// scalars/upload.ts
import { scalarType } from "nexus/dist";
import { GraphQLUpload } from "graphql-upload";

export const Upload = scalarType({
  name: "Upload",
  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,
});

export default Upload;

//scalar/index.ts
export { default as Upload } from "./Upload";

// index.ts
import * as allTypes from "./resolvers";
import * as scalars from "./scalars";
const schema = makePrismaSchema({
  types: [scalars, allTypes],
  prisma: {
    datamodelInfo,
    client: prisma,
  },
...

// my mutation 
t.string("uploadFile", {
      args: {
        file: arg({ type: "Upload", nullable: false }),
      },
      resolve: async (_: any, { file }, {  }: any) => {
        console.log(file);
        return "ok";
      },
    });

this is how I made the uplaod client in my react/nextjs app

// the link
const link = () => {
    return createUploadLink({
      uri: process.env.backend,
      credentials: "include",
      fetch,
    });
  };

// the mutation ( I use graphql codegen )

mutation TestUpload($file: Upload!) {
  uploadFile(file: $file)
}

const [upload] = useTestUploadMutation();

<input
            type="file"
            onChange={(e) => {
              const { files, validity } = e.target;
              if (validity.valid && files && files[0]) {
                upload({
                  variables: {
                    file: files[0],
                  },
                });
              }
            }}
          />

even when trying to run the mutation using something other than my frontend app I get the same error, so I guess the problem is whith my backend setup, even though I searched a lot for ways to do it none seems to work.

I just had the exact same problem. This fixed it. So basically defining the upload manually instead of using GraphQLUpload

import { objectType, scalarType } from "@nexus/schema";
import { GraphQLError } from "graphql";
import * as FileType from "file-type";

export const Upload = scalarType({
  name: "Upload",
  asNexusMethod: "upload", // We set this to be used as a method later as `t.upload()` if needed
  description: "desc",
  serialize: () => {
    throw new GraphQLError("Upload serialization unsupported.");
  },
  parseValue: async (value) => {
    const upload = await value;
    const stream = upload.createReadStream();
    const fileType = await FileType.fromStream(stream);

    if (fileType?.mime !== upload.mimetype)
      throw new GraphQLError("Mime type does not match file content.");

    return upload;
  },
  parseLiteral: (ast) => {
    throw new GraphQLError("Upload literal unsupported.", ast);
  },
});

export const File = objectType({
  name: "File",
  definition(t) {
    t.id("id");
    t.string("path");
    t.string("filename");
    t.string("mimetype");
    t.string("encoding");
  },
});

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