Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
109 changes: 92 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,24 @@ export async function geocodeAddress(
})
}

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

/**
* Looks up the coordinates for an 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',
})

const results = await searchNominatim(params)

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

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

/**
* Searches settlements through Nominatim. This is the fallback used by the
* admin venue form for cities outside the local city table.
*/
export async function searchCities(term: string): Promise<CitySearchResult[]> {
const params = new URLSearchParams({
q: term,
format: 'jsonv2',
addressdetails: '1',
limit: '8',
featureType: 'settlement',
'accept-language': 'no,en',
})

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

// Keep same-named places in different regions/countries: the display name
// includes the administrative context that the short name omits.
const key = result.display_name.toLocaleLowerCase('nb-NO')

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

return [...cities.values()]
}
143 changes: 135 additions & 8 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 @@ -45,11 +46,49 @@ builder.prismaObject('City', {
fields: (t) => ({
id: t.exposeString('id'),
name: t.exposeString('name'),
displayName: t.exposeString('displayName', { nullable: true }),
lat: t.exposeFloat('centreLat'),
lon: t.exposeFloat('centreLon'),
}),
})

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' },
})
}
}

function distanceKm(aLat: number, aLon: number, bLat: number, bLon: number) {
const toRadians = (degrees: number) => (degrees * Math.PI) / 180
const latDelta = toRadians(bLat - aLat)
const lonDelta = toRadians(bLon - aLon)
const a =
Math.sin(latDelta / 2) ** 2 +
Math.cos(toRadians(aLat)) *
Math.cos(toRadians(bLat)) *
Math.sin(lonDelta / 2) ** 2

return 6371 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
}

builder.prismaObject('Review', {
fields: (t) => ({
id: t.exposeString('id'),
Expand Down Expand Up @@ -521,8 +560,22 @@ builder.queryType({
mode: 'insensitive',
},
},
orderBy: { name: 'asc' },
}),
}),
cityPlaceSearch: t.field({
type: [cityPlaceRef],
args: {
name: t.arg.string({ required: true }),
},
description:
'Search cities through Nominatim. Used by the admin form to find places outside the local 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,15 +832,11 @@ 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 },
select: { id: true, name: true },
select: { id: true, name: true, displayName: true },
})

if (city === null) {
Expand All @@ -796,7 +845,10 @@ builder.mutationType({
})
}

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

if (coordinates === null) {
throw new GraphQLError(
Expand Down Expand Up @@ -834,5 +886,80 @@ builder.mutationType({
})
},
}),
findOrCreateCity: t.prismaFieldWithInput({
type: 'City',
input: {
name: t.input.string({ required: true }),
displayName: t.input.string({
required: false,
description:
'Full place name from Nominatim, including region and country.',
}),
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 displayName = args.input.displayName?.trim() || null
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 candidates = await prisma.city.findMany({
where: {
name: {
equals: name,
mode: 'insensitive',
},
},
})

const normalizedDisplayName = displayName?.toLocaleLowerCase('nb-NO')
const existing =
candidates.find(
(city) =>
(normalizedDisplayName !== undefined &&
city.displayName?.toLocaleLowerCase('nb-NO') ===
normalizedDisplayName) ||
distanceKm(lat, lon, city.centreLat, city.centreLon) <= 25,
) ?? null

if (existing !== null) return existing

return prisma.city.create({
...query,
data: {
name,
displayName,
centreLat: lat,
centreLon: lon,
},
})
},
}),
}),
})
Loading
Loading