Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
110 changes: 93 additions & 17 deletions apps/backend/src/geocoding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,44 @@ export interface GeocodingResult {
lon: number
}

export interface CitySearchResult {
name: string
displayName: string
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'
const REQUEST_TIMEOUT_MS = 5000

interface NominatimPlace {
lat: string
lon: string
name?: string
display_name: string
address?: {
city?: string
town?: string
village?: string
municipality?: string
}
}

/**
* 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
* Looks up addresses through Nominatim. 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',
})

async function searchNominatim(
params: URLSearchParams,
): Promise<NominatimPlace[]> {
const response = await fetch(`${NOMINATIM_URL}?${params}`, {
headers: {
'User-Agent': USER_AGENT,
},
signal: AbortSignal.timeout(5000),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
})

if (!response.ok) {
Expand All @@ -40,7 +51,25 @@ export async function geocodeAddress(
})
}

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

/**
* Looks up the coordinates for a Norwegian address using Nominatim.
* Returns null when the address could not be found.
*/
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 results = await searchNominatim(params)

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

Expand All @@ -49,3 +78,50 @@ export async function geocodeAddress(
lon: Number(results[0].lon),
}
}

/**
* Searches Norwegian settlements through Nominatim. This is the fallback used
* by the admin venue form when the local city table has no match, so cities
* outside the seed data can still be used.
*/
export async function searchCities(term: string): Promise<CitySearchResult[]> {
const params = new URLSearchParams({
q: term,
format: 'jsonv2',
addressdetails: '1',
limit: '6',
featureType: 'settlement',
countrycodes: 'no',
'accept-language': 'no',
})

const results = await searchNominatim(params)
const cities = new Map<string, CitySearchResult>()

for (const result of results) {
const lat = Number(result.lat)
const lon = Number(result.lon)
const name =
result.name ??
result.address?.city ??
result.address?.town ??
result.address?.village ??
result.address?.municipality ??
result.display_name.split(',')[0]?.trim()

if (!name || !Number.isFinite(lat) || !Number.isFinite(lon)) continue

const key = name.toLocaleLowerCase('nb-NO')

if (!cities.has(key)) {
cities.set(key, {
name,
displayName: result.display_name,
lat,
lon,
})
}
}

return [...cities.values()]
}
104 changes: 98 additions & 6 deletions apps/backend/src/schema/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import type {
import { GraphQLError } from 'graphql'

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

Expand Down Expand Up @@ -50,6 +51,30 @@ builder.prismaObject('City', {
}),
})

interface CityPlace {
name: string
displayName: string
lat: number
lon: number
}

const cityPlaceRef = builder.objectRef<CityPlace>('CityPlace').implement({
fields: (t) => ({
name: t.exposeString('name'),
displayName: t.exposeString('displayName'),
lat: t.exposeFloat('lat'),
lon: t.exposeFloat('lon'),
}),
})

function requireAdmin(context: Context) {
if (context.user?.role !== 'admin') {
throw new GraphQLError('Unauthorized', {
extensions: { code: 'UNAUTHORIZED' },
})
}
}

builder.prismaObject('Review', {
fields: (t) => ({
id: t.exposeString('id'),
Expand Down Expand Up @@ -523,6 +548,19 @@ builder.queryType({
},
}),
}),
cityPlaceSearch: t.field({
type: [cityPlaceRef],
args: {
name: t.arg.string({ required: true }),
},
description:
'Search Norwegian cities through Nominatim. Used by the admin form when the city is not in the database.',
resolve: (_parent, args) => {
const term = args.name.trim()

return term.length < 2 ? [] : searchCities(term)
},
}),
search: t.field({
type: [searchResultRef],
args: {
Expand Down Expand Up @@ -779,11 +817,7 @@ builder.mutationType({
}),
},
resolve: async (query, _parent, args, context) => {
if (context.user?.role !== 'admin') {
throw new GraphQLError('Unauthorized', {
extensions: { code: 'UNAUTHORIZED' },
})
}
requireAdmin(context)

const city = await prisma.city.findUnique({
where: { id: args.input.cityId },
Expand Down Expand Up @@ -834,5 +868,63 @@ builder.mutationType({
})
},
}),
findOrCreateCity: t.prismaFieldWithInput({
type: 'City',
input: {
name: t.input.string({ required: true }),
lat: t.input.float({
required: true,
description: 'Latitude of the city centre.',
}),
lon: t.input.float({
required: true,
description: 'Longitude of the city centre.',
}),
},
resolve: async (query, _parent, args, context) => {
requireAdmin(context)

const name = args.input.name.trim()
const { lat, lon } = args.input

if (!name) {
throw new GraphQLError('City name is required', {
extensions: { code: 'BAD_USER_INPUT' },
})
}

if (!Number.isFinite(lat) || lat < -90 || lat > 90) {
throw new GraphQLError('lat must be between -90 and 90', {
extensions: { code: 'BAD_USER_INPUT' },
})
}

if (!Number.isFinite(lon) || lon < -180 || lon > 180) {
throw new GraphQLError('lon must be between -180 and 180', {
extensions: { code: 'BAD_USER_INPUT' },
})
}

const existing = await prisma.city.findFirst({
where: {
name: {
equals: name,
mode: 'insensitive',
},
},
})

if (existing !== null) return existing

return prisma.city.create({
...query,
data: {
name,
centreLat: lat,
centreLon: lon,
},
})
},
}),
}),
})
102 changes: 102 additions & 0 deletions apps/backend/tests/e2e/api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,27 @@ async function query<T>(
return body.data
}

async function adminQuery<T>(
request: APIRequestContext,
document: string,
variables?: Record<string, unknown>,
): Promise<T> {
const response = await request.post('/', {
headers: { authorization: `Bearer ${adminToken()}` },
data: { query: document, variables },
})
const body: GraphQLResponse<T> = await response.json()

expect(response.status(), JSON.stringify(body)).toBe(200)
expect(body.errors).toBeUndefined()

if (body.data == null) {
throw new Error('GraphQL response did not contain data')
}

return body.data
}

test('city query returns Trondheim and its map coordinates', async ({
request,
}) => {
Expand Down Expand Up @@ -626,6 +647,87 @@ test('createPriceSighting rejects an unknown venue', async ({ request }) => {
expect(body.errors?.[0]?.message).toBe(`Unknown venue: ${unknownVenueId}`)
})

test('findOrCreateCity creates a city with coordinates and reuses it', async ({
request,
}) => {
const name = `Playwright ${randomUUID()}`
const variables = {
input: { name, lat: 59.1234, lon: 10.5678 },
}

try {
const { findOrCreateCity } = await adminQuery<{
findOrCreateCity: {
id: string
name: string
lat: number
lon: number
}
}>(
request,
`
mutation FindOrCreateCity($input: MutationFindOrCreateCityInput!) {
findOrCreateCity(input: $input) {
id
name
lat
lon
}
}
`,
variables,
)

expect(findOrCreateCity).toMatchObject({
id: expect.any(String),
name,
lat: 59.1234,
lon: 10.5678,
})

const second = await adminQuery<{
findOrCreateCity: { id: string }
}>(
request,
`
mutation FindOrCreateCity($input: MutationFindOrCreateCityInput!) {
findOrCreateCity(input: $input) {
id
}
}
`,
variables,
)

expect(second.findOrCreateCity.id).toBe(findOrCreateCity.id)

const cities = await prisma.city.findMany({ where: { name } })
expect(cities).toHaveLength(1)
} finally {
await prisma.city.deleteMany({ where: { name } })
}
})

test('findOrCreateCity requires an admin user', async ({ request }) => {
const response = await request.post('/', {
data: {
query: `
mutation {
findOrCreateCity(
input: { name: "Playwright city", lat: 59.1234, lon: 10.5678 }
) {
id
}
}
`,
},
})
const body: GraphQLResponse<unknown> = await response.json()

expect(response.status(), JSON.stringify(body)).toBe(200)
expect(body.errors?.[0]?.message).toBe('Unauthorized')
})

test('createVenue rejects an unknown city before geocoding', async ({
request,
}) => {
Expand Down
Loading
Loading