从装饰器获取价值(打字稿)

时间:2018-08-21 20:48:18

标签: typescript

export class UploadGreetingController {
constructor(
private greetingFacade: GreetingFacade,

) {}
@UseInterceptors(FileInterceptor('file', {
    storage: diskStorage({
        destination: (req: any, file, cb) => {
            if (process.env.DEVELOPMENT === 'prod') {
                return cb(null, `${process.env.DEV_PATH_TO_GREETING_AUDIO}`);
            }
            return cb(null, `${process.env.PROD_PATH_TO_GREETING_AUDIO}`);
        },
        filename: async (req: any, file, cb) => {
            let uuid = await v4();
            req.params.uuid = uuid;
            return cb(null, `${uuid}.mp3`);
        }
    }),
    fileFilter: async (req, file: any, cb) => {
        let {userId, accountId} = req.user;
        let {greetingID} = req.params;
        if (greetingID === 'null' || !greetingID) {
            req.params.error = 'greeting:youShouldPassGreetingID';
            return cb(null, false);
        }
//HERE I WANT TO GET ACCESS TO this.greetingFacade .How can I make it ?
            let greetingEntity: any = await this.greetingFacade.getGreetingByUserIdAndAccountIdAndGreetingID(userId, accountId, greetingID);
            let type = (req.params.type) ? req.params.type : greetingEntity.type;
            if (type) {
                let type = (typeof req.params.type === 'string') ? parseInt(req.params.type) : req.params.type;
                if (type === 2) {
                    if (!file.originalname.match(/\.(mp3)$/)) {
                        return cb(null, false);
                    }
                    req.params.error = 'greeting:youShouldPassCorrectAudioFormat';
                    let deleteGreeting = (greetingEntity.uuid) ?
                        await this.greetingFacade.deleteAudioFromDisk(`${process.env.DEV_PATH_TO_GREETING_AUDIO}`, greetingEntity.uuid) : null;
                    return cb(null, file);
                }
                return cb(null, false);
            }
            return cb(null, false);
        }
    }))
}

在上面您可以看到我的代码。我想访问this.greetingFacade值。但是在此装饰器的@UseInterceptors内部是不可见的。如何使其可见(或访问此值)?如果我不需要使用此private greetingFacade: GreetingFacade这部分代码,这不是问题。但就我而言,它做不到。检查此代码段。

  //HERE I WANT TO GET ACCESS TO this.greetingFacade .How can I make it ?

1 个答案:

答案 0 :(得分:1)

只需在类或控制器上声明一个属性,然后将该实例设置为构造函数中的属性即可。

  private greetingFacade:GreetingFacade;

    export class UploadGreetingController {
    constructor(greetingFacade: GreetingFacade) {

    this.greetingFacade=greetingFacade;

    }