diff --git a/src/repos/Location.ts b/src/repos/Location.ts index cf99e54..345fe44 100644 --- a/src/repos/Location.ts +++ b/src/repos/Location.ts @@ -4,9 +4,23 @@ import { LocationRequest } from '../requests'; class Location { public async getHistory(query: LocationRequest): Promise<GPSPoint[]> { let apiResponse: any[] = []; + let dbQuery: any = query.toMap($db); + + if (query.userId) { + dbQuery.include = [ + { + model: $db.UserDevice(), + as: 'device', + required: true, + where: { + userId: query.userId + } + } + ]; + } try { - apiResponse = await $db.GPSData().findAll(query.toMap($db)); + apiResponse = await $db.GPSData().findAll(dbQuery); } catch (error) { throw new Error(`Error fetching data: ${error}`); } diff --git a/src/requests/LocationRequest.ts b/src/requests/LocationRequest.ts index 2383d9a..48d0e2b 100644 --- a/src/requests/LocationRequest.ts +++ b/src/requests/LocationRequest.ts @@ -4,7 +4,11 @@ import { Optional } from 'src/types'; import { Db } from 'src/db'; import { ValidationError } from '../errors'; +type Order = 'ASC' | 'DESC'; + class LocationRequest { + userId: Optional<number> = null; + deviceId: Optional<string> = null; limit: Optional<number> = 250; offset: Optional<number> = null; startDate: Optional<Date> = null; @@ -16,9 +20,26 @@ class LocationRequest { postalCode: Optional<string> = null; description: Optional<string> = null; orderBy: string = 'timestamp'; - order: string = 'DESC'; + order: Order = 'DESC'; - constructor(req: any) { + constructor(req: { + userId?: number; + deviceId?: string; + limit?: number; + offset?: number; + startDate?: Date; + endDate?: Date; + minId?: number; + maxId?: number; + country?: string; + locality?: string; + postalCode?: string; + description?: string; + orderBy?: string; + order?: string; + }) { + this.userId = req.userId; + this.deviceId = req.deviceId; this.initNumber('limit', req); this.initNumber('offset', req); this.initDate('startDate', req); @@ -30,7 +51,7 @@ class LocationRequest { this.postalCode = req.postalCode; this.description = req.description; this.orderBy = req.orderBy || this.orderBy; - this.order = req.order || this.order; + this.order = (req.order || this.order).toUpperCase() as Order; } private initNumber(key: string, req: any): void { diff --git a/src/routes/api/v1/GPSData.ts b/src/routes/api/v1/GPSData.ts index 5d88020..85f5e31 100644 --- a/src/routes/api/v1/GPSData.ts +++ b/src/routes/api/v1/GPSData.ts @@ -23,12 +23,12 @@ class GPSData extends ApiV1Route { }; @authenticate() - get = async (req: Request, res: Response) => { + get = async (req: Request, res: Response, auth: Optional<AuthInfo>) => { let query: LocationRequest try { - // TODO Limit to the points that the user has access to query = new LocationRequest(req.query); + query.userId = auth!!.user.id; } catch (error) { const e = `Error parsing query: ${error}`; console.warn(e);