Refactor group controller methods and add device product guard

This commit is contained in:
faris Aljohari
2024-04-21 16:27:53 +03:00
parent 18e7e35d35
commit 7abfe29746
8 changed files with 284 additions and 260 deletions
+71
View File
@@ -0,0 +1,71 @@
import { DeviceRepository } from '@app/common/modules/device/repositories';
import {
Injectable,
CanActivate,
HttpStatus,
BadRequestException,
ExecutionContext,
} from '@nestjs/common';
@Injectable()
export class CheckProductUuidForAllDevicesGuard implements CanActivate {
constructor(private readonly deviceRepository: DeviceRepository) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
try {
const { deviceUuids } = req.body;
console.log(deviceUuids);
await this.checkAllDevicesHaveSameProductUuid(deviceUuids);
return true;
} catch (error) {
this.handleGuardError(error, context);
return false;
}
}
async checkAllDevicesHaveSameProductUuid(deviceUuids: string[]) {
const firstDevice = await this.deviceRepository.findOne({
where: { uuid: deviceUuids[0] },
});
if (!firstDevice) {
throw new BadRequestException('First device not found');
}
const firstProductUuid = firstDevice.productUuid;
for (let i = 1; i < deviceUuids.length; i++) {
const device = await this.deviceRepository.findOne({
where: { uuid: deviceUuids[i] },
});
if (!device) {
throw new BadRequestException(`Device ${deviceUuids[i]} not found`);
}
if (device.productUuid !== firstProductUuid) {
throw new BadRequestException(`Devices have different product UUIDs`);
}
}
}
private handleGuardError(error: Error, context: ExecutionContext) {
const response = context.switchToHttp().getResponse();
console.error(error);
if (error instanceof BadRequestException) {
response
.status(HttpStatus.BAD_REQUEST)
.json({ statusCode: HttpStatus.BAD_REQUEST, message: error.message });
} else {
response.status(HttpStatus.NOT_FOUND).json({
statusCode: HttpStatus.NOT_FOUND,
message: 'Device not found',
});
}
}
}