简体   繁体   English

Nestjs Apollo graphql 上传标量

[英]Nestjs Apollo graphql upload scalar

I'm using nestjs graphql framework and I want to use apollo scalar upload我正在使用 nestjs graphql 框架,我想使用 apollo 标量上传

I have been able to use the scalar in another project that did not include nestjs.我已经能够在另一个不包含 nestjs 的项目中使用标量。

schema.graphql App.module.ts register graphql schema.graphql App.module.ts 注册 graphql

    GraphQLModule.forRoot({
      typePaths: ['./**/*.graphql'],
      resolvers: { Upload: GraphQLUpload },
      installSubscriptionHandlers: true,
      context: ({ req }) => ({ req }),
      playground: true,
      definitions: {
        path: join(process.cwd(), './src/graphql.classes.ts'),
        outputAs: 'class',
      },
      uploads: {
        maxFileSize: 10000000, // 10 MB
        maxFiles: 5
      }
    }),

pets.resolver.ts mutation createPet pets.resolver.ts 变异 createPet

@Mutation('uploadFile')
    async uploadFile(@Args('fileUploadInput') fileUploadInput: FileUploadInput) {
        console.log("TCL: PetsResolver -> uploadFile -> file", fileUploadInput);
        return {
            id: '123454',
            path: 'www.wtf.com',
            filename: fileUploadInput.file.filename,
            mimetype: fileUploadInput.file.mimetype
        }
    }

pets.type.graphql pets.type.graphql

type Mutation {
        uploadFile(fileUploadInput: FileUploadInput!): File!
}
input FileUploadInput{
    file: Upload!
}

type File {
        id: String!
        path: String!
        filename: String!
        mimetype: String!
}

I expect that scalar works with nestjs but my actual result is我希望标量适用于 nestjs,但我的实际结果是

{"errors":[{"message":"Promise resolver undefined is not a function","locations":[{"line":2,"column":3}],"path":["createPet"],"extensions":{"code":"INTERNAL_SERVER_ERROR","exception":{"stacktrace":["TypeError: Promise resolver undefined is not a function","    at new Promise (<anonymous>)","    at TransformOperationExecutor.transform (E:\\projectos\\Gitlab\\latineo\\latineo-api\\src\\TransformOperationExecutor.ts:119:32)","    at E:\\projectos\\Gitlab\\latineo\\latineo-api\\src\\TransformOperationExecutor.ts:62:40","    at Array.forEach (<anonymous>)","    at TransformOperationExecutor.transform (E:\\projectos\\Gitlab\\latineo\\latineo-api\\src\\TransformOperationExecutor.ts:41:30)","    at _loop_1 (E:\\projectos\\Gitlab\\latineo\\latineo-api\\src\\TransformOperationExecutor.ts:226:43)","    at TransformOperationExecutor.transform (E:\\projectos\\Gitlab\\latineo\\latineo-api\\node_modules\\class-transformer\\TransformOperationExecutor.js:240:17)","    at ClassTransformer.plainToClass (E:\\projectos\\Gitlab\\latineo\\latineo-api\\src\\ClassTransformer.ts:43:25)","    at Object.plainToClass (E:\\projectos\\Gitlab\\latineo\\latineo-api\\src\\index.ts:37:29)","    at ValidationPipe.transform (E:\\projectos\\Gitlab\\latineo\\latineo-api\\node_modules\\@nestjs\\common\\pipes\\validation.pipe.js:50:41)","    at transforms.reduce (E:\\projectos\\Gitlab\\latineo\\latineo-api\\node_modules\\@nestjs\\core\\pipes\\pipes-consumer.js:15:28)","    at process._tickCallback (internal/process/next_tick.js:68:7)"]}}}],"data":null}

Use import {GraphQLUpload} from " apollo-server-express "使用import {GraphQLUpload} from " apollo-server-express "
Not from 'graphql-upload'不是来自'graphql-upload'

import { Resolver, Mutation, Args } from '@nestjs/graphql';
import { createWriteStream } from 'fs';

import {GraphQLUpload} from "apollo-server-express"

@Resolver('Download')
export class DownloadResolver {
    @Mutation(() => Boolean)
    async uploadFile(@Args({name: 'file', type: () => GraphQLUpload})
    {
        createReadStream,
        filename
    }): Promise<boolean> {
        return new Promise(async (resolve, reject) => 
            createReadStream()
                .pipe(createWriteStream(`./uploads/${filename}`))
                .on('finish', () => resolve(true))
                .on('error', () => reject(false))
        );
    }
    
}

在此处输入图片说明

I solved it by using graphql-upload library.我通过使用graphql-upload库解决了它。 First i created a class for my scalar using GraphQLUpload from graphql-upload首先,我使用graphql-upload GraphQLUpload为我的标量创建了一个类

import { Scalar } from '@nestjs/graphql';

import { GraphQLUpload } from 'graphql-upload';

@Scalar('Upload')
export class Upload {
  description = 'Upload custom scalar type';

  parseValue(value) {
    return GraphQLUpload.parseValue(value);
  }

  serialize(value: any) {
    return GraphQLUpload.serialize(value);
  }

  parseLiteral(ast) {
    return GraphQLUpload.parseLiteral(ast);
  }
}

That i added in my Application module我在我的应用程序模块中添加的

@Module({
  imports: [
  ...
    DateScalar,
    Upload,
    GraphQLModule.forRoot({
      typePaths: ['./**/*.graphql'],
     ...
      uploads: {
        maxFileSize: 10000000, // 10 MB
        maxFiles: 5,
      },
    }),
  ...
  ],
...
})
export class ApplicationModule {}

i also added Upload scalar in my graphql我还在我的 graphql 中添加了上传标量

scalar Upload
...
type Mutation {
  uploadFile(file: Upload!): String
}

and is worked in my resolver i had acces to the uploaded file.并且在我的解析器中工作,我可以访问上传的文件。

  @Mutation()
  async uploadFile(@Args('file') file,) {
    console.log('Hello file',file)
    return "Nice !";
  }

(side note : I used https://github.com/jaydenseric/apollo-upload-client#function-createuploadlink to upload the file, in the resolver it is a Node Stream) (旁注:我使用https://github.com/jaydenseric/apollo-upload-client#function-createuploadlink上传文件,在解析器中它是一个节点流)

The correct answer for all versions of Apollo Server (fully compatible with Node 14) Apollo Server所有版本的正确答案(完全兼容Node 14)

  1. Disable Apollo Server's built-in upload handling (for apollo 3+ not needed) and add the graphqlUploadExpress middleware to your application.禁用 Apollo Server 的内置上传处理(对于 apollo 3+ 不需要)并将 graphqlUploadExpress 中间件添加到您的应用程序。
import { graphqlUploadExpress } from "graphql-upload"
import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common"

@Module({
  imports: [
    GraphQLModule.forRoot({
      uploads: false, // disable built-in upload handling (for apollo 3+ not needed)
    }),
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(graphqlUploadExpress()).forRoutes("graphql")
  }
}
  1. Remove the GraphQLUpload import from apollo-server-core and import from graphql-upload insteadapollo-server-core删除GraphQLUpload导入,而从graphql-upload导入
// import { GraphQLUpload } from "apollo-server-core" <-- remove this
import { FileUpload, GraphQLUpload } from "graphql-upload"

Note that This old version is not fully compatible with Node 14.请注意,此旧版本与 Node 14 不完全兼容。

Note: Apollo Server's built-in file upload mechanism is not fully supported in Node 14 and later, and it will be removed in Apollo Server 3. For details, see below .注意:Apollo Server 内置的文件上传机制在 Node 14 及更高版本中不完全支持,Apollo Server 3 中将删除它。 详情见下文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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