mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-15 10:25:23 +00:00
Refactor group controller methods and add device product guard
This commit is contained in:
@ -5,17 +5,18 @@ import {
|
|||||||
Get,
|
Get,
|
||||||
Post,
|
Post,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
Query,
|
|
||||||
Param,
|
Param,
|
||||||
Put,
|
Put,
|
||||||
Delete,
|
Delete,
|
||||||
|
HttpException,
|
||||||
|
HttpStatus,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
|
||||||
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
import { JwtAuthGuard } from '../../../libs/common/src/guards/jwt.auth.guard';
|
||||||
import { AddGroupDto } from '../dtos/add.group.dto';
|
import { AddGroupDto } from '../dtos/add.group.dto';
|
||||||
import { GetGroupDto } from '../dtos/get.group.dto';
|
|
||||||
import { ControlGroupDto } from '../dtos/control.group.dto';
|
import { ControlGroupDto } from '../dtos/control.group.dto';
|
||||||
import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
||||||
|
import { CheckProductUuidForAllDevicesGuard } from 'src/guards/device.product.guard';
|
||||||
|
|
||||||
@ApiTags('Group Module')
|
@ApiTags('Group Module')
|
||||||
@Controller({
|
@Controller({
|
||||||
@ -25,34 +26,43 @@ import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
|||||||
export class GroupController {
|
export class GroupController {
|
||||||
constructor(private readonly groupService: GroupService) {}
|
constructor(private readonly groupService: GroupService) {}
|
||||||
|
|
||||||
@ApiBearerAuth()
|
// @ApiBearerAuth()
|
||||||
@UseGuards(JwtAuthGuard)
|
// @UseGuards(JwtAuthGuard)
|
||||||
@Get()
|
@Get('space/:spaceUuid')
|
||||||
async getGroupsByHomeId(@Query() getGroupsDto: GetGroupDto) {
|
async getGroupsBySpaceUuid(@Param('spaceUuid') spaceUuid: string) {
|
||||||
try {
|
try {
|
||||||
return await this.groupService.getGroupsByHomeId(getGroupsDto);
|
return await this.groupService.getGroupsBySpaceUuid(spaceUuid);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
throw new Error(err);
|
throw new HttpException(
|
||||||
|
error.message || 'Internal server error',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ApiBearerAuth()
|
// @ApiBearerAuth()
|
||||||
@UseGuards(JwtAuthGuard)
|
// @UseGuards(JwtAuthGuard)
|
||||||
@Get(':groupId')
|
@Get(':groupUuid')
|
||||||
async getGroupsByGroupId(@Param('groupId') groupId: number) {
|
async getGroupsByGroupId(@Param('groupUuid') groupUuid: string) {
|
||||||
try {
|
try {
|
||||||
return await this.groupService.getGroupsByGroupId(groupId);
|
return await this.groupService.getGroupsByGroupUuid(groupUuid);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
throw new Error(err);
|
throw new HttpException(
|
||||||
|
error.message || 'Internal server error',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ApiBearerAuth()
|
// @ApiBearerAuth()
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(CheckProductUuidForAllDevicesGuard)
|
||||||
@Post()
|
@Post()
|
||||||
async addGroup(@Body() addGroupDto: AddGroupDto) {
|
async addGroup(@Body() addGroupDto: AddGroupDto) {
|
||||||
try {
|
try {
|
||||||
return await this.groupService.addGroup(addGroupDto);
|
return await this.groupService.addGroup(addGroupDto);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
throw new Error(err);
|
throw new HttpException(
|
||||||
|
error.message || 'Internal server error',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -67,25 +77,37 @@ export class GroupController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ApiBearerAuth()
|
// @ApiBearerAuth()
|
||||||
@UseGuards(JwtAuthGuard)
|
// @UseGuards(JwtAuthGuard)
|
||||||
@Put('rename')
|
@Put('rename/:groupUuid')
|
||||||
async renameGroup(@Body() renameGroupDto: RenameGroupDto) {
|
async renameGroupByUuid(
|
||||||
|
@Param('groupUuid') groupUuid: string,
|
||||||
|
@Body() renameGroupDto: RenameGroupDto,
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
return await this.groupService.renameGroup(renameGroupDto);
|
return await this.groupService.renameGroupByUuid(
|
||||||
} catch (err) {
|
groupUuid,
|
||||||
throw new Error(err);
|
renameGroupDto,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException(
|
||||||
|
error.message || 'Internal server error',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ApiBearerAuth()
|
// @ApiBearerAuth()
|
||||||
@UseGuards(JwtAuthGuard)
|
// @UseGuards(JwtAuthGuard)
|
||||||
@Delete(':groupId')
|
@Delete(':groupUuid')
|
||||||
async deleteGroup(@Param('groupId') groupId: number) {
|
async deleteGroup(@Param('groupUuid') groupUuid: string) {
|
||||||
try {
|
try {
|
||||||
return await this.groupService.deleteGroup(groupId);
|
return await this.groupService.deleteGroup(groupUuid);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
throw new Error(err);
|
throw new HttpException(
|
||||||
|
error.message || 'Internal server error',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { IsNotEmpty, IsString, IsNumberString } from 'class-validator';
|
import { IsNotEmpty, IsString, IsArray } from 'class-validator';
|
||||||
|
|
||||||
export class AddGroupDto {
|
export class AddGroupDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
@ -11,26 +11,10 @@ export class AddGroupDto {
|
|||||||
public groupName: string;
|
public groupName: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'homeId',
|
description: 'deviceUuids',
|
||||||
required: true,
|
required: true,
|
||||||
})
|
})
|
||||||
@IsNumberString()
|
@IsArray()
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
public homeId: string;
|
public deviceUuids: [string];
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'productId',
|
|
||||||
required: true,
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
public productId: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'The list of up to 20 device IDs, separated with commas (,)',
|
|
||||||
required: true,
|
|
||||||
})
|
|
||||||
@IsString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
public deviceIds: string;
|
|
||||||
}
|
}
|
||||||
|
@ -1,28 +0,0 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
|
||||||
import { IsNotEmpty, IsNumberString } from 'class-validator';
|
|
||||||
|
|
||||||
export class GetGroupDto {
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'homeId',
|
|
||||||
required: true,
|
|
||||||
})
|
|
||||||
@IsNumberString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
public homeId: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'pageSize',
|
|
||||||
required: true,
|
|
||||||
})
|
|
||||||
@IsNumberString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
public pageSize: number;
|
|
||||||
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'pageNo',
|
|
||||||
required: true,
|
|
||||||
})
|
|
||||||
@IsNumberString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
public pageNo: number;
|
|
||||||
}
|
|
@ -1,15 +1,7 @@
|
|||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import { IsNotEmpty, IsString, IsNumberString } from 'class-validator';
|
import { IsNotEmpty, IsString } from 'class-validator';
|
||||||
|
|
||||||
export class RenameGroupDto {
|
export class RenameGroupDto {
|
||||||
@ApiProperty({
|
|
||||||
description: 'groupId',
|
|
||||||
required: true,
|
|
||||||
})
|
|
||||||
@IsNumberString()
|
|
||||||
@IsNotEmpty()
|
|
||||||
public groupId: string;
|
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'groupName',
|
description: 'groupName',
|
||||||
required: true,
|
required: true,
|
||||||
|
@ -2,10 +2,26 @@ import { Module } from '@nestjs/common';
|
|||||||
import { GroupService } from './services/group.service';
|
import { GroupService } from './services/group.service';
|
||||||
import { GroupController } from './controllers/group.controller';
|
import { GroupController } from './controllers/group.controller';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { GroupRepositoryModule } from '@app/common/modules/group/group.repository.module';
|
||||||
|
import { GroupRepository } from '@app/common/modules/group/repositories';
|
||||||
|
import { GroupDeviceRepositoryModule } from '@app/common/modules/group-device/group.device.repository.module';
|
||||||
|
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||||
|
import { DeviceRepositoryModule } from '@app/common/modules/device';
|
||||||
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule],
|
imports: [
|
||||||
|
ConfigModule,
|
||||||
|
GroupRepositoryModule,
|
||||||
|
GroupDeviceRepositoryModule,
|
||||||
|
DeviceRepositoryModule,
|
||||||
|
],
|
||||||
controllers: [GroupController],
|
controllers: [GroupController],
|
||||||
providers: [GroupService],
|
providers: [
|
||||||
|
GroupService,
|
||||||
|
GroupRepository,
|
||||||
|
GroupDeviceRepository,
|
||||||
|
DeviceRepository,
|
||||||
|
],
|
||||||
exports: [GroupService],
|
exports: [GroupService],
|
||||||
})
|
})
|
||||||
export class GroupModule {}
|
export class GroupModule {}
|
||||||
|
@ -1,25 +1,15 @@
|
|||||||
export class GetGroupDetailsInterface {
|
export interface GetGroupDetailsInterface {
|
||||||
result: {
|
groupUuid: string;
|
||||||
id: string;
|
groupName: string;
|
||||||
name: string;
|
createdAt: Date;
|
||||||
};
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
export class GetGroupsInterface {
|
export interface GetGroupsBySpaceUuidInterface {
|
||||||
result: {
|
groupUuid: string;
|
||||||
count: number;
|
groupName: string;
|
||||||
data_list: [];
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class addGroupInterface {
|
export interface controlGroupInterface {
|
||||||
success: boolean;
|
|
||||||
msg: string;
|
|
||||||
result: {
|
|
||||||
id: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export class controlGroupInterface {
|
|
||||||
success: boolean;
|
success: boolean;
|
||||||
result: boolean;
|
result: boolean;
|
||||||
msg: string;
|
msg: string;
|
||||||
|
@ -1,21 +1,30 @@
|
|||||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
import {
|
||||||
|
Injectable,
|
||||||
|
HttpException,
|
||||||
|
HttpStatus,
|
||||||
|
BadRequestException,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { AddGroupDto } from '../dtos/add.group.dto';
|
import { AddGroupDto } from '../dtos/add.group.dto';
|
||||||
import {
|
import {
|
||||||
GetGroupDetailsInterface,
|
GetGroupDetailsInterface,
|
||||||
GetGroupsInterface,
|
GetGroupsBySpaceUuidInterface,
|
||||||
addGroupInterface,
|
|
||||||
controlGroupInterface,
|
controlGroupInterface,
|
||||||
} from '../interfaces/get.group.interface';
|
} from '../interfaces/get.group.interface';
|
||||||
import { GetGroupDto } from '../dtos/get.group.dto';
|
|
||||||
import { ControlGroupDto } from '../dtos/control.group.dto';
|
import { ControlGroupDto } from '../dtos/control.group.dto';
|
||||||
import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
import { RenameGroupDto } from '../dtos/rename.group.dto copy';
|
||||||
|
import { GroupRepository } from '@app/common/modules/group/repositories';
|
||||||
|
import { GroupDeviceRepository } from '@app/common/modules/group-device/repositories';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class GroupService {
|
export class GroupService {
|
||||||
private tuya: TuyaContext;
|
private tuya: TuyaContext;
|
||||||
constructor(private readonly configService: ConfigService) {
|
constructor(
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
private readonly groupRepository: GroupRepository,
|
||||||
|
private readonly groupDeviceRepository: GroupDeviceRepository,
|
||||||
|
) {
|
||||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||||
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
|
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
|
||||||
// const clientId = this.configService.get<string>('auth-config.CLIENT_ID');
|
// const clientId = this.configService.get<string>('auth-config.CLIENT_ID');
|
||||||
@ -26,86 +35,83 @@ export class GroupService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async getGroupsByHomeId(getGroupDto: GetGroupDto) {
|
async getGroupsBySpaceUuid(
|
||||||
|
spaceUuid: string,
|
||||||
|
): Promise<GetGroupsBySpaceUuidInterface[]> {
|
||||||
try {
|
try {
|
||||||
const response = await this.getGroupsTuya(getGroupDto);
|
const groupDevices = await this.groupDeviceRepository.find({
|
||||||
|
relations: ['group', 'device'],
|
||||||
const groups = response.result.data_list.map((group: any) => ({
|
where: {
|
||||||
groupId: group.id,
|
device: { spaceUuid },
|
||||||
groupName: group.name,
|
isActive: true,
|
||||||
}));
|
|
||||||
|
|
||||||
return {
|
|
||||||
count: response.result.count,
|
|
||||||
groups: groups,
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Error fetching groups',
|
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getGroupsTuya(getGroupDto: GetGroupDto): Promise<GetGroupsInterface> {
|
|
||||||
try {
|
|
||||||
const path = `/v2.0/cloud/thing/group`;
|
|
||||||
const response = await this.tuya.request({
|
|
||||||
method: 'GET',
|
|
||||||
path,
|
|
||||||
query: {
|
|
||||||
space_id: getGroupDto.homeId,
|
|
||||||
page_size: getGroupDto.pageSize,
|
|
||||||
page_no: getGroupDto.pageNo,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return response as unknown as GetGroupsInterface;
|
|
||||||
|
// Extract and return only the group entities
|
||||||
|
const groups = groupDevices.map((groupDevice) => {
|
||||||
|
return {
|
||||||
|
groupUuid: groupDevice.uuid,
|
||||||
|
groupName: groupDevice.group.groupName,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
if (groups.length > 0) {
|
||||||
|
return groups;
|
||||||
|
} else {
|
||||||
|
throw new HttpException(
|
||||||
|
'this space has no groups',
|
||||||
|
HttpStatus.NOT_FOUND,
|
||||||
|
);
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
'Error fetching groups ',
|
error.message || 'Error fetching groups',
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async addGroup(addGroupDto: AddGroupDto) {
|
async addGroup(addGroupDto: AddGroupDto) {
|
||||||
const response = await this.addGroupTuya(addGroupDto);
|
try {
|
||||||
|
const group = await this.groupRepository.save({
|
||||||
|
groupName: addGroupDto.groupName,
|
||||||
|
});
|
||||||
|
|
||||||
if (response.success) {
|
const groupDevicePromises = addGroupDto.deviceUuids.map(
|
||||||
return {
|
async (deviceUuid) => {
|
||||||
success: true,
|
await this.saveGroupDevice(group.uuid, deviceUuid);
|
||||||
groupId: response.result.id,
|
},
|
||||||
};
|
);
|
||||||
} else {
|
|
||||||
|
await Promise.all(groupDevicePromises);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === '23505') {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
response.msg || 'Unknown error',
|
'User already belongs to this group',
|
||||||
HttpStatus.BAD_REQUEST,
|
HttpStatus.BAD_REQUEST,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
async addGroupTuya(addGroupDto: AddGroupDto): Promise<addGroupInterface> {
|
|
||||||
try {
|
|
||||||
const path = `/v2.0/cloud/thing/group`;
|
|
||||||
const response = await this.tuya.request({
|
|
||||||
method: 'POST',
|
|
||||||
path,
|
|
||||||
body: {
|
|
||||||
space_id: addGroupDto.homeId,
|
|
||||||
name: addGroupDto.groupName,
|
|
||||||
product_id: addGroupDto.productId,
|
|
||||||
device_ids: addGroupDto.deviceIds,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return response as addGroupInterface;
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
'Error adding group',
|
err.message || 'Internal Server Error',
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async saveGroupDevice(groupUuid: string, deviceUuid: string) {
|
||||||
|
try {
|
||||||
|
await this.groupDeviceRepository.save({
|
||||||
|
group: {
|
||||||
|
uuid: groupUuid,
|
||||||
|
},
|
||||||
|
device: {
|
||||||
|
uuid: deviceUuid,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async controlGroup(controlGroupDto: ControlGroupDto) {
|
async controlGroup(controlGroupDto: ControlGroupDto) {
|
||||||
const response = await this.controlGroupTuya(controlGroupDto);
|
const response = await this.controlGroupTuya(controlGroupDto);
|
||||||
|
|
||||||
@ -141,105 +147,76 @@ export class GroupService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async renameGroup(renameGroupDto: RenameGroupDto) {
|
async renameGroupByUuid(
|
||||||
const response = await this.renameGroupTuya(renameGroupDto);
|
groupUuid: string,
|
||||||
|
|
||||||
if (response.success) {
|
|
||||||
return {
|
|
||||||
success: response.success,
|
|
||||||
result: response.result,
|
|
||||||
msg: response.msg,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
throw new HttpException(
|
|
||||||
response.msg || 'Unknown error',
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async renameGroupTuya(
|
|
||||||
renameGroupDto: RenameGroupDto,
|
renameGroupDto: RenameGroupDto,
|
||||||
): Promise<controlGroupInterface> {
|
): Promise<GetGroupsBySpaceUuidInterface> {
|
||||||
try {
|
try {
|
||||||
const path = `/v2.0/cloud/thing/group/${renameGroupDto.groupId}/${renameGroupDto.groupName}`;
|
await this.groupRepository.update(
|
||||||
const response = await this.tuya.request({
|
{ uuid: groupUuid },
|
||||||
method: 'PUT',
|
{ groupName: renameGroupDto.groupName },
|
||||||
path,
|
);
|
||||||
|
|
||||||
|
// Fetch the updated floor
|
||||||
|
const updatedGroup = await this.groupRepository.findOneOrFail({
|
||||||
|
where: { uuid: groupUuid },
|
||||||
});
|
});
|
||||||
|
|
||||||
return response as controlGroupInterface;
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Error rename group',
|
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async deleteGroup(groupId: number) {
|
|
||||||
const response = await this.deleteGroupTuya(groupId);
|
|
||||||
|
|
||||||
if (response.success) {
|
|
||||||
return {
|
return {
|
||||||
success: response.success,
|
groupUuid: updatedGroup.uuid,
|
||||||
result: response.result,
|
groupName: updatedGroup.groupName,
|
||||||
msg: response.msg,
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
throw new HttpException(
|
|
||||||
response.msg || 'Unknown error',
|
|
||||||
HttpStatus.BAD_REQUEST,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async deleteGroupTuya(groupId: number): Promise<controlGroupInterface> {
|
|
||||||
try {
|
|
||||||
const path = `/v2.0/cloud/thing/group/${groupId}`;
|
|
||||||
const response = await this.tuya.request({
|
|
||||||
method: 'DELETE',
|
|
||||||
path,
|
|
||||||
});
|
|
||||||
|
|
||||||
return response as controlGroupInterface;
|
|
||||||
} catch (error) {
|
|
||||||
throw new HttpException(
|
|
||||||
'Error delete group',
|
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getGroupsByGroupId(groupId: number) {
|
|
||||||
try {
|
|
||||||
const response = await this.getGroupsByGroupIdTuya(groupId);
|
|
||||||
|
|
||||||
return {
|
|
||||||
groupId: response.result.id,
|
|
||||||
groupName: response.result.name,
|
|
||||||
};
|
};
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException('Group not found', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteGroup(groupUuid: string) {
|
||||||
|
try {
|
||||||
|
const group = await this.getGroupsByGroupUuid(groupUuid);
|
||||||
|
|
||||||
|
if (!group) {
|
||||||
|
throw new HttpException('Group not found', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.groupRepository.update(
|
||||||
|
{ uuid: groupUuid },
|
||||||
|
{ isActive: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
return { message: 'Group deleted successfully' };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
'Error fetching group',
|
error.message || 'Error deleting group',
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getGroupsByGroupIdTuya(
|
async getGroupsByGroupUuid(
|
||||||
groupId: number,
|
groupUuid: string,
|
||||||
): Promise<GetGroupDetailsInterface> {
|
): Promise<GetGroupDetailsInterface> {
|
||||||
try {
|
try {
|
||||||
const path = `/v2.0/cloud/thing/group/${groupId}`;
|
const group = await this.groupRepository.findOne({
|
||||||
const response = await this.tuya.request({
|
where: {
|
||||||
method: 'GET',
|
uuid: groupUuid,
|
||||||
path,
|
isActive: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
return response as GetGroupDetailsInterface;
|
if (!group) {
|
||||||
} catch (error) {
|
throw new BadRequestException('Invalid group UUID');
|
||||||
throw new HttpException(
|
}
|
||||||
'Error fetching group ',
|
return {
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
groupUuid: group.uuid,
|
||||||
);
|
groupName: group.groupName,
|
||||||
|
createdAt: group.createdAt,
|
||||||
|
updatedAt: group.updatedAt,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof BadRequestException) {
|
||||||
|
throw err; // Re-throw BadRequestException
|
||||||
|
} else {
|
||||||
|
throw new HttpException('Group not found', HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
71
src/guards/device.product.guard.ts
Normal file
71
src/guards/device.product.guard.ts
Normal 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',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user