Chore/refactor hotel trpc routes * chore(SW-3519): refactor trpc hotel routers * chore(SW-3519): refactor trpc hotel routers * refactor * merge * Merge branch 'master' of bitbucket.org:scandic-swap/web into chore/refactor-hotel-trpc-routes Approved-by: Linus Flood
78 lines
2.3 KiB
TypeScript
78 lines
2.3 KiB
TypeScript
import { getCacheClient } from "@scandic-hotels/common/dataCache"
|
|
import { createLogger } from "@scandic-hotels/common/logger/createLogger"
|
|
|
|
import * as api from "../../../api"
|
|
import { toApiLang } from "../../../utils"
|
|
import { citiesByCountrySchema } from "../output"
|
|
|
|
import type { Lang } from "@scandic-hotels/common/constants/language"
|
|
|
|
import type { CitiesGroupedByCountry } from "../../../types/locations"
|
|
|
|
const logger = createLogger("trpc:hotels:getCitiesByCountry")
|
|
export const locationsAffix = "locations"
|
|
export async function getCitiesByCountry({
|
|
countries,
|
|
lang,
|
|
affix = locationsAffix,
|
|
serviceToken,
|
|
}: {
|
|
countries: string[]
|
|
lang: Lang
|
|
affix?: string
|
|
serviceToken: string
|
|
}): Promise<CitiesGroupedByCountry> {
|
|
const cacheClient = await getCacheClient()
|
|
const allCitiesByCountries = await Promise.all(
|
|
countries.map(async (country) => {
|
|
return cacheClient.cacheOrGet(
|
|
`${lang}:${affix}:cities-by-country:${country}`,
|
|
async () => {
|
|
const params = new URLSearchParams({
|
|
language: toApiLang(lang),
|
|
})
|
|
const countryResponse = await api.get(
|
|
api.endpoints.v1.Hotel.Cities.country(country),
|
|
{
|
|
headers: {
|
|
Authorization: `Bearer ${serviceToken}`,
|
|
},
|
|
},
|
|
params
|
|
)
|
|
|
|
if (!countryResponse.ok) {
|
|
throw new Error(`Unable to fetch cities by country ${country}`)
|
|
}
|
|
|
|
const countryJson = await countryResponse.json()
|
|
const citiesByCountry = citiesByCountrySchema.safeParse(countryJson)
|
|
if (!citiesByCountry.success) {
|
|
logger.error(
|
|
`Unable to parse cities by country ${country}`,
|
|
citiesByCountry.error
|
|
)
|
|
|
|
throw new Error(`Unable to parse cities by country ${country}`)
|
|
}
|
|
return { ...citiesByCountry.data, country }
|
|
},
|
|
"1d"
|
|
)
|
|
})
|
|
)
|
|
|
|
const filteredCitiesByCountries = allCitiesByCountries.map((country) => ({
|
|
...country,
|
|
data: country.data.filter((city) => city.isPublished),
|
|
}))
|
|
|
|
const groupedCitiesByCountry: CitiesGroupedByCountry =
|
|
filteredCitiesByCountries.reduce((acc, { country, data }) => {
|
|
acc[country] = data
|
|
return acc
|
|
}, {} as CitiesGroupedByCountry)
|
|
|
|
return groupedCitiesByCountry
|
|
}
|