diff --git a/src/index.ts b/src/index.ts index df41ff0..45cdb53 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,6 +10,7 @@ import { getCOEResultByMonth, groupMonthsByYear, } from "./lib"; +import { getLatestMonth } from "./lib/getLatestMonth"; import { type Car, type COEResult, FUEL_TYPE } from "./types"; const app = new Hono(); @@ -79,6 +80,23 @@ app.get("/months", async (c) => { return c.json(sortedMonths); }); +app.get("/months/latest", async (c) => { + const collection = c.req.query("collection"); + const dbCollections = ["cars", "coe"]; + + const latestMonthObj = {}; + + if (collection) { + latestMonthObj[collection] = await getLatestMonth(collection); + } else { + for (const dbCollection of dbCollections) { + latestMonthObj[dbCollection] = await getLatestMonth(dbCollection); + } + } + + return c.json(latestMonthObj); +}); + showRoutes(app); export const handler = handle(app); diff --git a/src/lib/getCOEResultByMonth.ts b/src/lib/getCOEResultByMonth.ts index 35d0428..43faeb3 100644 --- a/src/lib/getCOEResultByMonth.ts +++ b/src/lib/getCOEResultByMonth.ts @@ -1,25 +1,12 @@ import db from "../config/db"; +import { getLatestMonth } from "./getLatestMonth"; import type { COEResult } from "../types"; export const getCOEResultByMonth = async (month?: string) => { let selectedMonth = month; if (!month) { - const latestMonthFromDb = await db - .collection("coe") - .aggregate([ - { - $group: { - _id: null, - latestMonth: { $max: "$month" }, - }, - }, - { $sort: { month: -1 } }, - { $limit: 1 }, - ]) - .next(); - - selectedMonth = latestMonthFromDb.latestMonth; + selectedMonth = await getLatestMonth("coe"); } return db diff --git a/src/lib/getLatestMonth.ts b/src/lib/getLatestMonth.ts new file mode 100644 index 0000000..5d0f676 --- /dev/null +++ b/src/lib/getLatestMonth.ts @@ -0,0 +1,19 @@ +import db from "../config/db"; + +export const getLatestMonth = async (collection: string) => { + const latestMonthFromDb = await db + .collection(collection) + .aggregate([ + { + $group: { + _id: null, + latestMonth: { $max: "$month" }, + }, + }, + { $sort: { month: -1 } }, + { $limit: 1 }, + ]) + .next(); + + return latestMonthFromDb.latestMonth; +}; diff --git a/src/types/index.ts b/src/types/index.ts index 16a05b0..49a3738 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -29,3 +29,8 @@ export interface UpdateParams { zipUrl: string; keyFields: string[]; } + +export interface LatestMonth { + _id: null; + latestMonth: string; +}