Files
Livebeat/backend/endpoints/beat.ts

56 lines
2.4 KiB
TypeScript

import { Response } from "express";
import { LivebeatRequest } from "../lib/request";
import { IBeat } from "../models/beat/beat.interface";
import { Beat } from "../models/beat/beat.model.";
import { Phone } from "../models/phone/phone.model";
export async function GetBeat(req: LivebeatRequest, res: Response) {
const from: number = Number(req.query.from);
const to: number = Number(req.query.to);
const preset: string = req.query.preset as string;
const phoneId = req.query.phoneId;
const phone = req.query.phone === undefined ? await Phone.findOne({ user: req.user?._id }) : await Phone.findOne({ _id: phoneId, user: req.user?._id });
let beats: IBeat[] = []
if (phone !== null) {
// If the battery preset is chosen, we only return documents where the battery status changed.
if (preset === 'battery') {
// Group documents under the battery percentage.
const batteryBeats = await Beat.aggregate([
{ $group: { _id: {battery: "$battery"}, uniqueIds: { $addToSet: "$_id" } } }
]).sort({ '_id.battery': -1 }).sort({ '_id.id': -1 });
// Loop though array and grab the first document where the battery percentage changed.
for (let i = 0; i < batteryBeats.length; i++) {
const firstId = batteryBeats[i].uniqueIds[0];
const firstBeat = await Beat.findById(firstId);
if (firstBeat !== null) {
beats.push(firstBeat);
}
}
} else {
// If no preset is chosen, get latest.
beats = await Beat.find({ phone: phone._id, createdAt: { $gte: new Date((from | 0) * 1000), $lte: new Date((to | Date.now() / 1000) * 1000) } }).sort({ _id: -1 });
}
// Check time
/*for (let i = 0; i < beats.length; i++) {
const beat = beats[i];
if (!isNaN(from) && !isNaN(to)) {
if (Math.floor(beat.createdAt!.getTime() / 1000) >= new Date(from).getTime() &&
Math.floor(beat.createdAt!.getTime() / 1000) <= new Date(to).getTime()) {}
else {
console.log(`${Math.floor(beat.createdAt!.getTime() / 1000)} is not in range`);
beats.splice(i, 1);
}
}
}*/
res.status(200).send(beats);
} else {
res.status(404).send({ message: 'Phone not found' });
}
}