feat(logs): cleanup of token expired logs * feat(logs): cleanup of token expired logs Approved-by: Matilda Landström
70 lines
1.8 KiB
TypeScript
70 lines
1.8 KiB
TypeScript
import { createCounter } from "@scandic-hotels/common/telemetry"
|
|
|
|
import * as api from "../../../api"
|
|
import { cache } from "../../../DUPLICATED/cache"
|
|
import {
|
|
internalServerError,
|
|
serverErrorByStatus,
|
|
sessionExpiredError,
|
|
} from "../../../errors"
|
|
import { getUserSchema } from "../output"
|
|
|
|
export const getVerifiedUser = cache(
|
|
async ({
|
|
token,
|
|
includeExtendedPartnerData,
|
|
}: {
|
|
token: { expires_at?: number; access_token: string }
|
|
includeExtendedPartnerData?: boolean
|
|
}) => {
|
|
const getVerifiedUserCounter = createCounter("user", "getVerifiedUser")
|
|
const metricsGetVerifiedUser = getVerifiedUserCounter.init()
|
|
|
|
metricsGetVerifiedUser.start()
|
|
|
|
const now = Date.now()
|
|
if (token.expires_at && token.expires_at < now) {
|
|
throw sessionExpiredError()
|
|
}
|
|
|
|
const apiResponse = await api.get(
|
|
api.endpoints.v2.Profile.profile,
|
|
{
|
|
headers: {
|
|
Authorization: `Bearer ${token.access_token}`,
|
|
},
|
|
},
|
|
includeExtendedPartnerData
|
|
? { includes: "extendedPartnerInformation" }
|
|
: {}
|
|
)
|
|
|
|
if (!apiResponse.ok) {
|
|
await metricsGetVerifiedUser.httpError(apiResponse)
|
|
|
|
throw serverErrorByStatus(apiResponse.status, apiResponse)
|
|
}
|
|
|
|
const apiJson = await apiResponse.json()
|
|
if (!apiJson.data?.attributes) {
|
|
metricsGetVerifiedUser.dataError(
|
|
`Missing data attributes in API response`,
|
|
{
|
|
data: apiJson,
|
|
}
|
|
)
|
|
throw internalServerError("Missing data attributes in API response")
|
|
}
|
|
|
|
const verifiedData = getUserSchema.safeParse(apiJson)
|
|
if (!verifiedData.success) {
|
|
metricsGetVerifiedUser.validationError(verifiedData.error)
|
|
throw verifiedData.error
|
|
}
|
|
|
|
metricsGetVerifiedUser.success()
|
|
|
|
return verifiedData.data
|
|
}
|
|
)
|