Skip to content

Commit

Permalink
Add months and latest months from DB
Browse files Browse the repository at this point in the history
  • Loading branch information
ruchernchong committed Jun 16, 2024
1 parent fd92a41 commit 4777af4
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 15 deletions.
18 changes: 18 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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);
17 changes: 2 additions & 15 deletions src/lib/getCOEResultByMonth.ts
Original file line number Diff line number Diff line change
@@ -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<COEResult>("coe")
.aggregate([
{
$group: {
_id: null,
latestMonth: { $max: "$month" },
},
},
{ $sort: { month: -1 } },
{ $limit: 1 },
])
.next();

selectedMonth = latestMonthFromDb.latestMonth;
selectedMonth = await getLatestMonth("coe");
}

return db
Expand Down
19 changes: 19 additions & 0 deletions src/lib/getLatestMonth.ts
Original file line number Diff line number Diff line change
@@ -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;
};
5 changes: 5 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,8 @@ export interface UpdateParams {
zipUrl: string;
keyFields: string[];
}

export interface LatestMonth {
_id: null;
latestMonth: string;
}

0 comments on commit 4777af4

Please sign in to comment.