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
4 changes: 3 additions & 1 deletion apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@
"@pothos/plugin-with-input": "^4.1.5",
"@t09-project-2/db": "workspace:*",
"graphql": "^16.9.0",
"tsx": "^4.23.15"
"tsx": "^4.23.15",
"jsonwebtoken": "^9.0.3"
},
"devDependencies": {
"@playwright/test": "^1.64.1",
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^22.20.4",
"dotenv-cli": "^11.0.0",
"typescript": "^6.0.3"
Expand Down
1 change: 1 addition & 0 deletions apps/backend/src/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ export const builder = new SchemaBuilder<{

builder.scalarType('DateTime', {
serialize: (date: Date) => date.toISOString(),
parseValue: (value) => new Date(value as string | number | Date),
})
34 changes: 32 additions & 2 deletions apps/backend/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,40 @@
import { prisma } from '@t09-project-2/db'
import jwt from 'jsonwebtoken'
import type { PrismaClient } from '@t09-project-2/db'
import type { IncomingMessage } from 'node:http'

// In a real application, this would be a type an auth provider like Auth0
export interface User {
sub: string
iat: number
exp: number
role: 'admin' | 'user'
}

export interface Context {
prisma: PrismaClient
user: User | null
}

export function createContext(): Context {
return { prisma }
export function createContext({ req }: { req: IncomingMessage }): Context {
const authHeader = req.headers.authorization
let user: User | null = null

if (authHeader === undefined || !authHeader.startsWith('Bearer ')) {
return {
prisma,
user,
}
}

try {
const token = authHeader.split(' ')[1]
// Would not have the secret in plain text in a real prod application obviously
user = jwt.verify(token, 'secret-string', { algorithms: ['HS256'] }) as User
} catch {} // Empty catch to keep user null if the token in invalid or header is malformed

return {
prisma,
user,
}
}
51 changes: 51 additions & 0 deletions apps/backend/src/geocoding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { GraphQLError } from 'graphql'

export interface GeocodingResult {
lat: number
lon: number
}

const NOMINATIM_URL = 'https://nominatim.openstreetmap.org/search'
const USER_AGENT = process.env.NOMINATIM_USER_AGENT ?? 'T09-Project-2/1.0'

/**
* Looks up the coordinates for a Norwegian address using Nominatim.
* Returns null when the address could not be found.
*
* See https://operations.osmfoundation.org/policies/nominatim/ for the usage
* policy. In particular, requests should identify the application through the
* User-Agent header and must not be sent at a high rate.
*/
export async function geocodeAddress(
address: string,
city: string,
): Promise<GeocodingResult | null> {
const params = new URLSearchParams({
q: `${address}, ${city}`,
format: 'jsonv2',
limit: '1',
countrycodes: 'no',
})

const response = await fetch(`${NOMINATIM_URL}?${params}`, {
headers: {
'User-Agent': USER_AGENT,
},
signal: AbortSignal.timeout(5000),
})

if (!response.ok) {
throw new GraphQLError(`Geocoding failed: ${response.status}`, {
extensions: { code: 'BAD_GATEWAY' },
})
}

const results = (await response.json()) as GeocodingResult[]

if (results.length === 0) return null

return {
lat: Number(results[0].lat),
lon: Number(results[0].lon),
}
}
2 changes: 1 addition & 1 deletion apps/backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const port = Number(process.env.PORT ?? 3001)

const { url } = await startStandaloneServer(server, {
listen: { port },
context: async () => createContext(),
context: async ({ req }) => createContext({ req }),
})

console.log(`GraphQL server ready at ${url}`)
184 changes: 183 additions & 1 deletion apps/backend/src/schema/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
import { GraphQLError } from 'graphql'

import { builder } from '../builder.js'
import { geocodeAddress } from '../geocoding.js'
import { latestPriceSightings } from './price-sightings.js'
import type { VenueWithPriceSightings } from './price-sightings.js'

Expand Down Expand Up @@ -62,6 +63,7 @@ builder.prismaObject('Review', {

const priceSightingRef = builder.prismaObject('PriceSighting', {
select: {
id: true,
size: true,
sizeMl: true,
limitation: true,
Expand All @@ -70,6 +72,7 @@ const priceSightingRef = builder.prismaObject('PriceSighting', {
timeSighted: true,
},
fields: (t) => ({
id: t.exposeString('id'),
timeSighted: t.expose('timeSighted', { type: 'DateTime' }),
venue: t.relation('venue'),
price: t.exposeFloat('price'),
Expand All @@ -86,11 +89,34 @@ const glassSizeRef = builder.enumType('GlassSize', {
PINT: { value: GlassSize.PINT },
HALF_LITER: { value: GlassSize.HALF_LITER },
QUARTER_LITER: { value: GlassSize.QUARTER_LITER },
BOX: { value: GlassSize.BOX },
CAN: { value: GlassSize.CAN },
OTHER: { value: GlassSize.OTHER },
},
})

const dayRef = builder.enumType('Day', {
values: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] as const,
})

const limitationsRef = builder.enumType('Limitations', {
values: ['TIME', 'MEMBERSHIP'] as const,
})

const openingHoursInputRef = builder.inputType('OpeningHoursInput', {
fields: (t) => ({
days: t.field({ type: [dayRef], required: true }),
opening: t.field({ type: 'DateTime', required: true }),
closing: t.field({ type: 'DateTime', required: true }),
}),
})

const openingHoursNoteInputRef = builder.inputType('OpeningHoursNoteInput', {
fields: (t) => ({
days: t.field({ type: [dayRef], required: true }),
note: t.string({ required: true }),
}),
})

type SearchResultItem = {
id: string
cityId: string | null
Expand Down Expand Up @@ -652,5 +678,161 @@ builder.mutationType({
},
}),
}),
createPriceSighting: t.prismaFieldWithInput({
type: 'PriceSighting',
input: {
venueId: t.input.string({ required: true }),
price: t.input.float({
required: true,
description: 'Price in NOK.',
}),
size: t.input.field({ type: glassSizeRef, required: true }),
sizeMl: t.input.float({
description: 'Serving size in millilitres, when known.',
}),
limitation: t.input.field({
type: [limitationsRef],
required: false,
description: 'Defaults to no limitations.',
}),
timeStart: t.input.field({
type: 'DateTime',
description: 'Start of the time-limited offer. Requires TIME.',
}),
timeEnd: t.input.field({
type: 'DateTime',
description: 'End of the time-limited offer. Requires TIME.',
}),
},
resolve: async (query, _parent, args) => {
const { venueId, price, size, sizeMl, timeStart, timeEnd } = args.input
const limitation = args.input.limitation ?? []

if (!Number.isFinite(price) || price <= 0) {
throw new GraphQLError('Price must be greater than 0', {
extensions: { code: 'BAD_USER_INPUT' },
})
}

if (sizeMl != null && (!Number.isFinite(sizeMl) || sizeMl <= 0)) {
throw new GraphQLError('sizeMl must be greater than 0', {
extensions: { code: 'BAD_USER_INPUT' },
})
}

const hasTimeLimit = limitation.includes('TIME')

if (hasTimeLimit !== (timeStart != null && timeEnd != null)) {
throw new GraphQLError(
'timeStart and timeEnd are required when limitation includes TIME, and must otherwise be omitted',
{ extensions: { code: 'BAD_USER_INPUT' } },
)
}

const venue = await prisma.venue.findUnique({
where: { id: venueId },
select: { id: true },
})

if (venue === null) {
throw new GraphQLError(`Unknown venue: ${venueId}`, {
extensions: { code: 'BAD_USER_INPUT' },
})
}

return prisma.priceSighting.create({
...query,
data: {
venue: { connect: { id: venueId } },
price,
size,
sizeMl: sizeMl ?? null,
limitation: [...limitation],
timeStart: timeStart ?? null,
timeEnd: timeEnd ?? null,
timeSighted: new Date(),
},
})
},
}),
createVenue: t.prismaFieldWithInput({
type: 'Venue',
input: {
name: t.input.string({ required: true }),
address: t.input.string({
required: true,
description:
'Street address used to look up the venue coordinates with Nominatim.',
}),
cityId: t.input.string({
required: true,
description:
'ID of an existing city, for example from the city search.',
}),
openingHours: t.input.field({
type: [openingHoursInputRef],
required: false,
}),
openingHoursNotes: t.input.field({
type: [openingHoursNoteInputRef],
required: false,
}),
},
resolve: async (query, _parent, args, context) => {
if (context.user?.role !== 'admin') {
throw new GraphQLError('Unauthorized', {
extensions: { code: 'UNAUTHORIZED' },
})
}

const city = await prisma.city.findUnique({
where: { id: args.input.cityId },
select: { id: true, name: true },
})

if (city === null) {
throw new GraphQLError(`Unknown city: ${args.input.cityId}`, {
extensions: { code: 'BAD_USER_INPUT' },
})
}

const coordinates = await geocodeAddress(args.input.address, city.name)

if (coordinates === null) {
throw new GraphQLError(
`Could not geocode address: ${args.input.address}`,
{ extensions: { code: 'BAD_USER_INPUT' } },
)
}

return prisma.venue.create({
...query,
data: {
name: args.input.name,
address: args.input.address,
lat: coordinates.lat,
lon: coordinates.lon,
city: { connect: { id: city.id } },
openingHours: args.input.openingHours
? {
create: args.input.openingHours.map((hours) => ({
days: [...hours.days],
opening: hours.opening,
closing: hours.closing,
})),
}
: undefined,
openingHoursNotes: args.input.openingHoursNotes
? {
create: args.input.openingHoursNotes.map((note) => ({
days: [...note.days],
note: note.note,
})),
}
: undefined,
},
})
},
}),
}),
})
Loading