fix(SW-236): properly handle expired token in webviews

Trying out a new pattern for errors in data fetching.

Next.js is not a fan of throwing errors. Instead it recommends returning
different shapes for each state. Ref:
https://nextjs.org/docs/app/building-your-application/routing/error-handling#handling-expected-errors-from-server-components

It requires some more detailing and a bit more refactoring in non webview part,
but it is a start. This webview specific implementation should not break web.
This commit is contained in:
Michael Zetterberg
2024-08-10 01:02:03 +02:00
parent c0284cd56c
commit bc84122a40
12 changed files with 64 additions and 32 deletions

View File

@@ -31,6 +31,12 @@ import type {
} from "@/types/components/tracking"
async function getVerifiedUser({ session }: { session: Session }) {
const now = Date.now()
if (session.token.expires_at < now) {
return { error: true, cause: "token_expired" } as const
}
const apiResponse = await api.get(api.endpoints.v1.profile, {
cache: "no-store",
headers: {
@@ -39,6 +45,11 @@ async function getVerifiedUser({ session }: { session: Session }) {
})
if (!apiResponse.ok) {
if (apiResponse.status === 401) {
return { error: true, cause: "unauthorized" } as const
} else if (apiResponse.status === 403) {
return { error: true, cause: "forbidden" } as const
}
return null
}
@@ -141,12 +152,18 @@ export const userQueryRouter = router({
get: protectedProcedure
.input(getUserInputSchema)
.query(async function getUser({ ctx, input }) {
const verifiedData = await getVerifiedUser({ session: ctx.session })
const data = await getVerifiedUser({ session: ctx.session })
if (!verifiedData) {
if (!data) {
return null
}
if ("error" in data) {
return data
}
const verifiedData = data
const country = countries.find(
(c) => c.code === verifiedData.data.address.countryCode
)
@@ -199,7 +216,7 @@ export const userQueryRouter = router({
}
const verifiedData = await getVerifiedUser({ session: ctx.session })
if (!verifiedData) {
if (!verifiedData || "error" in verifiedData) {
return null
}
return {
@@ -213,7 +230,7 @@ export const userQueryRouter = router({
}
const verifiedData = await getVerifiedUser({ session: ctx.session })
if (!verifiedData) {
if (!verifiedData || "error" in verifiedData) {
return null
}
@@ -230,7 +247,7 @@ export const userQueryRouter = router({
}
const verifiedUserData = await getVerifiedUser({ session: ctx.session })
if (!verifiedUserData) {
if (!verifiedUserData || "error" in verifiedUserData) {
return notLoggedInUserTrackingData
}