Skip to content

Commit

Permalink
fix: server fetch lastest note
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <i@innei.in>
  • Loading branch information
Innei committed Apr 11, 2024
1 parent 787c7e7 commit 790d934
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
15 changes: 11 additions & 4 deletions src/app/(app)/notes/page.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import type { NoteWrappedWithLikedPayload } from '@mx-space/api-client'

import { attachServerFetchAuth, detachServerFetchAuth } from '~/lib/attach-ua'
import { getAuthFromCookie } from '~/lib/attach-ua'
import { AuthKeyNames } from '~/lib/cookie'
import { apiClient } from '~/lib/request'
import { definePrerenderPage } from '~/lib/request.server'

export default definePrerenderPage()({
async fetcher() {
attachServerFetchAuth()
const { data } = await apiClient.note.getLatest()
detachServerFetchAuth()
const { data } =
await apiClient.note.proxy.latest.get<NoteWrappedWithLikedPayload>({
params: {
token: getAuthFromCookie()
? `bearer ${getAuthFromCookie()}`
: undefined,
},
})

return data
},
Component: ({ data: { nid, hide } }) => {
Expand Down
14 changes: 11 additions & 3 deletions src/lib/attach-ua.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'server-only'

import { cookies, headers } from 'next/headers'

import PKG from '../../package.json'
Expand Down Expand Up @@ -25,11 +27,10 @@ export const attachServerFetch = () => {
}

export const attachServerFetchAuth = () => {
const cookie = cookies()
const jwt = cookie.get(AuthKeyNames[0])
const jwt = getAuthFromCookie()

if (jwt) {
attachFetchHeader('Authorization', `Bearer ${jwt.value}`)
attachFetchHeader('Authorization', `Bearer ${jwt}`)
} else {
attachFetchHeader('Authorization', '')
}
Expand All @@ -38,3 +39,10 @@ export const attachServerFetchAuth = () => {
export const detachServerFetchAuth = () => {
attachFetchHeader('Authorization', null)
}

export const getAuthFromCookie = () => {
const cookie = cookies()
const jwt = cookie.get(AuthKeyNames[0])

return jwt?.value || ''
}

0 comments on commit 790d934

Please sign in to comment.