Skip to content

Commit

Permalink
Add filter for beds/baths
Browse files Browse the repository at this point in the history
refs #49
  • Loading branch information
franthormel committed Aug 23, 2024
1 parent 34e841e commit 5cfd24c
Showing 1 changed file with 44 additions and 3 deletions.
47 changes: 44 additions & 3 deletions app/listings/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@

import prisma from "@/lib/db";
import { DEFAULT_LIST_FILTERS } from "./constants";
import { Listing, ListingsSearchFilters, PrismaListing } from "./types";
import {
BedsBathsOption,
Listing,
ListingsSearchFilters,
PrismaListing,
} from "./types";

const prismaListingMapper = (dbListing: PrismaListing) => {
const dbListingPrice = dbListing.prices
Expand Down Expand Up @@ -34,8 +39,6 @@ const prismaListingMapper = (dbListing: PrismaListing) => {
export async function fetchMatchedListings(
filters: ListingsSearchFilters = DEFAULT_LIST_FILTERS
): Promise<Listing[]> {
// TODO: Use beds filter values
// TODO: Use baths filter values
const prismaListings = await prisma.listing.findMany({
include: {
address: true,
Expand Down Expand Up @@ -73,5 +76,43 @@ export async function fetchMatchedListings(
},
},
});

// It is easier to filter the beds/baths values programatically rather than using Prisma's filtering API for the use case.
return prismaListings
.filter((listing) =>
bedsBathsOptionFilter(filters.beds.value, listing.beds)
)
.filter((listing) =>
bedsBathsOptionFilter(filters.baths.value, listing.baths)
)
.map(prismaListingMapper);
return prismaListings.map(prismaListingMapper);
}

function bedsBathsOptionFilter(
option: BedsBathsOption,
value: number
): boolean {
switch (option) {
case BedsBathsOption.ANY:
return true;
break;
case BedsBathsOption.ONE:
return value === 1;
break;
case BedsBathsOption.TWO:
return value === 2;
break;
case BedsBathsOption.THREE:
return value === 3;
break;
case BedsBathsOption.FOUR:
return value === 4;
break;
case BedsBathsOption.MORE_THAN_FIVE:
return value >= 5;
break;
default:
return true;
}
}

0 comments on commit 5cfd24c

Please sign in to comment.