Files
backend/src/home/services/home.service.ts
2024-03-10 22:43:02 +03:00

67 lines
2.0 KiB
TypeScript

import { HomeRepository } from './../../../libs/common/src/modules/home/repositories/home.repository';
import { HomeEntity } from './../../../libs/common/src/modules/home/entities/home.entity';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import { ConfigService } from '@nestjs/config';
import { AddHomeDto } from '../dtos';
@Injectable()
export class HomeService {
private tuya: TuyaContext;
constructor(
private readonly configService: ConfigService,
private readonly homeRepository: HomeRepository,
) {
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
// const clientId = this.configService.get<string>('auth-config.CLIENT_ID');
this.tuya = new TuyaContext({
baseUrl: 'https://openapi.tuyaeu.com',
accessKey,
secretKey,
});
}
async getHomesByUserId(userUuid: string) {
const homesData = await this.findHomes(userUuid);
return homesData;
}
async findHomes(userUuid: string) {
return await this.homeRepository.find({
where: {
userUuid: userUuid,
},
});
}
async addHome(addHomeDto: AddHomeDto) {
try {
const path = `/v2.0/cloud/space/creation`;
const data = await this.tuya.request({
method: 'POST',
path,
body: { name: addHomeDto.homeName },
});
if (data.success) {
const homeEntity = {
userUuid: addHomeDto.userUuid,
homeId: data.result,
homeName: addHomeDto.homeName,
} as HomeEntity;
const savedHome = await this.homeRepository.save(homeEntity);
return savedHome;
}
return {
success: data.success,
homeId: data.result,
};
} catch (error) {
throw new HttpException(
'Error adding home',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
}