Knex.js return promise 中的 transactionScope
Knex.js return transactionScope in promise
我有一个函数 setClaims,它只是为当前交易设置声明。我需要创建一个辅助函数来检查是否提供了 uuid、设置声明和 return 交易对象。像这样:
export const useAuthTransaction = async (
kx: Knex,
setClaims: (tx: Knex.Transaction, uuid?: string) => Promise<any>,
uuid?: string,
): Promise<Knex.Transaction> => {
if (!uuid) {
throw { errorCodes: [RemoveQuestionErrorCode.Unauthorized] };
}
return kx.transaction(async tx => {
await setClaims(tx);
return tx;
});
};
但是当我尝试在解析器中使用它时:
useAuthTransaction(kx, setClaims, claims?.uid).then(async tx =>
dataSources.questionAPI.update(tx, input));
它说:
Transaction query already complete
如何在不关闭的情况下解析事务上下文?
从事务处理程序返回承诺会自动提交/拒绝它。
所以您使用的是 async tx => {...}
类型的处理程序,它隐含地总是 returns 一个承诺。
您想要做的是使用 knex.transactionProvider()
功能(检查文档中的示例),然后您可以传递该事务并明确告知何时应提交/回滚。
我有一个函数 setClaims,它只是为当前交易设置声明。我需要创建一个辅助函数来检查是否提供了 uuid、设置声明和 return 交易对象。像这样:
export const useAuthTransaction = async (
kx: Knex,
setClaims: (tx: Knex.Transaction, uuid?: string) => Promise<any>,
uuid?: string,
): Promise<Knex.Transaction> => {
if (!uuid) {
throw { errorCodes: [RemoveQuestionErrorCode.Unauthorized] };
}
return kx.transaction(async tx => {
await setClaims(tx);
return tx;
});
};
但是当我尝试在解析器中使用它时:
useAuthTransaction(kx, setClaims, claims?.uid).then(async tx =>
dataSources.questionAPI.update(tx, input));
它说:
Transaction query already complete
如何在不关闭的情况下解析事务上下文?
从事务处理程序返回承诺会自动提交/拒绝它。
所以您使用的是 async tx => {...}
类型的处理程序,它隐含地总是 returns 一个承诺。
您想要做的是使用 knex.transactionProvider()
功能(检查文档中的示例),然后您可以传递该事务并明确告知何时应提交/回滚。