Skip to content
This repository has been archived by the owner on Mar 12, 2023. It is now read-only.

Refetch expired images by using swr #95

Merged
merged 7 commits into from Jul 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 37 additions & 0 deletions __tests__/pages/api/blocks.test.ts
@@ -0,0 +1,37 @@
jest.mock('../../../src/lib/notion/blog-index-cache')

import { createMocks } from 'node-mocks-http'
import ApiBlocks from '../../../src/pages/api/blocks'

const slug = 'supported-blocks'

describe('/api/blocks', () => {
describe('not GET', () => {
test('returns 400', async () => {
const { req, res } = createMocks({ method: 'POST', url: `/api/blocks?slug=${slug}` });

await ApiBlocks(req, res)
expect(res.statusCode).toEqual(400)
})
})

describe('GET', () => {
describe('empty slug', () => {
test('returns 400', async () => {
const { req, res } = createMocks({ method: 'GET', url: '/api/blocks?slug=' });

await ApiBlocks(req, res)
expect(res.statusCode).toEqual(400)
})
})

describe('valid slug', () => {
test('returns 400', async () => {
const { req, res } = createMocks({ method: 'GET', url: `/api/blocks?slug=${slug}` });

await ApiBlocks(req, res)
expect(res.statusCode).toEqual(200)
})
})
})
})
6 changes: 4 additions & 2 deletions __tests__/pages/blog/[slug].test.tsx
Expand Up @@ -34,16 +34,18 @@ describe('RenderPost', () => {
const sameTagPosts = (await getPostsByTag(post.Tags[0], 6)).filter(
p => p.Slug !== post.Slug
)
const fallback = {}
fallback[slug] = blocks

const { container } = render(
<RenderPost
slug={slug}
post={post}
blocks={blocks}
rankedPosts={rankedPosts}
recentPosts={recentPosts}
sameTagPosts={sameTagPosts}
tags={tags}
redirect={null}
fallback={fallback}
/>
)
await waitFor(() => {
Expand Down
2 changes: 1 addition & 1 deletion __tests__/pages/blog/__snapshots__/[slug].test.tsx.snap
Expand Up @@ -205,7 +205,7 @@ exports[`RenderPost renders the page unchanged 1`] = `
<div>
<img
alt="画像が読み込まれない場合はページを更新してみてください。"
src="/notion_images/5d04be89-54da-482a-9391-efd465f74082.png"
src="https://s3.us-west-2.amazonaws.com/secure.notion-static.com/5d04be89-54da-482a-9391-efd465f74082/profile.png"
/>
</div>
<figcaption
Expand Down
5 changes: 4 additions & 1 deletion package.json
Expand Up @@ -19,6 +19,7 @@
"@dhaiwat10/react-link-preview": "^1.14.0",
"@notionhq/client": "^1.0.4",
"@types/mermaid": "^8.2.9",
"axios": "^0.27.2",
"image-size": "^1.0.1",
"mermaid": "^9.1.1",
"next": "12",
Expand All @@ -27,8 +28,9 @@
"react-dom": "^17.0.2",
"react-share": "^4.4.0",
"react-twitter-embed": "^4.0.4",
"react-youtube": "^9.0.2",
"shell-quote": "^1.7.3",
"react-youtube": "^9.0.2"
"swr": "^1.3.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.16.2",
Expand All @@ -41,6 +43,7 @@
"husky": "^8.0.1",
"jest": "^27.5.1",
"lint-staged": "^12.4.2",
"node-mocks-http": "^1.11.0",
"prettier": "^2.6.2",
"typescript": "^4.7.2"
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/notion-block.tsx
Expand Up @@ -117,7 +117,7 @@ const ImageBlock = ({ block }) => (
src={
block.Image.External
? block.Image.External.Url
: `/notion_images/${block.Id}.png`
: block.Image.File.Url
}
alt="画像が読み込まれない場合はページを更新してみてください。"
/>
Expand Down
10 changes: 1 addition & 9 deletions src/lib/notion/client.ts
Expand Up @@ -26,7 +26,6 @@ import {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { Client } = require('@notionhq/client')
import * as blogIndexCache from './blog-index-cache'
import * as imageCache from './image-cache'

const client = new Client({
auth: NOTION_API_SECRET,
Expand Down Expand Up @@ -443,7 +442,7 @@ export async function getAllBlocksByBlockId(blockId) {
if (item.image.type === 'external') {
image.External = { Url: item.image.external.url }
} else {
image.File = { Url: item.image.file.url }
image.File = { Url: item.image.file.url, ExpiryTime: item.image.file.expiry_time }
}

block.Image = image
Expand Down Expand Up @@ -546,13 +545,6 @@ export async function getAllBlocksByBlockId(blockId) {
block.BulletedListItem.Children = await getAllBlocksByBlockId(block.Id)
} else if (block.Type === 'numbered_list_item' && block.HasChildren) {
block.NumberedListItem.Children = await getAllBlocksByBlockId(block.Id)
} else if (
block.Type === 'image' &&
block.Image.File &&
block.Image.File.Url
) {
// Cache image to local (only type: file)
imageCache.store(block.Id, block.Image.File.Url)
}
}

Expand Down
1 change: 1 addition & 0 deletions src/lib/notion/interfaces.ts
Expand Up @@ -81,6 +81,7 @@ export interface Video {

export interface File {
Url: string
ExpiryTime?: string
}

export interface External {
Expand Down
43 changes: 43 additions & 0 deletions src/pages/api/blocks.ts
@@ -0,0 +1,43 @@
import { NextApiRequest, NextApiResponse } from 'next'

import {
getPostBySlug,
getAllBlocksByBlockId,
} from '../../lib/notion/client'

const ApiBlocks = async function(req: NextApiRequest, res: NextApiResponse) {
res.setHeader('Content-Type', 'application/json')

if (req.method !== 'GET') {
res.statusCode = 400
res.end()
return
}

const { slug } = req.query

if (!slug) {
res.statusCode = 400
res.end()
return
}

try {
const post = await getPostBySlug(slug as string)
if (!post) {
throw new Error(`post not found. slug: ${slug}`)
}

const blocks = await getAllBlocksByBlockId(post.PageId)

res.write(JSON.stringify(blocks))
res.statusCode = 200
res.end()
} catch (e) {
console.log(e)
res.statusCode = 500
res.end()
}
}

export default ApiBlocks
51 changes: 38 additions & 13 deletions src/pages/blog/[slug].tsx
@@ -1,8 +1,10 @@
import React, { useEffect } from 'react'
import { useRouter } from 'next/router'
import React from 'react'
import useSWR from "swr"
import axios from 'axios'

import { NEXT_PUBLIC_URL } from '../../lib/notion/server-constants'
import DocumentHead from '../../components/document-head'
import { Block } from '../../lib/notion/interfaces'
import {
BlogPostLink,
BlogTagLink,
Expand Down Expand Up @@ -53,14 +55,18 @@ export async function getStaticProps({ params: { slug } }) {
getPostsByTag(post.Tags[0], 6),
])

const fallback = {}
fallback[slug] = blocks

return {
props: {
slug,
post,
blocks,
rankedPosts,
recentPosts,
tags,
sameTagPosts: sameTagPosts.filter(p => p.Slug !== post.Slug),
fallback,
},
revalidate: 60,
}
Expand All @@ -74,24 +80,43 @@ export async function getStaticPaths() {
}
}

const fetchBlocks = async (slug: string): Promise<Array<Block>> => {
try {
const { data: blocks } = await axios.get(`/api/blocks?slug=${slug}`)
return blocks as Array<Block>
} catch (error) {
console.log(error)
}
}

const includeExpiredImage = (blocks: Array<Block>): boolean => {
const now = Date.now()

blocks.forEach(block => {
if (block.Type === 'image') {
const image = block.Image
if (image.File && image.File.ExpiryTime && Date.parse(image.File.ExpiryTime) < now) {
return true
}
}
// TODO: looking for the image block in Children recursively
})

return false
}

const RenderPost = ({
slug,
post,
blocks = [],
rankedPosts = [],
recentPosts = [],
sameTagPosts = [],
tags = [],
redirect,
fallback,
}) => {
const router = useRouter()
const { data: blocks, error } = useSWR(includeExpiredImage(fallback[slug]) && slug, fetchBlocks, { fallbackData: fallback[slug] })

useEffect(() => {
if (redirect && !post) {
router.replace(redirect)
}
}, [router, redirect, post])

if (!post) {
if (error || !blocks) {
return <PostsNotFound />
}

Expand Down