Skip to content

Commit

Permalink
feat: add revalidate page feature
Browse files Browse the repository at this point in the history
  • Loading branch information
nabi-chan committed May 24, 2024
1 parent 578cadd commit a58c2cd
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/features/custom-pages/queries/useUpdatePageMutation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { useMutation } from '@tanstack/react-query'
import { merge } from 'immutable'
import { useToast } from '@channel.io/bezier-react'
import axios from 'axios'
import assert from 'assert'
import { supabase } from '@/supabase/client'
import type { Tables } from '@/supabase/types'

Expand All @@ -20,7 +22,19 @@ export function useUpdatePageMutation() {
.select('id')
.single()
.throwOnError(),
onSuccess: async () => {
onSuccess: async (_, { pageId }) => {
const {
data: { session },
} = await supabase.auth.getSession()
assert(session?.access_token, 'session.access_token is undefined')
await axios.patch<'ok'>('/api/page/invalidate', undefined, {
params: {
pageId,
},
headers: {
Authorization: `Bearer ${session.access_token}`,
},
})
addToast('성공적으로 수정되었습니다.', { preset: 'success' })
},
onError: async () => {
Expand Down
46 changes: 46 additions & 0 deletions src/pages/api/page/invalidate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import { isNull, toNumber } from 'lodash'
import { supabase } from '@/supabase/server'

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
switch (req.method) {
case 'PATCH': {
const { authorization } = req.headers
if (!authorization) {
return res.status(401).send('Unauthorized')
}

const token = authorization.replace('Bearer ', '')
const user = await supabase.auth.getUser(token)
if (user.error) {
return res.status(403).send('Forbidden')
}

if (!user.data) {
return res.status(404).send('Not Found')
}

const pageId = toNumber(req.query.pageId)
const { data: page } = await supabase
.from('CustomPage')
.select('slug')
.eq('id', pageId)
.single()
.throwOnError()

if (isNull(page)) {
return res.status(404).send('Not Found')
}

await res.revalidate(`/${page?.slug}`)
return res.status(200).send('ok')
}

default: {
return res.status(405).send('Method Not Allowed')
}
}
}

0 comments on commit a58c2cd

Please sign in to comment.