jen*_*gel 5 reactjs graphql apollo-server nestjs fastify
使用以下包/技术组合(及其相应的依赖项未列出)从服务器上的客户端接收文件上传的正确实现是什么:
graphql-uploadapollo-server-fastify@nestjs/platform-fastify (代码优先方法)理想情况下,我们正在尝试使用 NestJS GraphQL Code First 技术(除了多个文件而不是一个文件)来实现以下内容(来自apollo 服务器文件上传)
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type File {
filename: String!
mimetype: String!
encoding: String!
}
type Query {
uploads: [File]
}
type Mutation {
singleUpload(file: Upload!): File!
}
`;
const resolvers = {
Query: {
uploads: (parent, args) => {},
},
Mutation: {
singleUpload: (parent, args) => {
return args.file.then(file => {
//Contents of Upload scalar: https://github.com/jaydenseric/graphql-upload#class-graphqlupload
//file.stream is a node stream that contains the contents of the uploaded file
//node stream api: https://nodejs.org/api/stream.html
return file;
});
},
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.listen().then(({ url }) => {
console.log(` Server ready at ${url}`);
});
Run Code Online (Sandbox Code Playgroud)
现在,我的前端使用此更改正确地将文件发送到我的服务器:
gql`
mutation uploadObjects($files: [Upload!]!) {
uploadObjects(files: $files) {
bucketKey
}
}
`;
Run Code Online (Sandbox Code Playgroud)
以下是按预期与文件二进制文件一起发送的请求图像的链接:
小智 0
您可以将 graphql-upload 与 Apollo Server 和 NestJS 的 @nestjs/platform-fastify 一起使用。这个想法是使用 graphql-upload 作为中间件来处理来自客户端的文件上传。
首先,您需要更新 NestJS 的 main.ts 文件,以将 graphql-upload 与 Apollo 和 Fastify 集成。
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { graphqlUploadFastify } from 'graphql-upload';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
// Apply the graphql upload middleware
app.register(graphqlUploadFastify, {
maxFileSize: 10000000, // 10 MB
maxFiles: 5,
});
await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
然后,您需要在 GraphQL 模块中定义上传标量并更新解析器和架构以使用上传标量。以下是如何做到这一点的示例。
在你的app.module.ts中:
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'path';
@Module({
imports: [
GraphQLModule.forRoot({
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
uploads: false, // Disable the built-in upload functionality of Apollo Server
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
接下来,定义您的架构(例如 upload.schema.ts):
import { ObjectType, Field, InputType, Directive } from '@nestjs/graphql';
@ObjectType()
export class File {
@Field()
filename: string;
@Field()
mimetype: string;
@Field()
encoding: string;
}
@InputType()
@Directive('@extends')
@Directive('@key(fields: "id")')
export class Upload {
@Field()
id: string;
}
Run Code Online (Sandbox Code Playgroud)
以及相应的解析器(例如upload.resolver.ts):
import { Resolver, Mutation, Args, Query } from '@nestjs/graphql';
import { FileUpload, GraphQLUpload } from 'graphql-upload';
import { createWriteStream } from 'fs';
import { File } from './upload.schema';
@Resolver()
export class UploadResolver {
@Query(() => [File])
async uploads(): Promise<File[]> {
// Implement the logic to return the files
return [];
}
@Mutation(() => Boolean)
async uploadObjects(@Args({ name: 'files', type: () => [GraphQLUpload] }) files: FileUpload[]): Promise<boolean> {
await Promise.all(
files.map(async file => {
const { createReadStream, filename } = await file;
// Create a stream to your file destination.
// Here is an example of saving the file locally
return new Promise((resolve, reject) =>
createReadStream()
.pipe(createWriteStream(`./uploads/${filename}`))
.on('finish', () => resolve(true))
.on('error', (error) => reject(error)),
);
}),
);
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
在此实现中,您使用 Fastify 作为 HTTP 服务器,而不是默认服务器 (Express),并使用 graphql-upload 中间件来处理文件上传。中间件通过文件上传解析传入请求,并将流传递到解析器。请注意,在 @Mutation 装饰器中,我们使用 graphql-upload 提供的 GraphQLUpload,这是文件上传所需的格式。
请确保安装了所有必需的软件包。如果没有,请使用 npm 或 yarn 安装它们:
npm install @nestjs/graphql graphql-tools graphql apollo-server-fastify fastify multipart graphql-upload
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
880 次 |
| 最近记录: |