Merged in feat/common-package (pull request #2333)

feat: Add common package

* Add isEdge, safeTry and dataCache to new common package

* Add eslint and move prettier config

* Fix yarn lock

* Clean up tests

* Add lint-staged config to common

* Add missing dependencies


Approved-by: Joakim Jäderberg
This commit is contained in:
Anton Gunnarsson
2025-06-11 13:08:39 +00:00
parent 40d1b67a6f
commit 048a477e52
65 changed files with 939 additions and 182 deletions

View File

@@ -2,11 +2,11 @@ import { cookies } from "next/headers"
import { redirect } from "next/navigation"
import { z } from "zod"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { env } from "@/env/server"
import { serverClient } from "@/lib/trpc/server"
import { safeTry } from "@/utils/safeTry"
import { SAS_TOKEN_STORAGE_KEY, stateSchema } from "../sasUtils"
import type { NextRequest } from "next/server"

View File

@@ -2,11 +2,12 @@ import { cookies } from "next/headers"
import { redirect } from "next/navigation"
import { z } from "zod"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { myPages } from "@/constants/routes/myPages"
import { serverClient } from "@/lib/trpc/server"
import { getIntl } from "@/i18n"
import { safeTry } from "@/utils/safeTry"
import { SAS_TOKEN_STORAGE_KEY, SAS_TRANSFER_POINT_KEY } from "../sasUtils"
import OneTimePasswordForm, {

View File

@@ -2,11 +2,12 @@ import { revalidateTag } from "next/cache"
import { headers } from "next/headers"
import { z } from "zod"
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { Lang } from "@/constants/languages"
import { env } from "@/env/server"
import { badRequest, internalServerError, notFound } from "@/server/errors/next"
import { getCacheClient } from "@/services/dataCache"
import { generateHotelUrlTag } from "@/utils/generateTag"
import type { NextRequest } from "next/server"

View File

@@ -2,11 +2,12 @@ import { revalidateTag } from "next/cache"
import { headers } from "next/headers"
import { z } from "zod"
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { Lang } from "@/constants/languages"
import { env } from "@/env/server"
import { badRequest, internalServerError, notFound } from "@/server/errors/next"
import { getCacheClient } from "@/services/dataCache"
import { generateLoyaltyConfigTag } from "@/utils/generateTag"
import type { NextRequest } from "next/server"

View File

@@ -1,10 +1,11 @@
import { revalidateTag } from "next/cache"
import { headers } from "next/headers"
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { env } from "@/env/server"
import { badRequest, internalServerError } from "@/server/errors/next"
import { getCacheClient } from "@/services/dataCache"
import { generateTag } from "@/utils/generateTag"
import type { Lang } from "@/constants/languages"

View File

@@ -2,6 +2,8 @@ import { revalidateTag } from "next/cache"
import { headers } from "next/headers"
import { z } from "zod"
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { Lang } from "@/constants/languages"
import { env } from "@/env/server"
import { badRequest, internalServerError } from "@/server/errors/next"
@@ -10,7 +12,6 @@ import { languageSwitcherAffix } from "@/server/routers/contentstack/languageSwi
import { affix as metadataAffix } from "@/server/routers/contentstack/metadata/utils"
import { affix as pageSettingsAffix } from "@/server/routers/contentstack/pageSettings/utils"
import { getCacheClient } from "@/services/dataCache"
import {
generateRefsResponseTag,
generateRefTag,

View File

@@ -1,6 +1,8 @@
import { notFound } from "next/navigation"
import { Suspense } from "react"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import {
getHotel,
getHotelPage,
@@ -16,7 +18,6 @@ import { getIntl } from "@/i18n"
import { getLang } from "@/i18n/serverContext"
import { setFacilityCards } from "@/utils/facilityCards"
import { generateHotelSchema } from "@/utils/jsonSchemas"
import { safeTry } from "@/utils/safeTry"
import MapCard from "./Map/MapCard"
import MapWithCardWrapper from "./Map/MapWithCard"

View File

@@ -1,3 +1,4 @@
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { Typography } from "@scandic-hotels/design-system/Typography"
import { getMeetingRooms } from "@/lib/trpc/memoizedRequests"
@@ -7,7 +8,6 @@ import StickyMeetingPackageWidget from "@/components/StickyMeetingPackageWidget"
import Divider from "@/components/TempDesignSystem/Divider"
import { getIntl } from "@/i18n"
import { getLang } from "@/i18n/serverContext"
import { safeTry } from "@/utils/safeTry"
import HeroHeader from "../HeroHeader"
import HtmlContent from "../HtmlContent"

View File

@@ -1,12 +1,13 @@
import { notFound } from "next/navigation"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { env } from "@/env/server"
import { getCityCoordinates } from "@/lib/trpc/memoizedRequests"
import TrackingSDK from "@/components/TrackingSDK"
import { getLang } from "@/i18n/serverContext"
import { getHotelSearchDetails } from "@/utils/hotelSearchDetails"
import { safeTry } from "@/utils/safeTry"
import { getHotelPins } from "../../HotelCardDialogListing/utils"
import { getFiltersFromHotels, getHotels } from "../helpers"

1
apps/scandic-web/global.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
import "@scandic-hotels/common/global.d.ts"

View File

@@ -1,7 +1,8 @@
import * as Sentry from "@sentry/nextjs"
import { isEdge } from "@scandic-hotels/common/utils/isEdge"
import { env } from "./env/server"
import { isEdge } from "./utils/isEdge"
export async function register() {
/*

View File

@@ -6,10 +6,10 @@ import { arrayMerge } from "@/utils/merge"
import { request } from "./request"
import type { CacheTime } from "@scandic-hotels/common/dataCache"
import type { BatchRequestDocument } from "graphql-request"
import type { Data } from "@/types/request"
import type { CacheTime } from "@/services/dataCache"
export async function batchRequest<T>(
queries: (BatchRequestDocument & {

View File

@@ -3,11 +3,14 @@ import { GraphQLClient } from "graphql-request"
import stringify from "json-stable-stringify-without-jsonify"
import { cache as reactCache } from "react"
import {
type CacheTime,
getCacheClient,
} from "@scandic-hotels/common/dataCache"
import { env } from "@/env/server"
import { getPreviewHash, isPreviewByUid } from "@/lib/previewContext"
import { type CacheTime, getCacheClient } from "@/services/dataCache"
import { request as _request } from "./_request"
import { getOperationName } from "./getOperationName"

View File

@@ -1,9 +1,10 @@
import { type NextMiddleware, NextResponse } from "next/server"
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { notFound } from "@/server/errors/next"
import { getPublicNextURL } from "@/server/utils"
import { getCacheClient } from "@/services/dataCache"
import { findLang } from "@/utils/languages"
import { getDefaultRequestHeaders } from "./utils"

View File

@@ -5,7 +5,7 @@ import {
type WarmupFunctionsKey,
warmupKeys,
} from "@/services/warmup/warmupKeys"
import { safeTry } from "@/utils/safeTry"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { timeout } from "@/utils/timeout"
import type { Config, Context } from "@netlify/functions"

View File

@@ -119,6 +119,7 @@
"@eslint/js": "^9.26.0",
"@formatjs/cli": "^6.7.1",
"@lokalise/node-api": "^14.0.0",
"@scandic-hotels/common": "workspace:*",
"@scandic-hotels/typescript-config": "workspace:*",
"@svgr/webpack": "^8.1.0",
"@testing-library/jest-dom": "^6.6.3",

View File

@@ -1,12 +1,12 @@
import { z } from "zod"
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { Lang } from "@/constants/languages"
import { safeProtectedServiceProcedure } from "@/server/trpc"
import { isDefined } from "@/server/utils"
import { getCacheClient } from "@/services/dataCache"
import { safeTry } from "@/utils/safeTry"
import { getCityPageUrls } from "../contentstack/destinationCityPage/utils"
import { getCountryPageUrls } from "../contentstack/destinationCountryPage/utils"
import { getHotelPageUrls } from "../contentstack/hotelPage/utils"

View File

@@ -1,3 +1,5 @@
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { Lang } from "@/constants/languages"
import {
GetDestinationOverviewPage,
@@ -13,7 +15,6 @@ import {
} from "@/server/trpc"
import { generateRefsResponseTag, generateTag } from "@/utils/generateTag"
import { safeTry } from "@/utils/safeTry"
import {
getCitiesByCountry,

View File

@@ -1,3 +1,5 @@
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import * as api from "@/lib/api"
import {
GetRewards as GetRewards,
@@ -7,7 +9,6 @@ import { request } from "@/lib/graphql/request"
import { notFound } from "@/server/errors/trpc"
import { createCounter } from "@/server/telemetry"
import { getCacheClient } from "@/services/dataCache"
import {
generateLoyaltyConfigTag,
generateRefsResponseTag,

View File

@@ -1,3 +1,5 @@
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { REDEMPTION } from "@/constants/booking"
import { Lang } from "@/constants/languages"
import { env } from "@/env/server"
@@ -16,8 +18,6 @@ import {
} from "@/server/trpc"
import { toApiLang } from "@/server/utils"
import { getCacheClient } from "@/services/dataCache"
import { getHotelPageUrls } from "../contentstack/hotelPage/utils"
import { additionalDataSchema } from "./schemas/hotel/include/additionalData"
import { meetingRoomsSchema } from "./schemas/meetingRoom"

View File

@@ -1,6 +1,8 @@
import deepmerge from "deepmerge"
import stringify from "json-stable-stringify-without-jsonify"
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { BookingErrorCodeEnum, REDEMPTION } from "@/constants/booking"
import { Lang } from "@/constants/languages"
import { selectRate } from "@/constants/routes/hotelReservation"
@@ -11,7 +13,6 @@ import { createCounter } from "@/server/telemetry"
import { toApiLang } from "@/server/utils"
import { generateChildrenString } from "@/components/HotelReservation/utils"
import { getCacheClient } from "@/services/dataCache"
import { cache } from "@/utils/cache"
import { chunk } from "@/utils/chunk"
import { sortRoomConfigs } from "@/utils/sort"

View File

@@ -1,10 +1,11 @@
import { cache } from "react"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import * as routes from "@/constants/routes/myPages"
import { env } from "@/env/server"
import { getIntl } from "@/i18n"
import { safeTry } from "@/utils/safeTry"
import { getEurobonusMembership } from "@/utils/user"
import type { UserLoyalty } from "@/types/user"

View File

@@ -1,8 +1,8 @@
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { createCounter } from "@/server/telemetry"
import { publicProcedure, router } from "@/server/trpc"
import { getCacheClient } from "@/services/dataCache"
import { jobylonFeedSchema } from "./output"
export const TWENTYFOUR_HOURS = 60 * 60 * 24

View File

@@ -1,10 +1,10 @@
import { trace, type Tracer } from "@opentelemetry/api"
import { getCacheClient } from "@scandic-hotels/common/dataCache"
import { env } from "@/env/server"
import { createCounter } from "@/server/telemetry"
import { getCacheClient } from "@/services/dataCache"
import type { ServiceTokenResponse } from "@/types/tokens"
export async function getServiceToken() {

View File

@@ -1,102 +0,0 @@
import type { CacheOrGetOptions } from "./cacheOrGetOptions"
const ONE_HOUR_IN_SECONDS = 3_600 as const
const ONE_DAY_IN_SECONDS = 86_400 as const
export const namedCacheTimeMap: Record<NamedCacheTimes, number> = {
"no cache": 0,
"1m": 60,
"5m": 300,
"10m": 600,
"1h": ONE_HOUR_IN_SECONDS,
"3h": ONE_HOUR_IN_SECONDS * 3,
"6h": ONE_HOUR_IN_SECONDS * 6,
"1d": ONE_DAY_IN_SECONDS,
"3d": ONE_DAY_IN_SECONDS * 3,
max: ONE_DAY_IN_SECONDS * 30,
} as const
export const namedCacheTimes = [
"no cache",
"1m",
"5m",
"10m",
"1h",
"3h",
"6h",
"1d",
"3d",
"max",
] as const
export type NamedCacheTimes = (typeof namedCacheTimes)[number]
/**
* Retrieves the cache time in seconds based on the given cache time.
* @param cacheTime - The time value to determine, either a named cache time or a number of seconds.
* @returns The cache time in seconds.
*/
export const getCacheTimeInSeconds = (cacheTime: CacheTime): number => {
if (typeof cacheTime === "number") {
if (cacheTime < 0 || !Number.isInteger(cacheTime)) {
return 0
}
return cacheTime
}
return namedCacheTimeMap[cacheTime] ?? 0
}
export type CacheTime = NamedCacheTimes | number
export type DataCache = {
/**
* Type of cache
*/
type: "edge" | "redis" | "in-memory" | "unstable-cache"
/**
* Helper function that retrieves from the cache if it exists, otherwise calls the callback and caches the result.
* If the call fails, the cache is not updated.
* @param key The cache key
* @param getDataFromSource An async function that provides a value to cache
* @param ttl Time to live, either a named cache time or a number of seconds
* @param opts Options to control cache behavior when retrieving or storing data.
* @returns The cached value or the result from the callback
*/
cacheOrGet: <T>(
key: string | string[],
getDataFromSource: (
overrideTTL?: (cacheTime: CacheTime) => void
) => Promise<T>,
ttl: CacheTime,
opts?: CacheOrGetOptions
) => Promise<T>
/**
* Get a value from the cache, if it exists
* @see `cacheOrGet` for a more convenient way to cache values
* @param key The cache key to retrieve the value for
* @returns The cached value or undefined if not found
*/
get: <T>(key: string) => Promise<T | undefined>
/**
* Sets a value in the cache.
* @see `cacheOrGet` for a more convenient way to cache values
* @param key CacheKey to set
* @param obj Value to be cached
* @param ttl Time to live, either a named cache time or a number of seconds
* @returns A promise that resolves when the value has been cached
*/
set: <T>(key: string, obj: T, ttl: CacheTime) => Promise<void>
/**
* Deletes a key from the cache
* @param key CacheKey to delete
* @param fuzzy If true, does a wildcard delete. *key*
* @returns
*/
deleteKey: (key: string, opts?: { fuzzy?: boolean }) => Promise<void>
}

View File

@@ -1,50 +0,0 @@
import { type CacheTime, type DataCache } from "@/services/dataCache/Cache"
import {
type CacheOrGetOptions,
shouldGetFromCache,
} from "../cacheOrGetOptions"
import { cacheLogger } from "../logger"
import { generateCacheKey } from "./generateCacheKey"
import { get } from "./get"
import { set } from "./set"
export const cacheOrGet: DataCache["cacheOrGet"] = async <T>(
key: string | string[],
callback: (overrideTTL: (cacheTime: CacheTime) => void) => Promise<T>,
ttl: CacheTime,
opts?: CacheOrGetOptions
) => {
const cacheKey = generateCacheKey(key, {
includeGitHashInKey: opts?.includeGitHashInKey ?? true,
})
let cachedValue: Awaited<T> | undefined = undefined
if (shouldGetFromCache(opts)) {
cachedValue = await get<T>(cacheKey)
}
let realTTL = ttl
const overrideTTL = function (cacheTime: CacheTime) {
realTTL = cacheTime
}
if (!cachedValue) {
const perf = performance.now()
const data = await callback(overrideTTL)
const size = JSON.stringify(data).length / (1024 * 1024)
if (size >= 5) {
cacheLogger.warn(`'${key}' is larger than 5MB!`)
}
cacheLogger.debug(
`Fetching data took ${(performance.now() - perf).toFixed(2)}ms ${size.toFixed(4)}MB for '${key}'`
)
await set<T>(cacheKey, data, realTTL)
return data
}
return cachedValue
}

View File

@@ -1,19 +0,0 @@
import { env } from "@/env/server"
import { cacheOrGet } from "./cacheOrGet"
import { deleteKey } from "./deleteKey"
import { get } from "./get"
import { set } from "./set"
import type { DataCache } from "@/services/dataCache/Cache"
export const API_KEY = env.REDIS_API_KEY ?? ""
export async function createDistributedCache(): Promise<DataCache> {
return {
type: "redis",
get,
set,
cacheOrGet,
deleteKey,
} satisfies DataCache
}

View File

@@ -1,45 +0,0 @@
import * as Sentry from "@sentry/nextjs"
import { safeTry } from "@/utils/safeTry"
import { cacheLogger } from "../logger"
import { API_KEY } from "./client"
import { getCacheEndpoint } from "./endpoints"
export async function deleteKey(key: string, opts?: { fuzzy?: boolean }) {
const perf = performance.now()
const endpoint = getCacheEndpoint(key)
if (opts?.fuzzy) {
endpoint.searchParams.set("fuzzy", "true")
}
const [response, error] = await safeTry(
fetch(endpoint, {
method: "DELETE",
cache: "no-cache",
headers: {
"x-api-key": API_KEY,
},
signal: AbortSignal.timeout(10_000),
})
)
if (!response || !response.ok || error) {
if (response?.status !== 404) {
Sentry.captureException(error ?? new Error("Unable to DELETE cachekey"), {
extra: {
cacheKey: key,
statusCode: response?.status,
statusText: response?.statusText,
},
})
}
return undefined
}
cacheLogger.debug(
`Delete '${key}' took ${(performance.now() - perf).toFixed(2)}ms`
)
}

View File

@@ -1,12 +0,0 @@
import { env } from "@/env/server"
export function getCacheEndpoint(key: string) {
if (!env.REDIS_API_HOST) {
throw new Error("REDIS_API_HOST is not set")
}
const url = new URL(`/api/cache`, env.REDIS_API_HOST)
url.searchParams.set("key", encodeURIComponent(key))
return url
}

View File

@@ -1,29 +0,0 @@
import { describe, expect, it } from "@jest/globals"
import { getBranchPrefix } from "./getBranchPrefix"
describe("getBranchPrefix", () => {
it("should return empty string for production branches", () => {
expect(getBranchPrefix("production")).toBe("")
expect(getBranchPrefix("prod")).toBe("")
expect(getBranchPrefix("release")).toBe("")
expect(getBranchPrefix("release-v1")).toBe("")
expect(getBranchPrefix("release-v1.2")).toBe("")
expect(getBranchPrefix("release-v1.2.3")).toBe("")
expect(getBranchPrefix("release-v1.2.3-rc1")).toBe("")
expect(getBranchPrefix("release-v1.2-beta")).toBe("")
expect(getBranchPrefix("release-v1-preview")).toBe("")
})
it("should return branch name for non-production branches", () => {
expect(getBranchPrefix("feature/hello")).toBe("feature/hello")
expect(getBranchPrefix("fix/stuff")).toBe("fix/stuff")
expect(getBranchPrefix("releasee")).toBe("releasee")
expect(getBranchPrefix("release-vA")).toBe("release-vA")
expect(getBranchPrefix("release-v1.A")).toBe("release-v1.A")
expect(getBranchPrefix("release-v1.2.A")).toBe("release-v1.2.A")
expect(getBranchPrefix("release-v1.2.A-rc1")).toBe("release-v1.2.A-rc1")
expect(getBranchPrefix("release-v1.A-beta")).toBe("release-v1.A-beta")
expect(getBranchPrefix("release-vA-preview")).toBe("release-vA-preview")
})
})

View File

@@ -1,26 +0,0 @@
/**
* This will match release branches
* @example
* release-v1.2.3
* release-v1.2
* release-v1
* release-v1.2.3-alpha
* release-v1.2-beta
* release-v1-preview
*/
const releaseRegex = /^release-v\d+(?:\.\d+){0,2}(?:-\w+)?$/
/**
* If the branch is a production branch reuse the same prefix so that we can reuse the cache between pre-prod and prod
* @param branch
* @returns
*/
export const getBranchPrefix = (branch: string) => {
const isProdBranch =
branch === "production" ||
branch === "prod" ||
branch === "release" ||
releaseRegex.test(branch)
return isProdBranch ? "" : branch
}

View File

@@ -1,102 +0,0 @@
import { describe, expect, it, jest } from "@jest/globals"
jest.doMock("@/env/server", () => ({
env: {
NODE_ENV: "test",
},
}))
const { env } = require("@/env/server")
const { getPrefix } = require("./getPrefix")
const mockedEnv = env as { BRANCH: string; GIT_SHA: string }
describe("getPrefix", () => {
const OLD_ENV = process.env
beforeEach(() => {
jest.resetModules()
})
afterEach(() => {
process.env = OLD_ENV
})
it.each([
"prod",
"production",
"release",
"release-v1",
"release-v2",
"release-v2-alpha",
"release-v2.1-alpha",
"release-v2.1.2-alpha",
])(
"should return gitsha for production branches when name is '%s'",
(branchName: string) => {
mockedEnv.BRANCH = branchName
mockedEnv.GIT_SHA = "gitsha"
const result = getPrefix()
expect(result).toBe("gitsha")
}
)
it.each([
"fix/stuff",
"feat/my-feature",
"feature/my-feature",
"releasee",
"release-vA",
"FEAT",
])(
"should return branch name and gitsha for non-production branches when name is '%s'",
(branchName: string) => {
mockedEnv.BRANCH = branchName
mockedEnv.GIT_SHA = "gitsha"
const result = getPrefix()
expect(result).toBe(`${mockedEnv.BRANCH}:${mockedEnv.GIT_SHA}`)
}
)
it("should throw if BRANCH and/or GIT_SHA is not set", () => {
mockedEnv.BRANCH = ""
mockedEnv.GIT_SHA = ""
expect(getPrefix).toThrow(
"Unable to getPrefix, BRANCH and GIT_SHA must be set"
)
mockedEnv.BRANCH = "hasBranch"
mockedEnv.GIT_SHA = ""
expect(getPrefix).toThrow("Unable to getPrefix, GIT_SHA must be set")
mockedEnv.BRANCH = ""
mockedEnv.GIT_SHA = "hasGitSha"
expect(getPrefix).toThrow("Unable to getPrefix, BRANCH must be set")
})
it("should return dev or local user if running locally", () => {
;(process.env.NODE_ENV as any) = "development"
process.env.USER = "test_user"
process.env.USERNAME = "test_username"
mockedEnv.BRANCH = ""
mockedEnv.GIT_SHA = ""
expect(getPrefix()).toBe("test_user")
process.env.USER = ""
expect(getPrefix()).toBe("test_username")
process.env.USERNAME = ""
expect(getPrefix()).toBe("dev")
})
})

View File

@@ -1,42 +0,0 @@
import { env } from "@/env/server"
import { getBranchPrefix } from "./getBranchPrefix"
export function getPrefix(options: {
includeGitHashInKey: boolean
includeBranchPrefix: boolean
}): string {
const prefixTokens = []
const includeGitHashInKey = options.includeGitHashInKey
const includeBranchPrefix = options.includeBranchPrefix
if (process.env.NODE_ENV === "development") {
const devPrefix = process.env.USER || process.env.USERNAME || "dev"
return `${devPrefix}`
}
if (includeGitHashInKey) {
const gitSha = env.GIT_SHA?.trim().substring(0, 7)
if (!gitSha) {
throw new Error("Unable to getPrefix, GIT_SHA must be set")
}
prefixTokens.push(gitSha)
}
if (includeBranchPrefix) {
const branch = env.BRANCH?.trim()
if (!branch) {
throw new Error("Unable to getPrefix, BRANCH must be set")
}
const branchPrefix = getBranchPrefix(branch)
if (branchPrefix) {
prefixTokens.push(branchPrefix)
}
}
return prefixTokens.join(":")
}

View File

@@ -1,46 +0,0 @@
import { describe, expect, it, jest } from "@jest/globals"
jest.mock("./getPrefix", () => ({
getPrefix: jest.fn(() => "gitsha"),
}))
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const indexModule: typeof import(".") = require(".")
const { generateCacheKey } = indexModule
describe("generateCacheKey", () => {
const OLD_ENV = process.env
beforeEach(() => {
jest.resetModules()
})
afterEach(() => {
process.env = OLD_ENV
})
it("generates cachekey with prefix and key using string", () => {
expect(generateCacheKey("key1")).toBe("gitsha:key1")
})
it("generates cachekey with prefix and key using array", () => {
expect(generateCacheKey(["key1"])).toBe("gitsha:key1")
})
it("generates cachekey with prefix and keys", () => {
const actual = generateCacheKey(["key1", "key2"])
expect(actual).toBe("gitsha:key1_key2")
})
it("should throw an error if no keys are provided", () => {
expect(() => generateCacheKey([])).toThrow("No keys provided")
})
it("should throw an error if only invalid keys are provided", () => {
expect(() => generateCacheKey(["", undefined, null] as string[])).toThrow(
"No keys provided"
)
expect(() => generateCacheKey("")).toThrow("No keys provided")
})
})

View File

@@ -1,22 +0,0 @@
import { getPrefix } from "./getPrefix"
export function generateCacheKey(
key: string | string[],
options?: { includeGitHashInKey?: boolean }
): string {
const includeGitHashInKey = options?.includeGitHashInKey ?? true
const keyArray = (Array.isArray(key) ? key : [key]).filter(Boolean)
if (keyArray.length === 0) {
throw new Error("No keys provided")
}
const prefix = getPrefix({
includeGitHashInKey,
includeBranchPrefix: true,
})
const keyTokens = [prefix, keyArray.join("_")].filter(Boolean).join(":")
return keyTokens
}

View File

@@ -1,61 +0,0 @@
import * as Sentry from "@sentry/nextjs"
import { safeTry } from "@/utils/safeTry"
import { cacheLogger } from "../logger"
import { API_KEY } from "./client"
import { deleteKey } from "./deleteKey"
import { getCacheEndpoint } from "./endpoints"
export async function get<T>(key: string) {
const perf = performance.now()
const [response, error] = await safeTry(
fetch(getCacheEndpoint(key), {
method: "GET",
cache: "no-cache",
headers: {
"x-api-key": API_KEY,
},
signal: AbortSignal.timeout(3_000),
})
)
if (!response || !response.ok || error) {
if (response?.status === 404) {
cacheLogger.debug(
`Miss '${key}' took ${(performance.now() - perf).toFixed(2)}ms`
)
return undefined
}
Sentry.captureException(error ?? new Error("Unable to GET cachekey"), {
extra: {
cacheKey: key,
statusCode: response?.status,
statusText: response?.statusText,
},
})
return undefined
}
const [data, jsonError] = await safeTry(
response.json() as Promise<{ data: T }>
)
if (jsonError) {
cacheLogger.error("Failed to parse cache response", {
key,
error: jsonError,
})
await deleteKey(key)
return undefined
}
cacheLogger.debug(
`Hit '${key}' took ${(performance.now() - perf).toFixed(2)}ms`
)
return data?.data
}

View File

@@ -1 +0,0 @@
export { createDistributedCache } from "./client"

View File

@@ -1,32 +0,0 @@
import * as Sentry from "@sentry/nextjs"
import { safeTry } from "@/utils/safeTry"
import { type CacheTime, getCacheTimeInSeconds } from "../Cache"
import { API_KEY } from "./client"
import { getCacheEndpoint } from "./endpoints"
export async function set<T>(key: string, value: T, ttl: CacheTime) {
const [response, error] = await safeTry(
fetch(getCacheEndpoint(key), {
method: "PUT",
headers: {
"Content-Type": "application/json",
"x-api-key": API_KEY,
},
body: JSON.stringify({ data: value, ttl: getCacheTimeInSeconds(ttl) }),
cache: "no-cache",
signal: AbortSignal.timeout(3_000),
})
)
if (!response || !response.ok || error) {
Sentry.captureException(error ?? new Error("Unable to SET cachekey"), {
extra: {
cacheKey: key,
statusCode: response?.status,
statusText: response?.statusText,
},
})
}
}

View File

@@ -1,9 +0,0 @@
export const cacheMap = new Map<
string,
{
/** Absolute expiration timestamp (`Date.now()`) */
expiresAt: number
/** The cached data */
data: unknown
}
>()

View File

@@ -1,48 +0,0 @@
import { type CacheTime, type DataCache } from "@/services/dataCache/Cache"
import { cacheLogger } from "@/services/dataCache/logger"
import {
type CacheOrGetOptions,
shouldGetFromCache,
} from "../../cacheOrGetOptions"
import { get } from "./get"
import { set } from "./set"
export const cacheOrGet: DataCache["cacheOrGet"] = async <T>(
key: string | string[],
callback: (overrideTTL?: (cacheTime: CacheTime) => void) => Promise<T>,
ttl: CacheTime,
opts?: CacheOrGetOptions
): Promise<T> => {
if (Array.isArray(key)) {
key = key.join("-")
}
let realTTL = ttl
const overrideTTL = function (cacheTime: CacheTime) {
realTTL = cacheTime
}
let cached: Awaited<T> | undefined = undefined
if (shouldGetFromCache(opts)) {
cached = await get(key)
if (cached) {
return cached
}
cacheLogger.debug(`Miss for key '${key}'`)
}
try {
const data = await callback(overrideTTL)
await set(key, data, realTTL)
return data
} catch (e) {
cacheLogger.error(
`Error while fetching data for key '${key}', avoid caching`,
e
)
throw e
}
}

View File

@@ -1,17 +0,0 @@
import { cacheLogger } from "@/services/dataCache/logger"
import { cacheMap } from "./cacheMap"
export async function deleteKey(key: string, opts?: { fuzzy?: boolean }) {
cacheLogger.debug("Deleting key", key)
if (opts?.fuzzy) {
cacheMap.forEach((_, k) => {
if (k.includes(key)) {
cacheMap.delete(k)
}
})
return
}
cacheMap.delete(key)
}

View File

@@ -1,23 +0,0 @@
import { cacheLogger } from "@/services/dataCache/logger"
import { cacheMap } from "./cacheMap"
export async function get<T>(key: string): Promise<T | undefined> {
const cached = cacheMap.get(key)
if (!cached) {
return undefined
}
if (cached.expiresAt < Date.now()) {
cacheLogger.debug(`Expired for key '${key}'`)
cacheMap.delete(key)
return undefined
}
if (cached.data === undefined) {
cacheLogger.debug(`Data is undefined for key '${key}'`)
cacheMap.delete(key)
return undefined
}
return cached.data as T
}

View File

@@ -1,10 +0,0 @@
import { cacheOrGet } from "./cacheOrGet"
import { deleteKey } from "./deleteKey"
import { get } from "./get"
import { set } from "./set"
import type { DataCache } from "@/services/dataCache/Cache"
export async function createInMemoryCache(): Promise<DataCache> {
return { type: "in-memory", cacheOrGet, deleteKey, get, set }
}

View File

@@ -1,17 +0,0 @@
import {
type CacheTime,
getCacheTimeInSeconds,
} from "@/services/dataCache/Cache"
import { cacheMap } from "./cacheMap"
export async function set<T>(
key: string,
data: T,
ttl: CacheTime
): Promise<void> {
cacheMap.set(key, {
data: data,
expiresAt: Date.now() + getCacheTimeInSeconds(ttl) * 1000,
})
}

View File

@@ -1,7 +0,0 @@
import { createInMemoryCache } from "./InMemoryCache"
import type { DataCache } from "@/services/dataCache/Cache"
export function createMemoryCache(): Promise<DataCache> {
return createInMemoryCache()
}

View File

@@ -1,28 +0,0 @@
/**
* Options to control cache behavior when retrieving or storing data.
*
* - "cache-first": Default behaviour, check if the needed data is available in the cache first. If the data is found, it is returned immediately. Otherwise, the data is fetched and then cached.
* - "fetch-then-cache": Always fetch the data first, and then update the cache with the freshly fetched data.
*/
export type CacheStrategy = "cache-first" | "fetch-then-cache"
export type CacheOrGetOptions = {
cacheStrategy?: CacheStrategy
includeGitHashInKey?: boolean
}
export function defaultCacheOrGetOptions(
opts: CacheOrGetOptions = {}
): CacheOrGetOptions {
return {
cacheStrategy: "cache-first",
...opts,
}
}
export function shouldGetFromCache(
opts: CacheOrGetOptions | undefined
): boolean {
opts = defaultCacheOrGetOptions(opts)
return opts.cacheStrategy === "cache-first"
}

View File

@@ -1,27 +0,0 @@
import { env } from "@/env/server"
import { isEdge } from "@/utils/isEdge"
import { createMemoryCache } from "./MemoryCache/createMemoryCache"
import { type DataCache } from "./Cache"
import { createDistributedCache } from "./DistributedCache"
import { cacheLogger } from "./logger"
export type { CacheTime, DataCache } from "./Cache"
export async function getCacheClient(): Promise<DataCache> {
if (global.cacheClient) {
return global.cacheClient
}
global.cacheClient = env.REDIS_API_HOST
? createDistributedCache()
: createMemoryCache()
const cacheClient = await global.cacheClient
cacheLogger.debug(
`Creating ${cacheClient.type} cache on ${isEdge ? "edge" : "server"} runtime`
)
return global.cacheClient
}

View File

@@ -1,44 +0,0 @@
export const cacheLogger = {
async debug(message: string, ...args: unknown[]): Promise<void> {
console.debug(`${await loggerPrefix()} ${message}`, ...args)
},
async warn(message: string, ...args: unknown[]): Promise<void> {
console.warn(`${await loggerPrefix()} Warning - ${message}`, ...args)
},
async error(message: string, ...args: unknown[]): Promise<void> {
console.error(`${await loggerPrefix()} Error - ${message}`, ...args)
},
}
async function loggerPrefix() {
const instancePrefix = await getCachePrefix()
return `[Cache] ${instancePrefix ?? ""}`.trim()
}
async function getCachePrefix() {
const cacheCreated = await isPromiseResolved(global.cacheClient)
if (!cacheCreated.resolved) {
return null
}
const instanceType = cacheCreated.value?.type
if (!instanceType) {
return null
}
return `[${instanceType}]`
}
function isPromiseResolved<T>(promise: Promise<T> | undefined) {
if (!promise) {
return { resolved: false, value: undefined }
}
const check = Promise.race([promise, Promise.resolve("__PENDING__")])
return check.then((result) => ({
resolved: result !== "__PENDING__",
value: result !== "__PENDING__" ? (result as Awaited<T>) : undefined,
}))
}

View File

@@ -1,3 +1,5 @@
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { Lang } from "@/constants/languages"
import {
getCountries,
@@ -5,8 +7,6 @@ import {
} from "@/server/routers/hotels/utils"
import { getServiceToken } from "@/server/tokenManager"
import { safeTry } from "@/utils/safeTry"
import type { WarmupFunction, WarmupResult } from "."
export const warmupHotelIdsByCountry =

View File

@@ -1,5 +0,0 @@
import type { DataCache } from "@/services/dataCache"
declare global {
var cacheClient: Promise<DataCache> | undefined
}

View File

@@ -1,10 +1,11 @@
import { notFound } from "next/navigation"
import { safeTry } from "@scandic-hotels/common/utils/safeTry"
import { REDEMPTION } from "@/constants/booking"
import { getLocations } from "@/lib/trpc/memoizedRequests"
import { generateChildrenString } from "@/components/HotelReservation/utils"
import { safeTry } from "@/utils/safeTry"
import type { BookingSearchType } from "@/types/components/hotelReservation/booking"
import type { Child } from "@/types/components/hotelReservation/selectRate/selectRate"

View File

@@ -1,3 +0,0 @@
export const isEdge =
typeof (global as any).EdgeRuntime !== "undefined" ||
typeof (global as any).Deno !== "undefined"

View File

@@ -1,11 +0,0 @@
export type SafeTryResult<T> = Promise<
[T, undefined] | [undefined, Error | unknown]
>
export async function safeTry<T>(func: Promise<T>): SafeTryResult<T> {
try {
return [await func, undefined]
} catch (err) {
return [undefined, err]
}
}