From 828c5aedeb235f2da392bd786a1fcab167e7b51d Mon Sep 17 00:00:00 2001 From: Pagan Gazzard Date: Mon, 26 Jun 2023 17:32:55 +0100 Subject: [PATCH] Rollback device registration if the request ends/is aborted midway Change-type: patch --- src/features/device-provisioning/register.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/features/device-provisioning/register.ts b/src/features/device-provisioning/register.ts index e926487dc..3034936ba 100644 --- a/src/features/device-provisioning/register.ts +++ b/src/features/device-provisioning/register.ts @@ -16,6 +16,7 @@ import { getDeviceTypeBySlug } from '../device-types/device-types'; import { checkInt } from '../../lib/utils'; import { checkDeviceExistsIsFrozen } from '../device-state/middleware'; import { gracefullyDenyConflictingRegistrations } from './gracefully-deny-conflicting-registrations'; +import onFinished from 'on-finished'; const { BadRequestError, ConflictError } = errors; const { api } = sbvrUtils; @@ -67,6 +68,13 @@ export const register: RequestHandler = async (req, res) => { ); const response = await sbvrUtils.db.transaction(async (tx) => { + // TODO: Replace this manual rollback on request closure with a more generic/automated version + onFinished(res, () => { + if (!tx.isClosed()) { + tx.rollback(); + } + }); + const resinApiTx = api.resin.clone({ passthrough: { req, tx } }); const deviceType = await getDeviceTypeBySlug(resinApiTx, deviceTypeSlug); const device = await resinApiTx.post({