Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions apps/backend/src/schema/price-sightings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,22 @@ export function latestPriceSightings<T extends PriceSightingLike>(
return sightings.filter((sighting) => latest.has(sighting))
}

export function latestUnlimitedSighting<T extends PriceSightingLike>(
sightings: T[],
): T | null {
return sightings.reduce<T | null>((latest, sighting) => {
if (sighting.limitation.length > 0) {
return latest
}

if (latest === null || sighting.timeSighted > latest.timeSighted) {
return sighting
}

return latest
}, null)
}

function sightingKey(sighting: PriceSightingLike): string {
const category = [...sighting.limitation].sort().join('+')

Expand Down
153 changes: 143 additions & 10 deletions apps/backend/src/schema/schema.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
import { prisma } from '@t09-project-2/db'
import type { OpeningHours, PriceSighting } from '@t09-project-2/db'

import { builder } from '../builder.js'
import { latestPriceSightings } from './price-sightings.js'
import {
latestPriceSightings,
latestUnlimitedSighting,
} from './price-sightings.js'
import type { VenueWithPriceSightings } from './price-sightings.js'

builder.prismaObject('Venue', {
fields: (t) => ({
id: t.exposeString('id'),
name: t.exposeString('name'),
address: t.exposeString('address'),
lat: t.exposeFloat('lat'),
lon: t.exposeFloat('lon'),
openingHours: t.relation('openingHours'),
city: t.relation('city'),
pricesSighted: t.relation('pricesSighted'),
}),
})

builder.prismaObject('OpeningHours', {
const openingHoursRef = builder.prismaObject('OpeningHours', {
fields: (t) => ({
days: t.exposeStringList('days'),
opening: t.expose('opening', { type: 'DateTime' }),
Expand All @@ -32,7 +38,7 @@ builder.prismaObject('City', {
}),
})

builder.prismaObject('PriceSighting', {
const priceSightingRef = builder.prismaObject('PriceSighting', {
select: {
size: true,
sizeMl: true,
Expand All @@ -53,20 +59,147 @@ builder.prismaObject('PriceSighting', {
}),
})

type SearchResultItem = {
type: 'venue' | 'city'
name: string
lat: number
lon: number
address: string | null
openingHours: OpeningHours[] | null
latestPriceSighting: PriceSighting | null
}

const searchResultRef = builder
.objectRef<SearchResultItem>('SearchResult')
.implement({
fields: (t) => ({
type: t.exposeString('type'),
name: t.exposeString('name'),
lat: t.exposeFloat('lat'),
lon: t.exposeFloat('lon'),
address: t.exposeString('address', { nullable: true }),
openingHours: t.expose('openingHours', {
type: [openingHoursRef],
nullable: { list: true, items: false },
}),
latestPriceSighting: t.expose('latestPriceSighting', {
type: priceSightingRef,
nullable: true,
}),
}),
})

function applyLatestPriceSightings(venues: VenueWithPriceSightings[]) {
for (const venue of venues) {
if (venue.pricesSighted) {
venue.pricesSighted = latestPriceSightings(venue.pricesSighted)
}
}
}

builder.queryType({
fields: (t) => ({
venue: t.prismaField({
type: ['Venue'],
resolve: async (query) => {
const venues = await prisma.venue.findMany({ ...query })
args: {
lat: t.arg.float(),
lon: t.arg.float(),
},
resolve: async (query, _parent, args) => {
if (args.lat == null || args.lon == null) {
const venues = await prisma.venue.findMany({ ...query })

for (const venue of venues as VenueWithPriceSightings[]) {
if (venue.pricesSighted) {
venue.pricesSighted = latestPriceSightings(venue.pricesSighted)
}
applyLatestPriceSightings(venues as VenueWithPriceSightings[])

return venues
}

return venues
const nearest = await prisma.$queryRaw<{ id: string }[]>`
SELECT id FROM venue
ORDER BY haversine_distance(${args.lat}, ${args.lon}, lat, lon), name
`

const venues = await prisma.venue.findMany({
...query,
where: { id: { in: nearest.map((venue) => venue.id) } },
})

const byId = new Map(venues.map((venue) => [venue.id, venue] as const))

const sorted = nearest.flatMap((row) => {
const venue = byId.get(row.id)
return venue ? [venue] : []
})

applyLatestPriceSightings(sorted as VenueWithPriceSightings[])

return sorted
},
}),
city: t.prismaField({
type: ['City'],
args: {
name: t.arg.string({ required: true }),
},
resolve: (query, _parent, args) =>
prisma.city.findMany({
...query,
where: {
name: {
contains: args.name,
mode: 'insensitive',
},
},
}),
}),
search: t.field({
type: [searchResultRef],
args: {
term: t.arg.string({ required: true }),
},
resolve: async (_parent, args) => {
const contains = {
contains: args.term,
mode: 'insensitive' as const,
}

const [venues, cities] = await Promise.all([
prisma.venue.findMany({
where: {
OR: [{ name: contains }, { address: contains }],
},
include: {
openingHours: true,
pricesSighted: true,
},
orderBy: { name: 'asc' },
}),
prisma.city.findMany({
where: { name: contains },
orderBy: { name: 'asc' },
}),
])

return [
...venues.map((venue) => ({
type: 'venue' as const,
name: venue.name,
lat: venue.lat,
lon: venue.lon,
address: venue.address,
openingHours: venue.openingHours,
latestPriceSighting: latestUnlimitedSighting(venue.pricesSighted),
})),
...cities.map((city) => ({
type: 'city' as const,
name: city.name,
lat: city.centreLat,
lon: city.centreLon,
address: null,
openingHours: null,
latestPriceSighting: null,
})),
]
},
}),
}),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
Warnings:
- Added the required column `lat` to the `venue` table without a default value. This is not possible if the table is not empty.
- Added the required column `lon` to the `venue` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "venue" ADD COLUMN "lat" DOUBLE PRECISION NOT NULL,
ADD COLUMN "lon" DOUBLE PRECISION NOT NULL;
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- CreateFunction
CREATE FUNCTION haversine_distance(
lat1 double precision,
lon1 double precision,
lat2 double precision,
lon2 double precision
) RETURNS double precision
LANGUAGE sql
IMMUTABLE
PARALLEL SAFE
AS $$
SELECT 2 * 6371000 * asin(
sqrt(
power(sin(radians(lat2 - lat1) / 2), 2) +
cos(radians(lat1)) * cos(radians(lat2)) * power(sin(radians(lon2 - lon1) / 2), 2)
)
);
$$;
2 changes: 2 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ model Venue {
id String @id @default(dbgenerated("uuidv7()")) @db.Uuid
name String
address String
lat Float
lon Float
openingHours OpeningHours[]
Expand Down
12 changes: 12 additions & 0 deletions packages/db/prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ async function main() {
{
name: 'Den Gode Nabo',
address: 'Øvre Bakklandet 69',
lat: 63.4295,
lon: 10.3966,
openingHours: {
create: [
{
Expand Down Expand Up @@ -67,6 +69,8 @@ async function main() {
{
name: 'Skjenkestua',
address: 'Nedre Bakklandet 24',
lat: 63.4292,
lon: 10.3959,
openingHours: {
create: [
{
Expand Down Expand Up @@ -101,6 +105,8 @@ async function main() {
{
name: 'Baklandet Skydsstation',
address: 'Øvre Bakklandet 33',
lat: 63.4291,
lon: 10.3962,
openingHours: {
create: [
{
Expand Down Expand Up @@ -130,6 +136,8 @@ async function main() {
{
name: 'Trondheim Torg Pub',
address: 'Olav Tryggvasons gate 6',
lat: 63.4302,
lon: 10.3948,
openingHours: {
create: [
{
Expand Down Expand Up @@ -179,6 +187,8 @@ async function main() {
{
name: 'The Dubliner Folk Pub',
address: 'Rådhusgata 13',
lat: 59.9114,
lon: 10.7405,
openingHours: {
create: [
{
Expand Down Expand Up @@ -210,6 +220,8 @@ async function main() {
{
name: 'Tilt',
address: 'Øvre Slottsgate 6',
lat: 59.9139,
lon: 10.7432,
openingHours: {
create: [
{
Expand Down
1 change: 1 addition & 0 deletions packages/db/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { getDatabaseUrl } from './database-url.js'
export { prisma } from './client.js'
export { PrismaClient } from './generated/prisma/client.js'
export type { OpeningHours, PriceSighting } from './generated/prisma/client.js'
export type { default as PrismaTypes } from './generated/pothos-types.js'
export { getDatamodel } from './generated/pothos-types.js'