Merged in feat/sw-2861-move-autocomplete-router-to-trpc-package (pull request #2417)

feat(SW-2861): Move autocomplete router to trpc package

* Apply lint rules

* Use direct imports from trpc package

* Add lint-staged config to trpc

* Move lang enum to common

* Restructure trpc package folder structure

* WIP first step

* update internal imports in trpc

* Fix most errors in scandic-web

Just 100 left...

* Move Props type out of trpc

* Fix CategorizedFilters types

* Move more schemas in hotel router

* Fix deps

* fix getNonContentstackUrls

* Fix import error

* Fix entry error handling

* Fix generateMetadata metrics

* Fix alertType enum

* Fix duplicated types

* lint:fix

* Merge branch 'master' into feat/sw-2863-move-contentstack-router-to-trpc-package

* Fix broken imports

* Move booking router to trpc package

* Move partners router to trpc package

* Move autocomplete router to trpc package

* Merge branch 'master' into feat/sw-2861-move-autocomplete-router-to-trpc-package


Approved-by: Linus Flood
This commit is contained in:
Anton Gunnarsson
2025-06-26 12:40:45 +00:00
parent 7e4ed93c97
commit 5f8ac8cdeb
29 changed files with 92 additions and 70 deletions

View File

@@ -1,10 +1,10 @@
/** Routers */
import { router } from "@scandic-hotels/trpc"
import { autocompleteRouter } from "@scandic-hotels/trpc/routers/autocomplete"
import { contentstackRouter } from "@scandic-hotels/trpc/routers/contentstack"
import { hotelsRouter } from "@scandic-hotels/trpc/routers/hotels"
import { partnerRouter } from "@scandic-hotels/trpc/routers/partners"
import { autocompleteRouter } from "./routers/autocomplete"
import { bookingRouter } from "./routers/booking"
import { navigationRouter } from "./routers/navigation"
import { userRouter } from "./routers/user"

View File

@@ -1,199 +0,0 @@
import { z } from "zod"
import { Lang } from "@scandic-hotels/common/constants/language"
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { safeProtectedServiceProcedure } from "@scandic-hotels/trpc/procedures"
import { getCityPageUrls } from "@scandic-hotels/trpc/routers/contentstack/destinationCityPage/utils"
import { getCountryPageUrls } from "@scandic-hotels/trpc/routers/contentstack/destinationCountryPage/utils"
import { getHotelPageUrls } from "@scandic-hotels/trpc/routers/contentstack/hotelPage/utils"
import {
getCitiesByCountry,
getCountries,
getLocations,
} from "@scandic-hotels/trpc/routers/hotels/utils"
import { ApiCountry, type Country } from "@scandic-hotels/trpc/types/country"
import { isDefined } from "@/server/utils"
import { filterAndCategorizeAutoComplete } from "./util/filterAndCategorizeAutoComplete"
import { mapLocationToAutoCompleteLocation } from "./util/mapLocationToAutoCompleteLocation"
import type { AutoCompleteLocation } from "./schema"
const destinationsAutoCompleteInputSchema = z.object({
query: z.string(),
selectedHotelId: z.string().optional(),
selectedCity: z.string().optional(),
lang: z.nativeEnum(Lang),
includeTypes: z.array(z.enum(["hotels", "cities", "countries"])),
})
type DestinationsAutoCompleteOutput = {
hits: {
hotels: AutoCompleteLocation[]
cities: AutoCompleteLocation[]
countries: AutoCompleteLocation[]
}
currentSelection: {
hotel: (AutoCompleteLocation & { type: "hotels" }) | null
city: (AutoCompleteLocation & { type: "cities" }) | null
}
}
export const getDestinationsAutoCompleteRoute = safeProtectedServiceProcedure
.input(destinationsAutoCompleteInputSchema)
.query(async ({ ctx, input }): Promise<DestinationsAutoCompleteOutput> => {
const lang = input.lang || ctx.lang
const locations: AutoCompleteLocation[] =
await getAutoCompleteDestinationsData({
lang,
serviceToken: ctx.serviceToken,
})
const hits = filterAndCategorizeAutoComplete({
locations: locations,
query: input.query,
includeTypes: input.includeTypes,
})
const selectedHotel = locations.find(
(location) =>
location.type === "hotels" && location.id === input.selectedHotelId
)
const selectedCity = locations.find(
(location) =>
location.type === "cities" &&
location.cityIdentifier === input.selectedCity
)
return {
hits: hits,
currentSelection: {
city: isCity(selectedCity) ? selectedCity : null,
hotel: isHotel(selectedHotel) ? selectedHotel : null,
},
}
})
function isHotel(
location: AutoCompleteLocation | null | undefined
): location is AutoCompleteLocation & { type: "hotels" } {
return !!location && location.type === "hotels"
}
function isCity(
location: AutoCompleteLocation | null | undefined
): location is AutoCompleteLocation & { type: "cities" } {
return !!location && location.type === "cities"
}
export async function getAutoCompleteDestinationsData({
lang,
serviceToken,
warmup = false,
}: {
lang: Lang
serviceToken: string
warmup?: boolean
}) {
const cacheClient = await getCacheClient()
return await cacheClient.cacheOrGet(
`autocomplete:destinations:locations:${lang}`,
async () => {
const hotelUrlsPromise = safeTry(getHotelPageUrls(lang))
const cityUrlsPromise = safeTry(getCityPageUrls(lang))
const countryUrlsPromise = safeTry(getCountryPageUrls(lang))
const countries = await getCountries({
lang: lang,
serviceToken,
})
if (!countries) {
console.error("Unable to fetch countries")
throw new Error("Unable to fetch countries")
}
const countryNames = countries.data.map((country) => country.name)
const citiesByCountry = await getCitiesByCountry({
countries: countryNames,
serviceToken: serviceToken,
lang,
})
const locations = await getLocations({
lang: lang,
serviceToken: serviceToken,
citiesByCountry: citiesByCountry,
})
const activeLocations = locations.filter((location) => {
return (
location.type === "cities" ||
(location.type === "hotels" && location.isActive)
)
})
const [hotelUrls, hotelUrlsError] = await hotelUrlsPromise
const [cityUrls, cityUrlsError] = await cityUrlsPromise
const [countryUrls, countryUrlsError] = await countryUrlsPromise
if (
hotelUrlsError ||
cityUrlsError ||
countryUrlsError ||
!hotelUrls ||
!cityUrls ||
!countryUrls
) {
console.error("Unable to fetch location URLs")
throw new Error("Unable to fetch location URLs")
}
const hotelsAndCities = activeLocations
.map((location) => {
let url: string | undefined
if (location.type === "cities") {
url = cityUrls.find(
(c) =>
c.city &&
location.cityIdentifier &&
c.city === location.cityIdentifier
)?.url
}
if (location.type === "hotels") {
url = hotelUrls.find(
(h) => h.hotelId && location.id && h.hotelId === location.id
)?.url
}
return { ...location, url }
})
.map(mapLocationToAutoCompleteLocation)
.filter(isDefined)
const countryAutoCompleteLocations = countries.data.map((country) => {
const url = countryUrls.find(
(c) =>
c.country && ApiCountry[lang][c.country as Country] === country.name
)?.url
return {
id: country.id,
name: country.name,
type: "countries",
searchTokens: [country.name],
destination: "",
url,
} satisfies AutoCompleteLocation
})
return [...hotelsAndCities, ...countryAutoCompleteLocations]
},
"1d",
{ cacheStrategy: warmup ? "fetch-then-cache" : "cache-first" }
)
}

View File

@@ -1,7 +0,0 @@
import { router } from "@scandic-hotels/trpc"
import { getDestinationsAutoCompleteRoute } from "./destinations"
export const autocompleteRouter = router({
destinations: getDestinationsAutoCompleteRoute,
})

View File

@@ -1,13 +0,0 @@
import { z } from "zod"
export const autoCompleteLocationSchema = z.object({
id: z.string(),
name: z.string(),
type: z.enum(["cities", "hotels", "countries"]),
searchTokens: z.array(z.string()),
destination: z.string(),
url: z.string().optional(),
cityIdentifier: z.string().optional(),
})
export type AutoCompleteLocation = z.infer<typeof autoCompleteLocationSchema>

View File

@@ -1,68 +0,0 @@
import { filterAutoCompleteLocations } from "./filterAutoCompleteLocations"
import type { AutoCompleteLocation } from "../schema"
export type DestinationsAutoCompleteOutput = {
hits: {
hotels: AutoCompleteLocation[]
cities: AutoCompleteLocation[]
countries: AutoCompleteLocation[]
}
currentSelection: {
hotel: (AutoCompleteLocation & { type: "hotels" }) | null
city: (AutoCompleteLocation & { type: "cities" }) | null
}
}
export function filterAndCategorizeAutoComplete({
locations,
query,
includeTypes,
}: {
locations: AutoCompleteLocation[]
query: string
includeTypes: ("cities" | "hotels" | "countries")[]
}) {
const rankedLocations = filterAutoCompleteLocations(locations, query)
const sortedCities = rankedLocations.filter(
(loc) => shouldIncludeType(includeTypes, loc) && isCity(loc)
)
const sortedHotels = rankedLocations.filter(
(loc) => shouldIncludeType(includeTypes, loc) && isHotel(loc)
)
const sortedCountries = rankedLocations.filter(
(loc) => shouldIncludeType(includeTypes, loc) && isCountry(loc)
)
return {
cities: sortedCities,
hotels: sortedHotels,
countries: sortedCountries,
}
}
function shouldIncludeType(
includedTypes: ("cities" | "hotels" | "countries")[],
location: AutoCompleteLocation
) {
return includedTypes.includes(location.type)
}
function isHotel(
location: AutoCompleteLocation | null | undefined
): location is AutoCompleteLocation & { type: "hotels" } {
return !!location && location.type === "hotels"
}
function isCountry(
location: AutoCompleteLocation | null | undefined
): location is AutoCompleteLocation & { type: "countries" } {
return !!location && location.type === "countries"
}
function isCity(
location: AutoCompleteLocation | null | undefined
): location is AutoCompleteLocation & { type: "cities" } {
return !!location && location.type === "cities"
}

View File

@@ -1,226 +0,0 @@
import { describe, expect, it } from "@jest/globals"
import { filterAutoCompleteLocations } from "./filterAutoCompleteLocations"
import type { DeepPartial } from "@/types/DeepPartial"
import type { AutoCompleteLocation } from "../schema"
describe("rankAutoCompleteLocations", () => {
it("should give no hits when the query does not match", () => {
const locations = [scandicAlborgOst] as DeepPartial<AutoCompleteLocation>[]
const query = "NonMatchingQuery"
const ranked = filterAutoCompleteLocations(
locations as AutoCompleteLocation[],
query
)
expect(ranked.length).toBe(0)
})
it("should include items when the query matches parts of name", () => {
const locations = [scandicAlborgOst] as DeepPartial<AutoCompleteLocation>[]
const query = "Øst"
const ranked = filterAutoCompleteLocations(
locations as AutoCompleteLocation[],
query
)
expect(ranked.length).toBe(1)
expect(ranked.at(0)!.name).toEqual("Scandic Aalborg Øst")
})
it("should allow multiple search terms", () => {
const locations = [scandicAlborgOst] as DeepPartial<AutoCompleteLocation>[]
const query = "Aalborg Øst"
const ranked = filterAutoCompleteLocations(
locations as AutoCompleteLocation[],
query
)
expect(ranked.length).toBe(1)
expect(ranked.at(0)!.name).toEqual("Scandic Aalborg Øst")
})
it("should rank full word higher than part of word", () => {
const locations = [
scandicSyvSostre,
scandicAlborgOst,
] as DeepPartial<AutoCompleteLocation>[]
const query = "Øst"
const ranked = filterAutoCompleteLocations(
locations as AutoCompleteLocation[],
query
)
expect(ranked.length).toBe(2)
expect(ranked.at(0)!.name).toEqual("Scandic Aalborg Øst")
expect(ranked.at(1)!.name).toEqual("Scandic Syv Søstre")
})
it("should ignore items without match", () => {
const locations = [
scandicSyvSostre,
scandicAlborgOst,
berlinLodge,
scandicBrennemoen,
] as DeepPartial<AutoCompleteLocation>[]
const query = "Øst"
const ranked = filterAutoCompleteLocations(
locations as AutoCompleteLocation[],
query
)
expect(ranked.length).toBe(3)
expect(ranked.at(0)!.name).toEqual("Scandic Aalborg Øst")
expect(ranked.at(1)!.name).toEqual("Scandic Syv Søstre")
expect(ranked.at(2)!.name).toEqual("Scandic Brennemoen")
})
it("should ignore 'scandic' from name and destination when searching", () => {
const locations = [scandicAlborgOst, scandicBrennemoen].map((x) => ({
...x,
searchTokens: [],
})) as DeepPartial<AutoCompleteLocation>[]
const query = "scandic"
const ranked = filterAutoCompleteLocations(
locations as AutoCompleteLocation[],
query
)
expect(ranked.length).toBe(0)
})
it("should get hits for destination", () => {
const locations = [
scandicAlborgOst,
scandicBrennemoen,
] as DeepPartial<AutoCompleteLocation>[]
const query = "Mysen"
const ranked = filterAutoCompleteLocations(
locations as AutoCompleteLocation[],
query
)
expect(ranked.length).toBe(1)
expect(ranked.at(0)!.name).toBe("Scandic Brennemoen")
})
it("should get hits for searchTokens", () => {
const locations = [
scandicAlborgOst,
scandicBrennemoen,
] as DeepPartial<AutoCompleteLocation>[]
const query = "tusenfryd"
const ranked = filterAutoCompleteLocations(
locations as AutoCompleteLocation[],
query
)
expect(ranked.length).toBe(1)
expect(ranked.at(0)!.name).toBe("Scandic Brennemoen")
})
it("should match when using the wrong aumlaut ö -> ø", () => {
const locations = [scandicBodo] as DeepPartial<AutoCompleteLocation>[]
const query = "bodö"
const ranked = filterAutoCompleteLocations(
locations as AutoCompleteLocation[],
query
)
expect(ranked.length).toBe(1)
expect(ranked.at(0)!.name).toBe("Scandic Bodø")
})
})
const scandicAlborgOst: DeepPartial<AutoCompleteLocation> = {
name: "Scandic Aalborg Øst",
destination: "Aalborg",
searchTokens: [
"aalborg",
"aalborg øst",
"scandic aalborg øst",
"aalborg ost",
"scandic aalborg ost",
],
}
const scandicBrennemoen: DeepPartial<AutoCompleteLocation> = {
name: "Scandic Brennemoen",
destination: "Mysen",
searchTokens: [
"mysen",
"askim",
"indre østfold",
"drøbak",
"slitu",
"morenen",
"østfoldbadet",
"tusenfryd",
"brennemoen",
"scandic brennemoen",
"indre ostfold",
"drobak",
"ostfoldbadet",
],
}
const scandicSyvSostre: DeepPartial<AutoCompleteLocation> = {
name: "Scandic Syv Søstre",
destination: "Sandnessjoen",
searchTokens: [
"syv sostre",
"sandnessjoen",
"sandnessjøen",
"syv søstre",
"scandic syv søstre",
"scandic syv sostre",
],
}
const berlinLodge: DeepPartial<AutoCompleteLocation> = {
name: "Berlin Lodge",
searchTokens: [],
}
const scandicBodo: DeepPartial<AutoCompleteLocation> = {
name: "Scandic Bodø",
destination: "Bodo",
searchTokens: [
"bodo",
"kjerringoy",
"bodo i vinden",
"visit bodo",
"badin",
"scandic bodo",
"bodø",
"stormen",
"midnattsol",
"hurtigruten",
"saltstraumen",
"nord universitet",
"kjerringøy",
"nordlys",
"tuvsjyen",
"stella polaris",
"topptur",
"svartisen",
"polarsirkelen",
"aurora borealis",
"bodø i vinden",
"visit bodø",
"bådin",
"norsk luftfartsmuseum",
"rib",
"scandic bodø",
],
}

View File

@@ -1,66 +0,0 @@
import Fuse from "fuse.js"
import type { AutoCompleteLocation } from "../schema"
type SearchableAutoCompleteLocation = AutoCompleteLocation & {
nameTokens: string[]
destinationTokens: string[]
}
type SearchableKey = keyof SearchableAutoCompleteLocation
const fuseConfig = new Fuse([] as SearchableAutoCompleteLocation[], {
minMatchCharLength: 2,
isCaseSensitive: false,
ignoreDiacritics: true,
includeMatches: true,
includeScore: true,
threshold: 0.2,
keys: [
{
name: "nameTokens" satisfies SearchableKey,
weight: 3,
},
{
name: "destinationTokens" satisfies SearchableKey,
weight: 2,
},
{
name: "searchTokens" satisfies SearchableKey,
weight: 1,
},
],
})
export function filterAutoCompleteLocations<T extends AutoCompleteLocation>(
locations: T[],
query: string
) {
const searchable = locations.map((x) => ({
...x,
nameTokens: extractTokens(x.name),
destinationTokens: extractTokens(x.destination),
}))
fuseConfig.setCollection(searchable)
const searchResults = fuseConfig.search(query, { limit: 50 })
return searchResults.map(
(x) =>
({
id: x.item.id,
name: x.item.name,
cityIdentifier: x.item.cityIdentifier,
destination: x.item.destination,
searchTokens: x.item.searchTokens,
type: x.item.type,
url: x.item.url,
}) satisfies AutoCompleteLocation
)
}
function extractTokens(value: string): string[] {
const cleaned = value?.toLowerCase().replaceAll("scandic", "").trim() ?? ""
const output = [...new Set([cleaned, ...cleaned.split(" ")])]
return output
}

View File

@@ -1,54 +0,0 @@
import { describe, expect, it } from "@jest/globals"
import { getSearchTokens } from "./getSearchTokens"
import type { Location } from "@scandic-hotels/trpc/types/locations"
import type { DeepPartial } from "@/types/DeepPartial"
describe("getSearchTokens", () => {
it("should return lowercased tokens for a hotel location", () => {
const location: DeepPartial<Location> = {
keyWords: ["Beach", "Luxury"],
name: "Grand Hotel",
type: "hotels",
relationships: { city: { name: "Stockholm" } },
}
const result = getSearchTokens(location as Location)
expect(result).toEqual(["beach", "luxury", "grand hotel", "stockholm"])
})
it("should generate additional tokens for diacritics replacement on a non-hotel location", () => {
const location: DeepPartial<Location> = {
keyWords: ["Ångström", "Café"],
name: "München",
country: "Frånce",
type: "cities",
}
const result = getSearchTokens(location as Location)
expect(result).toEqual([
"ångström",
"café",
"münchen",
"frånce",
"angstrom",
"cafe",
"munchen",
"france",
])
})
it("should filter out empty or falsey tokens", () => {
const location: DeepPartial<Location> = {
keyWords: ["", "Valid"],
name: "",
type: "hotels",
relationships: { city: { name: "" } },
}
const result = getSearchTokens(location as Location)
expect(result).toEqual(["valid"])
})
})

View File

@@ -1,22 +0,0 @@
import { normalizeAumlauts } from "./normalizeAumlauts"
import type { Location } from "@scandic-hotels/trpc/types/locations"
export function getSearchTokens(location: Location) {
const tokens = [
...(location.keyWords?.map((x) => x.toLocaleLowerCase()) ?? []),
location.name,
location.type === "hotels"
? location.relationships.city.name
: location.country,
]
.filter(hasValue)
.map((x) => x.toLocaleLowerCase())
const normalizedTokens = normalizeAumlauts(tokens)
return normalizedTokens
}
function hasValue(value: string | null | undefined): value is string {
return !!value && value.length > 0
}

View File

@@ -1,25 +0,0 @@
import { getSearchTokens } from "./getSearchTokens"
import type { Location } from "@scandic-hotels/trpc/types/locations"
import type { AutoCompleteLocation } from "../schema"
export function mapLocationToAutoCompleteLocation(
location: (Location & { url?: string }) | null | undefined
): AutoCompleteLocation | null {
if (!location) return null
return {
id: location.id,
name: location.name,
type: location.type,
url: location.url,
searchTokens: getSearchTokens(location),
destination:
location.type === "hotels"
? location.relationships.city.name
: location.country,
cityIdentifier:
location.type === "cities" ? location.cityIdentifier : undefined,
}
}

View File

@@ -1,22 +0,0 @@
export function normalizeAumlauts(terms: string[]): string[] {
const additionalTerms: string[] = []
terms.forEach((token) => {
if (!token) return
const replaced = token
.replace(/å/g, "a")
.replace(/ä/g, "a")
.replace(/ö/g, "o")
.replace(/ø/g, "o")
.replace(/æ/g, "a")
.replace(/é/g, "e")
.replace(/ü/g, "u")
if (replaced !== token) {
additionalTerms.push(replaced)
}
})
return [...new Set([...additionalTerms, ...terms])]
}

View File

@@ -2,10 +2,6 @@ import { NextRequest } from "next/server"
import { env } from "@/env/server"
export function isDefined<T>(argument: T | undefined | null): argument is T {
return argument !== undefined && argument !== null
}
/**
* Use this function when you want to create URLs that are public facing, for
* example for redirects or redirectTo query parameters.