Skip to content

Commit ca93309

Browse files
committed
Better checking for start and end dates
1 parent 01402db commit ca93309

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

src/controllers/locationController.ts

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -325,14 +325,11 @@ const getLocationsForDevice = async (
325325
throw new ApiError(403, "Forbidden")
326326
}
327327

328-
const dateRange = {
329-
...(startDate ? { gte: new Date(startDate) } : {}),
330-
...(endDate ? { lte: new Date(endDate) } : {}),
331-
}
328+
const dateRange = generateDateRange(startDate, endDate)
332329

333330
const where = {
334331
device_id: deviceId,
335-
...(startDate || endDate ? { created_at: dateRange } : {}),
332+
...(dateRange ? { created_at: dateRange } : {}),
336333
}
337334

338335
if (latest === "true") {
@@ -365,15 +362,12 @@ const getLocationsForOwnedDevices = async (
365362

366363
const deviceIds = devices.map((device) => device.id)
367364

368-
const dateRange = {
369-
...(startDate ? { gte: new Date(startDate) } : {}),
370-
...(endDate ? { lte: new Date(endDate) } : {}),
371-
}
365+
const dateRange = generateDateRange(startDate, endDate)
372366

373367
const fetchLocations = async (id: bigint) => {
374368
const where = {
375369
device_id: id,
376-
...(startDate || endDate ? { created_at: dateRange } : {}),
370+
...(dateRange ? { created_at: dateRange } : {}),
377371
}
378372

379373
if (latest === "true") {
@@ -393,3 +387,26 @@ const getLocationsForOwnedDevices = async (
393387

394388
return Promise.all(deviceIds.map(fetchLocations))
395389
}
390+
391+
function generateDateRange(
392+
startDate?: string,
393+
endDate?: string,
394+
): { lte?: Date; gte?: Date } | null {
395+
const parseDate = (value?: string) => {
396+
if (!value) return null
397+
const d = new Date(value)
398+
return isNaN(d.getTime()) ? null : d
399+
}
400+
401+
const from = parseDate(startDate)
402+
const to = parseDate(endDate)
403+
404+
if (!from && !to) return null
405+
406+
const dateRange = {
407+
...(from ? { gte: from } : {}),
408+
...(to ? { lte: to } : {}),
409+
}
410+
411+
return dateRange
412+
}

0 commit comments

Comments
 (0)