Skip to content

Commit

Permalink
Update API for cars to query by month
Browse files Browse the repository at this point in the history
  • Loading branch information
Ru Chern Chong committed Dec 29, 2023
1 parent 4733bd6 commit 8b348b9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 12 deletions.
27 changes: 18 additions & 9 deletions packages/core/src/cars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ const trailingTwelveMonths = format(subMonths(today, 12), "yyyy-MM");

const getCarsByFuelType = async (
fuelType: FUEL_TYPE,
month?: string,
): Promise<CarDocument[]> => {
let cars = await db
.collection<CarDocument>("cars")
.find({ fuel_type: fuelType, month: { $gte: trailingTwelveMonths } })
.toArray();
const filter = {
fuel_type: fuelType,
month: month ?? { $gte: trailingTwelveMonths },
};

let cars = await db.collection<CarDocument>("cars").find(filter).toArray();

return cars.reduce(
(result: CarDocument[], { _id, month, make, fuel_type, number }) => {
Expand All @@ -44,10 +47,16 @@ const getCarsByFuelType = async (
);
};

export const electric = async (): Promise<CarDocument[]> =>
getCarsByFuelType(FUEL_TYPE.ELECTRIC);

export const petrol = async (): Promise<CarDocument[]> =>
getCarsByFuelType(FUEL_TYPE.PETROL);
export const electric = async ({
month,
}: {
month?: string;
}): Promise<CarDocument[]> => getCarsByFuelType(FUEL_TYPE.ELECTRIC, month);

export const petrol = async ({
month,
}: {
month?: string;
}): Promise<CarDocument[]> => getCarsByFuelType(FUEL_TYPE.PETROL, month);

export * as Cars from "./cars";
8 changes: 5 additions & 3 deletions packages/functions/src/cars.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { ApiHandler } from "sst/node/api";
import { ApiHandler, useQueryParam } from "sst/node/api";
import { Cars } from "@lta-cars-dataset/core/cars";
import { createResponse } from "./utils/createResponse";

export const electric = ApiHandler(async (_evt) => {
const electricCars = await Cars.electric();
const month = useQueryParam("month");
const electricCars = await Cars.electric({ month });

return createResponse(electricCars);
});

export const petrol = ApiHandler(async (_evt) => {
const petrolCars = await Cars.petrol();
const month = useQueryParam("month");
const petrolCars = await Cars.petrol({ month });

return createResponse(petrolCars);
});

0 comments on commit 8b348b9

Please sign in to comment.