[英]Typescript: how to use a method decorator in an instance member property (mixin)?
Background背景
We have implemented a mixin like this (simplified):我们已经实现了这样的混合(简化):
export type Constructor<I> = new (...args: any[]) => I;
export interface IBaseService<T = any> {
create: (data: any) => Promise<T>;
}
export function BaseService<T>(entity: Constructor<T>): Type<IBaseService<T>> {
class BaseServiceHost implements IBaseService<T> {
public repository: Repository<T>;
create(data: DeepPartial<T>): Promise<T> {
const newResource = this.repository.create(data);
return this.repository.save(newResource);
}
}
return BaseServiceHost;
}
Now my service extends BaseService
like this:现在我的服务像这样扩展
BaseService
:
@Injectable()
export class ResponseService extends BaseService(ResponseEntity) {
private readonly respondentService: RespondentService;
private readonly surveyService: SurveyService;
create = async (data: ResponseInput): Promise<ResponseEntity> => {
const respondent = await this.respondentService.findByNaturalKey(data.respondentKey);
const survey = await this.surveyService.findById(data.surveyId);
return super.create({ respondent, survey, ...data })
};
... and this works fine. ...这工作正常。
PS.: create
has to be a property now, otherwise I'd get the following error: PS .:
create
现在必须是一个属性,否则我会收到以下错误:
Class 'IBaseTenantService<ResponseEntity>' defines instance member property 'create',
but extended class 'ResponseService' defines it as instance member function.
Problem问题
The create
method (now a property), needs the method decorator Transactional()
, but the construction create
方法(现在是一个属性),需要方法装饰器Transactional()
,但是构造
@Transactional() // <--- error here
create = async (data: ResponseInput): Promise<ResponseEntity> => {
const respondent = await this.respondentService.findByNaturalKey(data.respondentKey);
const survey = await this.surveyService.findById(data.surveyId);
return super.create({ respondent, survey, ...data })
};
gives the following error:给出以下错误:
The return type of a property decorator function must be either 'void' or 'any'.
Unable to resolve signature of property decorator when called as an expression.
Question问题
How to use the Transactional()
in the create
property?如何在
create
属性中使用Transactional()
? Workarounds?解决方法?
this might sound dumb but ever you tried this:这听起来可能很愚蠢,但你试过这个:
@Transactional()
async create(data: ResponseInput): Promise<ResponseEntity> {
const respondent = await this.respondentService.findByNaturalKey(data.respondentKey);
const survey = await this.surveyService.findById(data.surveyId);
return super.create({ respondent, survey, ...data })
};
? ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.