import {Controller, Delete, Get, HttpException, Param, Res} from '@nestjs/common'; import {DbService} from '../db/db.service'; import * as crypto from 'crypto'; import {CloudService} from '../cloud/cloud.service'; import {Response} from 'express'; @Controller('client') export class ClientController { constructor( private readonly db: DbService, private readonly cloudService: CloudService ) { } @Get('devices') async devices() { const devices = await this.db.get(); return devices.map(device => JSON.parse(device)); } @Get('devices/completed') completed() { return this.db.completed(); } @Get('logs/:sn') async log(@Param('sn') sn: string) { const hash = crypto.createHash('md5').update(sn).digest('hex'); const logs = await this.db.logs(hash); return Object.entries(logs) .map(([key, value]) => ({type: key, ...JSON.parse(String(value))})) .sort((a: any, b: any) => a.time - b.time); } /** * Delete log for a specific device * @param sn */ @Delete('delete/:sn') delete(@Param('sn') sn: string) { const hash = crypto.createHash('md5').update(sn).digest('hex'); return this.db.delete(hash); } @Delete('delete/device/:sn') async deleteDevice( @Param('sn') sn: string, @Res() res: Response ) { const hash = crypto.createHash('md5').update(sn).digest('hex'); try { const deviceId = await this.db.getDevice(hash); if (deviceId) { await this.cloudService.deleteDevice(Number(deviceId)); } await this.delete(sn); res.status(204).send(); return {sn}; } catch (error) { throw new HttpException(error.data, error.status); } } }