2019-05-29 10:35:10 +00:00
"use strict" ;
class GatewayRepo {
2019-07-09 13:05:42 +00:00
constructor ( { database } ) {
this . db = database ;
2019-05-29 10:35:10 +00:00
}
add ( ... gateways ) {
2019-07-10 13:32:58 +00:00
const statement = this . db . prepare ( ` INSERT INTO gateways (
id ,
latitude , longitude ,
altitude
) VALUES (
: id ,
: latitude , : longitude ,
: altitude
) ` );
2019-05-29 10:35:10 +00:00
for ( let gateway of gateways )
2019-07-10 13:32:58 +00:00
statement . run ( gateway ) ;
2019-05-29 10:35:10 +00:00
}
2019-07-10 11:21:38 +00:00
/ * *
* 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 ;
}
2019-08-06 12:18:40 +00:00
/ * *
* 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 .
* /
2019-07-29 13:17:28 +00:00
get _by _id ( id ) {
return this . db . prepare ( ` SELECT * FROM gateways WHERE id = :id ` ) . get ( { id } ) ;
}
2019-07-10 11:21:38 +00:00
/ * *
* Iterates over all the gateways in the table .
* TODO : Use Symbol . iterator here ?
* @ return { Generator } A generator that can be used with for . . of
* /
2019-05-29 10:35:10 +00:00
iterate ( ) {
return this . db . prepare ( ` SELECT * FROM gateways ` ) . iterate ( ) ;
}
2019-08-06 12:18:40 +00:00
/ * *
* 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
} ;
}
2019-05-29 10:35:10 +00:00
}
2019-05-29 10:36:36 +00:00
export default GatewayRepo ;