Coder Social home page Coder Social logo

mercurius-js / mercurius-upload Goto Github PK

View Code? Open in Web Editor NEW

This project forked from bmullan91/fastify-gql-upload

27.0 27.0 9.0 255 KB

graphql-upload implementation plugin for Fastify & mercurius

Home Page: https://mercurius.dev/

License: MIT License

TypeScript 100.00%

mercurius-upload's People

Contributors

bmullan91 avatar jawell avatar mcollina avatar pabloszx avatar qlaffont avatar simenb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mercurius-upload's Issues

On file size exceded, server stop !

Hello,
I'm trying to use mercurius upload but I have an error who stop my server if the uploaded file exceed size.

[15:48:28.141] DEBUG (152219): File truncated as it exceeds the 131100 byte size limit.
    err: {
      "type": "PayloadTooLargeError",
      "message": "File truncated as it exceeds the 131100 byte size limit.",
      "stack":
          PayloadTooLargeError: File truncated as it exceeds the 131100 byte size limit.
              at FileStream.<anonymous> (/app/node_modules/graphql-upload/processRequest.js:250:23)
              at FileStream.emit (node:events:513:28)
              at SBMH.ssCb [as _cb] (/app/node_modules/busboy/lib/types/multipart.js:479:32)
              at feed (/app/node_modules/streamsearch/lib/sbmh.js:248:10)
              at SBMH.push (/app/node_modules/streamsearch/lib/sbmh.js:104:16)
              at Multipart._write (/app/node_modules/busboy/lib/types/multipart.js:567:19)
              at writeOrBuffer (node:internal/streams/writable:392:12)
              at _write (node:internal/streams/writable:333:10)
              at Multipart.Writable.write (node:internal/streams/writable:337:10)
              at IncomingMessage.ondata (node:internal/streams/readable:766:22)
      "status": 413,
      "statusCode": 413,
      "expose": true
    }
{
  filename: 'corey-willett-4wuVqpRvqbY-unsplash.jpg',
  mimetype: 'image/jpeg',
  encoding: '7bit',
  createReadStream: [Function: createReadStream]
}
[15:48:28.142] DEBUG (152219): Server is shutting down
@Mutation(() => String)
  async updateProfilePicture(
    @Arg('image', () => GraphQLUpload, { nullable: true }) payload,
  ): Promise<string> {
    await Controller.updateProfilePicture(payload);

    return 'OK';
  }
  
  
class Controller {
  static async updateProfilePicture(userId: string, payload) {
    //Retrict uploaded file
    if (['image/jpeg', 'image/png', 'image/jpg'].indexOf(payload.mimetype) === -1) {
      throw new BadRequest({ error: GenericErrors.invalid_file_type });
    }

    try {
      const rs = payload.createReadStream(); <------ C R A S H    H E R E
    } catch (e) {
      console.log(e);
      throw new BadRequest({ error: GenericErrors.file_too_large });
    }

    console.log(payload);
    // await savim.uploadFile(`nanny/${}`)
  }
}


  fastify.register(mercuriusUpload, {
    maxFileSize: 131100, // 1 MB
    maxFiles: 1,
  });
  
  

Upload value invalid and type Fastify, TypeGraphQL

I'm trying to do file uploads using a fastify server using mercurius, type-graphql and mercurius-upload plugin. Here is my server code:

import "reflect-metadata";
import "dotenv/config";
import _ from "node-env-types";
import Fastify from "fastify";
import mercurius from "mercurius";
import { buildSchema } from "type-graphql";
import { CtxType } from "./types";
import { resolvers } from "./resolvers";
import { PrismaClient } from "@prisma/client";
import cors from "@fastify/cors";
import cookie from "@fastify/cookie";
import { tokenRoute } from "./routes/token";
import fastifyStatic from "@fastify/static";
import path from "path";
import MercuriusGQLUpload from "mercurius-upload";
_();

const PORT: any = process.env.PORT || 3001;
const HOST =
  process.env.NODE_ENV === "production"
    ? "0.0.0.0"
    : "localhost" || "127.0.0.1";

(async () => {
  const fastify = Fastify({
    logger: false,
    ignoreTrailingSlash: true,
  });

  const prisma = new PrismaClient();
  const schema = await buildSchema({
    resolvers,
    validate: false,
  });

  fastify.register(cors, {
    credentials: true,
    origin: ["http://localhost:3000"],
  });

  fastify.register(cookie, {
    secret: "my-secret",
    parseOptions: {
      sameSite: "lax",
      httpOnly: false,
      secure: false,
      maxAge: 1000 * 60 * 60 * 24 * 7,
    },
  });
  fastify.register(fastifyStatic, {
    root: path.join(__dirname.replace("dist", ""), "storage"),
    prefixAvoidTrailingSlash: true,
    prefix: "/petmall/api/storage",
  });
  fastify.register(MercuriusGQLUpload, {});
  fastify.register(tokenRoute);
  fastify.register(mercurius, {
    context: (request, reply): CtxType => {
      return {
        request,
        reply,
        prisma,
      };
    },
    graphiql: true,
    schema: schema as any,
    errorHandler(error, request, reply) {
      console.log(error);
      console.error(error.message);
    },
  });

  fastify.listen({ port: PORT, host: HOST }, (error, address) => {
    if (error) {
      console.error(error);
      process.exit(1);
    }
    console.log(` Server is now listening on ${address}`);
  });
})();

Here is my PetResolver

import { Arg, Mutation, Resolver } from "type-graphql";
import { NewPetInputType } from "./inputs/inputTypes";

@Resolver()
export class PetResolver {
  @Mutation(() => Boolean)
  async add(@Arg("input", () => NewPetInputType) { image }: NewPetInputType) {
    console.log(image);
    return true;
  }
}

Here in my NewPetInputType

import { InputType, Field, Float, Int, registerEnumType } from "type-graphql";
import { Category, Gender } from "../../../types";
import GraphQLUpload from "graphql-upload/GraphQLUpload.js";
import { FileUpload } from "graphql-upload/Upload";
registerEnumType(Gender, {
  name: "Gender", // this one is mandatory
});

registerEnumType(Category, {
  name: "Category", // this one is mandatory
});

@InputType()
export class LocationInput {
  @Field(() => String, { nullable: true })
  district?: string;
  @Field(() => String, { nullable: true })
  city?: string;
  @Field(() => String, { nullable: true })
  street?: string;
  @Field(() => String, { nullable: true })
  region?: string;
  @Field(() => String, { nullable: true })
  country?: string;
  @Field(() => String, { nullable: true })
  postalCode?: string;
  @Field(() => String, { nullable: true })
  subregion?: string;
  @Field(() => String, { nullable: true })
  timezone?: string;
  @Field(() => String, { nullable: true })
  streetNumber?: string;
  @Field(() => String, { nullable: true })
  name?: string;
  @Field(() => String, { nullable: true })
  isoCountryCode?: string;
}

@InputType()
export class NewPetInputType {
  @Field(() => GraphQLUpload)
  image: FileUpload;

  @Field(() => LocationInput, { nullable: true })
  location?: LocationInput;

  @Field(() => String, { nullable: false })
  description: string;
  @Field(() => Category, { nullable: false })
  category: Category;
  @Field(() => Gender, { nullable: false })
  gender: Gender;
  @Field(() => Float, { nullable: false })
  price: number;
  @Field(() => Int, { nullable: false })
  age: number;
  @Field(() => String, { nullable: false })
  name: string;
}

On the client I'm using React-Native and URQL but when I submit to the file to the server I'm getting the following error.

errors: [
    GraphQLError: Variable "$input" got invalid value { uri: "file:///var/mobile/Containers/Data/Application/6833698F-0EB9-4FCE-AD0F-8DBE529CC55C/Library/Caches/ExponentExperienceData/%2540crispen_dev%252Fmobile/ImagePicker/2DD6F719-DD56-444B-A486-E272FC67793A.jpg", name: "IMG_6129.jpg", type: "image/png" } at "input.image"; Upload value invalid.
....
Graphql validation error

What maybe possibly the problem here?

client hangs after failed upload

I'm using mercurius + mercurius-upload with a basic mutation resolver that reads an input file to store it to a S3 bucket.
If the resolver fails all the subsequent requests to fastify hang indefinitely.

You can find a minimal reproduction code here: https://github.com/bhamon/bug-graphql-upload

To reproduce the issue you should use Chrome + upload a file of about 300 KB (smaller files doesn't fail).
The issue can be reproduced with other clients too, but depending on the client and the uploaded file the results varies a lot. The client must reuse the same HTTP stream in order for the problem to occurs.

The issue as already been reported here for Apollo server and a corrective PR has been issued.

I'm not very familiar with Fastify internals so I can only assume that the problem should be the same.

React Native support

This deson't seem to work in React Native ๐Ÿค”

It used to work in apollo-server v3 but not in fastify and mercurius

ESM support.

Is there a plan to introduce ESM (ECMAScript Module) support? The new version 16 of graphql-upload, which is a dependent is already in ESM and therefore not working with this version.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.