Skip to content

Commit 2669bf6

Browse files
committed
feat: added route data and cleanup
1 parent 1b6c98d commit 2669bf6

File tree

3 files changed

+92
-49
lines changed

3 files changed

+92
-49
lines changed

src/helpers/blobs/cacheFormat.ts

Lines changed: 65 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -5,47 +5,83 @@ import path from 'path'
55

66
import pkg from 'fs-extra'
77

8-
import { BUILD_DIR, SERVER_DIR } from '../constants.js'
9-
8+
import { NEXT_DIR, SERVER_DIR } from '../constants.js'
109
// readfile not available in esm version of fs-extra
1110
const { readFile } = pkg
1211

13-
1412
export const removeFileDir = (file: string, num: number) => {
1513
return file.split('/').slice(num).join('/')
1614
}
1715

18-
19-
export const formatPageData = async (pathname: string, key: string, file: string) => {
16+
export const formatBlobContent = async (pathname: string, key: string, file: string) => {
2017
const isPage = pathname.startsWith('pages')
2118
const isApp = pathname.startsWith('app')
22-
const removedDir = removeFileDir(pathname, 1).replace(path.extname(file), '')
23-
// console.log({pathname, key, file, isPage, isApp, removedDir} )
19+
const isFetchCache = file.startsWith('cache/fetch-cache')
20+
const isRoute = file.endsWith('body')
21+
2422
let data: any = {}
25-
if( isApp || isPage ){
26-
console.log("WIHTIN APP + PAGE CHECK")
27-
const getDataFile = async (files: string, appDir: boolean, ext: string) =>
28-
await readFile(
29-
join(SERVER_DIR, (appDir ? 'app' : 'pages'), `${files}.${ext}`),
30-
'utf8')
31-
32-
const pageData = isPage ? JSON.parse(await getDataFile(removedDir, false,'json')) : await getDataFile(removedDir, true, 'rsc')
33-
let meta: { status?: number, headers?: OutgoingHttpHeaders } = {}
34-
35-
try{
36-
meta = JSON.parse((await getDataFile(key, true, 'meta')))
37-
}catch{}
38-
39-
data = {
23+
24+
if( !isRoute && (isApp || isPage) ){
25+
data = await formatPage(isPage, file, pathname)
26+
}
27+
28+
if( isFetchCache ){
29+
data = await formatFetchCache(file)
30+
}
31+
32+
if(isRoute){
33+
data = await formatRoute(file, key, pathname)
34+
}
35+
return data
36+
}
37+
38+
const readFileData = async (files: string, appDir: boolean, ext: string) =>
39+
await readFile(
40+
join(SERVER_DIR, (appDir ? 'app' : 'pages'), `${files}.${ext}`),
41+
'utf8')
42+
43+
const formatPage = async (page: boolean, file: string, pathname: string) => {
44+
const removedDir = removeFileDir(pathname, 1).replace(path.extname(file), '')
45+
const pageData = page ? JSON.parse(await readFileData(removedDir, false,'json')) : await readFileData(removedDir, true, 'rsc')
46+
let meta: { status?: number, headers?: OutgoingHttpHeaders } = {}
47+
48+
try{
49+
meta = JSON.parse((await readFileData(removedDir, true, 'meta')))
50+
}catch{}
51+
52+
return {
4053
lastModified: Date.now(),
4154
value: {
42-
kind: 'PAGE',
43-
html: await readFile(join(BUILD_DIR, file), 'utf8'),
44-
pageData,
45-
headers: meta.headers,
46-
status: meta.status,
55+
kind: 'PAGE',
56+
html: await readFile(join(NEXT_DIR, file), 'utf8'),
57+
pageData,
58+
headers: meta.headers,
59+
status: meta.status,
4760
}
48-
}
4961
}
50-
return data
62+
}
63+
64+
const formatFetchCache = async (file: string) => {
65+
const parsedData = JSON.parse(await readFile(join(NEXT_DIR, file), 'utf8'))
66+
return {
67+
lastModified: Date.now(),
68+
value: parsedData,
69+
}
70+
}
71+
72+
const formatRoute = async (file: string, key: string, pathname: string) => {
73+
const removedDir = removeFileDir(pathname, 1).replace(path.extname(file), '')
74+
try{
75+
// const data = await readFileData(removedDir, true, 'body')
76+
const meta = JSON.parse(await readFileData(removedDir, true, 'meta'))
77+
return{
78+
lastModified: Date.now(),
79+
value: {
80+
kind: 'ROUTE',
81+
// body: data,
82+
headers: meta.headers,
83+
status: meta.status,
84+
}
85+
}
86+
}catch{}
5187
}

src/helpers/constants.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@ export const WORKING_DIR = process.cwd()
77

88
export const BUILD_DIR = `${WORKING_DIR}/.netlify`
99
export const RUN_DIR = WORKING_DIR
10-
export const SERVER_DIR = `${BUILD_DIR}/server`
11-
export const STANDALONE_BUILD_DIR = `${BUILD_DIR}/standalone`
12-
export const FETCH_CACHE_DIR = `${BUILD_DIR}/cache/fetch-cache`
10+
export const NEXT_DIR = `${BUILD_DIR}/.next`
11+
export const SERVER_DIR = `${NEXT_DIR}/server`
12+
export const STANDALONE_BUILD_DIR = `${NEXT_DIR}/standalone`
13+
export const FETCH_CACHE_DIR = `${NEXT_DIR}/cache/fetch-cache`
1314

1415
export const SERVER_FUNCTIONS_DIR = `${WORKING_DIR}/.netlify/functions-internal`
1516
export const SERVER_HANDLER_NAME = '___netlify-server-handler'

src/helpers/files.ts

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@ import { outdent } from 'outdent'
99
import pLimit from 'p-limit'
1010

1111
import { getNormalizedBlobKey, netliBlob } from './blobs/blobs.cjs'
12-
import { removeFileDir, formatPageData } from './blobs/cacheFormat.js'
13-
import { BUILD_DIR, STANDALONE_BUILD_DIR } from './constants.js'
12+
import { removeFileDir, formatBlobContent } from './blobs/cacheFormat.js'
13+
import { NEXT_DIR, STANDALONE_BUILD_DIR } from './constants.js'
1414

1515
/**
1616
* Move the Next.js build output from the publish dir to a temp dir
1717
*/
1818
export const stashBuildOutput = async ({ PUBLISH_DIR }: NetlifyPluginConstants) => {
19-
await move(PUBLISH_DIR, `${BUILD_DIR}/.next`, { overwrite: true })
19+
await move(PUBLISH_DIR, `${NEXT_DIR}`, { overwrite: true })
2020

2121
// remove prerendered content from the standalone build (it's also in the main build dir)
2222
const prerenderedContent = await getPrerenderedContent(STANDALONE_BUILD_DIR)
@@ -42,7 +42,8 @@ const getPrerenderedContent = async (cwd: string): Promise<string[]> => {
4242
*/
4343
export const storePrerenderedContent = async ({ NETLIFY_API_TOKEN, SITE_ID }:
4444
{
45-
NETLIFY_API_TOKEN: string, SITE_ID: string
45+
NETLIFY_API_TOKEN: string,
46+
SITE_ID: string
4647
}) => {
4748
const deployID = `${process.env.DEPLOY_ID}`
4849
const blob = netliBlob(NETLIFY_API_TOKEN, deployID, SITE_ID)
@@ -55,8 +56,7 @@ export const storePrerenderedContent = async ({ NETLIFY_API_TOKEN, SITE_ID }:
5556

5657
const uploadFilesToBlob = async (pathName: string, file: string) => {
5758
const key = path.basename(pathName, path.extname(pathName))
58-
const content = await formatPageData(pathName, key, file)
59-
console.log(content)
59+
const content = await formatBlobContent(pathName, key, file)
6060
try{
6161
await blob.setJSON(getNormalizedBlobKey(key), content)
6262
}catch(error){
@@ -65,29 +65,35 @@ export const storePrerenderedContent = async ({ NETLIFY_API_TOKEN, SITE_ID }:
6565
}
6666

6767
// todo: test it on demo with pages dir
68-
const prerenderedContent = await getPrerenderedContent(BUILD_DIR)
69-
70-
prerenderedContent.map((rawPath) => {
68+
// eslint-disable-next-line unicorn/no-await-expression-member
69+
(await getPrerenderedContent(NEXT_DIR)).map((rawPath: string) => {
7170
const cacheFile = rawPath.startsWith('cache')
72-
const hasHtml = Boolean(rawPath.endsWith('.html'))
73-
74-
// Removing app, page, and cache/fetch-cache from file path
7571
const pathKey = removeFileDir(rawPath, (cacheFile ? 2 : 1))
76-
const errorPages = pathKey.includes('404') || pathKey.includes('500')
77-
78-
// Checking for blob access before uploading
79-
if( hasHtml && !errorPages ){
72+
const files = findCacheFiles(pathKey, rawPath)
73+
74+
if(files){
8075
return limit(uploadFilesToBlob, pathKey, rawPath)
8176
}
8277
})
8378
}
8479

80+
const findCacheFiles = (pathKey: string, rawPath: string) => {
81+
const errorPages = pathKey.includes('404') || pathKey.includes('500')
82+
const isFetchCache = rawPath.startsWith('cache/fetch-cache')
83+
const isRoute = rawPath.endsWith('.body')
84+
const hasHtml = rawPath.endsWith('.html')
85+
86+
if (hasHtml && !errorPages || isFetchCache || isRoute){
87+
return true
88+
}
89+
}
90+
8591
/**
8692
* Move static assets to the publish dir so they are uploaded to the CDN
8793
*/
8894
export const publishStaticAssets = ({ PUBLISH_DIR }: NetlifyPluginConstants) => {
8995
return Promise.all([
9096
copy('public', PUBLISH_DIR),
91-
copy(`${BUILD_DIR}/.next/static/`, `${PUBLISH_DIR}/_next/static`),
97+
copy(`${NEXT_DIR}/static/`, `${PUBLISH_DIR}/_next/static`),
9298
])
9399
}

0 commit comments

Comments
 (0)