'Factory function for mongoose transaction session on Typescript
I have a lot of function like these
currency.service.ts
async createCurrencyOnSession(createCurrencyDto: CreateCurrencyDto): Promise<ResponseCurrencyDto> {
const session = await this.currencyModel.startSession();
session.startTransaction();
try {
const currency = await this.createCurrency(createCurrencyDto, {session});
await session.commitTransaction();
return currency;
} finally {
await session.endSession();
}
}
user.service.ts
async createUserOnSession(createUserDto: CreateUserDto): Promise<ResponseUserDto> {
const session = await this.userModel.startSession();
session.startTransaction();
try {
const user = await this.createUser(createUserDto, {session});
await session.commitTransaction();
return user;
} finally {
await session.endSession();
}
}
I don't like many try catch on code so I try to edit
currency.service.ts
async createCurrencyOnSession(
createCurrencyDto: CreateCurrencyDto,
): Promise<CurrencyResponseDto> {
const session = await this.currencyModel.startSession();
session.startTransaction();
return handleSession(this.createCurrency(createCurrencyDto, { session }));
}
export const handleSession =
async (handler) => async (dto, options: ISessionOptions) => {
try {
return await handler(dto, options);
} finally {
await options.session.endSession();
}
};
I can see error on Typescript because the main function return a specific interface: CurrencyResponseDto, UserResponseDto. How can I add dynamic interface to return CurrencyResponseDto, UserResponseDto, ... on factory function.
Could you help me to make it clean or suggest a better version on problem. Thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
