【发布时间】:2021-03-11 20:35:48
【问题描述】:
我正在为nestjs 编写一个模块,我想通过npm 发布它。该包是minio的动态模块。
问题是该模块在嵌套应用程序项目中时可以正常工作,但是当我将它复制到另一个文件夹并尝试从中创建一个 npm 模块时,异常处理就成了一个问题。
此模块包含一个minio.service.ts 文件作为提供程序,并且在此服务文件中存在一些例外情况,例如UnsupportedMediaTypeException 或PayloadTooLargeException。当模块在嵌套项目中时,异常处理工作非常好并且没有问题,但是当我尝试将其发布为 npm 包时,所有异常都被抛出为InternalServerException。
以下是一些重要文件:
// src/minio.module.ts
import { Module, DynamicModule, Global } from '@nestjs/common';
import {ClientOptions } from 'minio';
import { MinioService } from './minio.service';
import { MinioOptions } from './types/minio.options';
import {MINIO_CONFIG, MINIO_OPTIONS} from "./types/constants";
@Global()
@Module({})
export class MinioModule {
static register(
minioConfig: ClientOptions,
minioOptions: MinioOptions,
): DynamicModule {
return {
global: true,
module: MinioModule,
providers: [
{ provide: MINIO_CONFIG, useValue: minioConfig },
{ provide: MINIO_OPTIONS, useValue: minioOptions },
MinioService,
],
exports: [MinioService],
};
}
}
// src/minio.service.ts
import {
Injectable,
Logger,
InternalServerErrorException,
Inject,
NotFoundException,
UnsupportedMediaTypeException,
PayloadTooLargeException,
} from '@nestjs/common';
import { Response } from 'express';
import * as crypto from 'crypto';
import { ClientOptions, Client } from 'minio';
import { BufferedFile } from './types/buffered-file.interface';
import { DeleteFileResponse, UploadFileResponse } from './dto/response.dto';
import { IMinioService } from './types/minio-service.interface';
import { MinioOptions } from './types/minio.options';
import { UploadValidator } from './types/upload-validator.interface';
import { MINIO_CONFIG, MINIO_OPTIONS } from "./types/constants";
@Injectable()
export class MinioService implements IMinioService {
private readonly service;
constructor(
@Inject(MINIO_CONFIG) private minioConfig: ClientOptions,
@Inject(MINIO_OPTIONS) private minioOptions: MinioOptions,
) {
this.service = new Client(this.minioConfig);
}
async upload(
file: BufferedFile,
bucket: string,
validator: UploadValidator = null,
): Promise<string> {
if (file.size > 50000) {
throw new BadRequestException();
}
return this.service
.putObject(bucket, fileName, file.buffer, metaData)
.then(() => {
const url = `/${bucket}/${fileName}`;
return url;
})
.catch((err) => {
throw new InternalServerException(err.message);
});
}
}
如果您需要查看项目,这里是其存储库的链接:
【问题讨论】:
标签: typescript nestjs