LoRaWAN-Signal-Mapping/server/Repos.SQLite/GatewayRepo.mjs

76 lines
1.9 KiB
JavaScript

"use strict";
class GatewayRepo {
constructor({ database }) {
this.db = database;
}
add(...gateways) {
const statement = this.db.prepare(`INSERT INTO gateways (
id,
latitude, longitude,
altitude
) VALUES (
:id,
:latitude, :longitude,
:altitude
)`);
for(let gateway of gateways)
statement.run(gateway);
}
/**
* Determines whether a gateway exists in the dayabase with the given name.
* @param {string} id The id of the gateway.
* @return {bool} Whether a gateway with the given name exists in the database.
*/
exists(id) {
// Note that normally a count wouldn't be appropriate here just to test for existence, but it's ok because it's guaranteed that there will only ever be a single entry with a given id.
let statement = this.db.prepare(`SELECT COUNT(id) AS count
FROM gateways
WHERE id = :id`);
let count = statement.get({ id }).count;
return count > 0;
}
/**
* Returns a garteway by it's id.
* @param {string} id The id to fetcht he gateway for.
* @return {object} The information recorded about the gateway with the specified id .
*/
get_by_id(id) {
return this.db.prepare(`SELECT * FROM gateways WHERE id = :id`).get({ id });
}
/**
* Iterates over all the gateways in the table.
* TODO: Use Symbol.iterator here?
* @return {Generator} A generator that can be used with for..of
*/
iterate() {
return this.db.prepare(`SELECT * FROM gateways`).iterate();
}
/**
* Returns the average location of allt he currently registered gateways.
* @return {{latitude: number, longitude: number}} The lat longg coordinates of the average location of all the gateways.
*/
get_average_location() {
let count = 0, lat_sum = 0, lng_sum = 0;
for(let gateway of this.iterate()) {
lat_sum += gateway.latitude;
lng_sum += gateway.longitude;
count++;
}
return {
latitude: lat_sum / count,
longitude: lng_sum / count
};
}
}
export default GatewayRepo;