From 25c0024cfc4789792483091ff4b673d87205eef7 Mon Sep 17 00:00:00 2001 From: Ru Chern Chong Date: Sun, 2 Jun 2024 01:49:36 +0800 Subject: [PATCH] Add group to months API --- src/index.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 84c44d4..9c9b0dc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -64,7 +64,28 @@ app.get("/vehicle-make", async (c) => { }); app.get("/months", async (c) => { - return c.json(await db.collection("cars").distinct("month")); + const group = c.req.query("group"); + const months = await db.collection("cars").distinct("month"); + + const sortedMonths = months.sort((a, b) => b.localeCompare(a)); + + if (group) { + return c.json( + sortedMonths.reduce((acc: Record, date) => { + const [year, month] = date.split("-"); + + if (!acc[year]) { + acc[year] = []; + } + + acc[year].push(month); + + return acc; + }, {}), + ); + } + + return c.json(sortedMonths); }); showRoutes(app);