mirror of
https://github.com/SyncrowIOT/backend.git
synced 2026-10-25 06:17:54 +00:00
73 lines
2.0 KiB
TypeScript
73 lines
2.0 KiB
TypeScript
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;
|
|
|
|
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], isActive: true },
|
|
relations: ['productDevice'],
|
|
});
|
|
|
|
if (!firstDevice) {
|
|
throw new BadRequestException('First device not found');
|
|
}
|
|
|
|
const firstProductType = firstDevice.productDevice.prodType;
|
|
|
|
for (let i = 1; i < deviceUuids.length; i++) {
|
|
const device = await this.deviceRepository.findOne({
|
|
where: { uuid: deviceUuids[i], isActive: true },
|
|
relations: ['productDevice'],
|
|
});
|
|
|
|
if (!device) {
|
|
throw new BadRequestException(`Device ${deviceUuids[i]} not found`);
|
|
}
|
|
|
|
if (device.productDevice.prodType !== firstProductType) {
|
|
throw new BadRequestException(`Devices have different product types`);
|
|
}
|
|
}
|
|
}
|
|
|
|
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',
|
|
});
|
|
}
|
|
}
|
|
}
|