Browse Source

Add measurements API route

main
Haris Razis 4 years ago
parent
commit
5cd4bdbb64
No known key found for this signature in database GPG Key ID: 86A4D290ED03FAB4
  1. 40
      server/src/class/Database.ts
  2. 2
      server/src/class/Service.ts
  3. 19
      server/src/routes/Routes.ts

40
server/src/class/Database.ts

@ -48,25 +48,29 @@ export class Database {
});
}
query(filter: string): void {
const query = `from(bucket: "${process.env.DB_BUCKET}") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "${filter}")`;
query(filter: string, timeFrame: string) {
const query = `from(bucket: "${process.env.DB_BUCKET}") |> range(start: -${timeFrame}) |> filter(fn: (r) => r._measurement == "${filter}")`;
this.queryApi.queryRows(query, {
next(row, tableMeta) {
const o = tableMeta.toObject(row);
console.log(
chalk.cyan(
`On ${o._time} took ${o._measurement} of ${o._field}=${o._value}`
)
);
},
error(error) {
console.error(error);
console.log(chalk.red('Query ERROR'));
},
complete() {
console.log(chalk.magenta('Query finished'));
},
const data = this.queryApi
.collectRows(query)
.then(async (result) => {
const formatedData = await this.formatData(result);
return formatedData;
})
.catch(() => {
return [{ Error: 'Error occured' }];
});
return data;
}
formatData(rawData: any): Array<{}> {
let formatedData: Array<{}> = [];
rawData.forEach((element: any) => {
formatedData.push({ time: element._time, value: element._value });
});
return formatedData;
}
}

2
server/src/class/Service.ts

@ -3,7 +3,7 @@ import { Database } from './Database';
import { Socket } from './Socket';
export class Service {
private database!: Database;
database!: Database;
socket!: Socket<Express.Application>;
constructor(private http: Server) {

19
server/src/routes/Routes.ts

@ -1,4 +1,5 @@
import * as express from 'express';
import { Database } from '../class/Database';
import { Service } from '../class/Service';
export class Routes {
@ -12,6 +13,7 @@ export class Routes {
private devices(): void {
this.app.get('/devices', async (req, res) => {
const data = await this.service.socket.rooms;
res.header('Content-Type', 'application/json');
if (data) {
res.send(JSON.stringify(data));
@ -35,6 +37,22 @@ export class Routes {
});
}
private measurements(): void {
this.app.get('/measurements', async (req, res) => {
req.on('data', async (data) => {
const { filter, timeFrame } = JSON.parse(data);
const points = await this.service.database.query('temperature', '5m');
res.header('Content-Type', 'application/json');
if (points) {
res.send(JSON.stringify(points));
} else {
res.send(JSON.stringify({}));
}
});
});
}
private socket(): void {
this.app.post('/socket', (req, res) => {
req.on('data', async (data) => {
@ -54,6 +72,7 @@ export class Routes {
public routes(): void {
this.devices();
this.measurements();
this.socket();
}
}

Loading…
Cancel
Save