51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import { TRPCError } from "@trpc/server"
|
|
import { redirect } from "next/navigation"
|
|
|
|
import { Lang } from "@/constants/languages"
|
|
import { overview } from "@/constants/routes/webviews"
|
|
import { appRouter } from "@/server"
|
|
import { createContext } from "@/server/context"
|
|
import { internalServerError } from "@/server/errors/next"
|
|
import { createCallerFactory } from "@/server/trpc"
|
|
|
|
const createCaller = createCallerFactory(appRouter)
|
|
|
|
export function serverClient() {
|
|
return createCaller(createContext(), {
|
|
onError: ({ ctx, error, input, path, type }) => {
|
|
console.error(`Server Client error for ${type}: ${path}`)
|
|
if (input) {
|
|
console.error(`Received input:`)
|
|
console.error(input)
|
|
}
|
|
console.error(error)
|
|
|
|
if (error instanceof TRPCError) {
|
|
if (error.code === "UNAUTHORIZED") {
|
|
const lang = ctx?.lang || Lang.en
|
|
if (ctx?.webToken) {
|
|
console.log({ ctx })
|
|
const returnUrl = ctx.pathname || overview[lang]
|
|
|
|
const redirectUrl = `/${lang}/webview/refresh?returnurl=${encodeURIComponent(returnUrl)}`
|
|
console.error(
|
|
"Unautorized in webview, redirecting to: ",
|
|
redirectUrl
|
|
)
|
|
redirect(redirectUrl)
|
|
}
|
|
|
|
console.error("Unautorized on web, redirecting to login")
|
|
|
|
const pathname = ctx?.pathname || "/"
|
|
redirect(
|
|
`/${lang}/login?redirectTo=${encodeURIComponent(`/${lang}/${pathname}`)}`
|
|
)
|
|
}
|
|
}
|
|
|
|
throw internalServerError()
|
|
},
|
|
})
|
|
}
|