Skip to content

Commit

Permalink
perf(external): hydrate auth providers
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <tukon479@gmail.com>
  • Loading branch information
Innei committed Dec 16, 2024
1 parent 3497623 commit e0661ff
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 17 deletions.
File renamed without changes.
32 changes: 32 additions & 0 deletions apps/server/client/pages/(login)/login/metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { GetHydrateData } from "@client/lib/helper"
import type { AuthProvider } from "@client/query/users"

import { createApiFetch } from "~/lib/api-client"
import { defineMetadata } from "~/meta-handler"

const getTypedProviders = async () => {
const apiFetch = createApiFetch()
const data = (await apiFetch("/better-auth/get-providers")) as Record<string, AuthProvider>

return data
}

const meta = defineMetadata(async () => {
const providers = await getTypedProviders()

return [
{
type: "title",
title: "Login",
},
{
type: "hydrate",
data: providers,
path: "/login",
key: `betterAuth`,
},
] as const
})

export type LoginHydrateData = GetHydrateData<typeof meta>
export default meta
10 changes: 9 additions & 1 deletion apps/server/client/query/users.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { apiClient } from "@client/lib/api-fetch"
import { getHydrateData } from "@client/lib/helper"
import type { LoginHydrateData } from "@client/pages/(login)/login/metadata"
import { getProviders } from "@follow/shared/auth"
import { capitalizeFirstLetter, isBizId, parseUrl } from "@follow/utils/utils"
import { useQuery } from "@tanstack/react-query"
Expand Down Expand Up @@ -62,9 +63,16 @@ export interface AuthProvider {
color: string
icon: string
}
const getTypedProviders = async () => {
const providers = await getProviders()
return providers.data as Record<string, AuthProvider>
}
export const useAuthProviders = () => {
return useQuery({
queryKey: ["providers"],
queryFn: async () => (await getProviders()).data as Record<string, AuthProvider>,
queryFn: async () => getTypedProviders(),
initialData: getHydrateData(`betterAuth`) as LoginHydrateData,
})
}

export { getTypedProviders as getAuthProviders }
11 changes: 7 additions & 4 deletions apps/server/helper/meta-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import { dirname } from "node:path"
import { fileURLToPath } from "node:url"

import chokidar from "chokidar"
import { glob } from "glob"
import fg from "fast-glob"

const __dirname = dirname(fileURLToPath(import.meta.url))

async function generateMetaMap() {
const files = await glob("./client/pages/(main)/**/metadata.ts", {
const files = await fg.glob("./client/pages/**/*/metadata.ts", {
cwd: path.resolve(__dirname, ".."),
})

Expand All @@ -18,10 +18,13 @@ async function generateMetaMap() {

files.forEach((file, index) => {
const routePath = file
.replace("client/pages/(main)", "")
.replace("client/pages/", "")
.replace("/metadata.ts", "")
.replaceAll(/\[([^\]]+)\]/g, ":$1")

.replaceAll(/\([^)]+\)\//g, "")
.replace(/^\./, "")

const importName = `i${index}`
imports.push(`import ${importName} from "../${file.replace(".ts", "")}"`)
routes[routePath] = importName
Expand All @@ -47,7 +50,7 @@ ${Object.entries(routes)
}

async function watch() {
const watchPath = path.resolve(__dirname, "..", "./client/pages/(main)")
const watchPath = path.resolve(__dirname, "..", "./client/pages")
console.info("Watching metadata files...")

await generateMetaMap()
Expand Down
20 changes: 13 additions & 7 deletions apps/server/src/lib/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,9 @@ import { ofetch } from "ofetch"
import PKG from "../../../../package.json"
import { isDev } from "./env"

export const createApiClient = () => {
const authSessionToken = getTokenFromCookie(requestContext.get("req")?.headers.cookie || "")

const getBaseURL = () => {
const req = requestContext.get("req")!

const { host } = req.headers

let baseURL = env.VITE_EXTERNAL_API_URL || env.VITE_API_URL

if (env.VITE_EXTERNAL_API_URL?.startsWith("/")) {
Expand All @@ -29,11 +25,14 @@ export const createApiClient = () => {
if (upstreamEnv === "prod" && env.VITE_EXTERNAL_PROD_API_URL) {
baseURL = env.VITE_EXTERNAL_PROD_API_URL
}
return baseURL
}
export const createApiFetch = () => {
const baseURL = getBaseURL()

const apiFetch = ofetch.create({
return ofetch.create({
credentials: "include",
retry: false,

onRequest(context) {
if (isDev) console.info(`request: ${context.request}`)

Expand All @@ -44,7 +43,14 @@ export const createApiClient = () => {
return
}
},
baseURL,
})
}
export const createApiClient = () => {
const authSessionToken = getTokenFromCookie(requestContext.get("req")?.headers.cookie || "")

const baseURL = getBaseURL()
const apiFetch = createApiFetch()

const apiClient = hc<AppType>(baseURL, {
fetch: async (input: any, options = {}) => apiFetch(input.toString(), options),
Expand Down
12 changes: 7 additions & 5 deletions apps/server/src/meta-handler.map.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// This file is generated by `pnpm run meta`
import i1 from "../client/pages/(main)/share/feeds/[id]/metadata"
import i2 from "../client/pages/(main)/share/lists/[id]/metadata"
import i0 from "../client/pages/(main)/share/users/[id]/metadata"
import i0 from ".././client/pages/(login)/login/metadata"
import i3 from ".././client/pages/(main)/share/feeds/[id]/metadata"
import i2 from ".././client/pages/(main)/share/lists/[id]/metadata"
import i1 from ".././client/pages/(main)/share/users/[id]/metadata"

export default {
"/share/users/:id": i0,
"/share/feeds/:id": i1,
"/login": i0,
"/share/users/:id": i1,
"/share/lists/:id": i2,
"/share/feeds/:id": i3,
}

0 comments on commit e0661ff

Please sign in to comment.