Skip to content

Commit

Permalink
Fix image cache for vector and animated images
Browse files Browse the repository at this point in the history
  • Loading branch information
Kanta Kodama committed Dec 26, 2020
1 parent 9b3edd3 commit db7e514
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions packages/next/next-server/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,17 +217,19 @@ export async function imageOptimizer(
}
}

const expireAt = maxAge * 1000 + now

if (upstreamType) {
const vector = VECTOR_TYPES.includes(upstreamType)
const animate =
ANIMATABLE_TYPES.includes(upstreamType) && isAnimated(upstreamBuffer)
if (vector || animate) {
await writeToCacheDir(hashDir, upstreamType, expireAt, upstreamBuffer)
sendResponse(req, res, upstreamType, upstreamBuffer)
return { finished: true }
}
}

const expireAt = maxAge * 1000 + now
let contentType: string

if (mimeType) {
Expand Down Expand Up @@ -275,11 +277,7 @@ export async function imageOptimizer(
}

const optimizedBuffer = await transformer.toBuffer()
await promises.mkdir(hashDir, { recursive: true })
const extension = getExtension(contentType)
const etag = getHash([optimizedBuffer])
const filename = join(hashDir, `${expireAt}.${etag}.${extension}`)
await promises.writeFile(filename, optimizedBuffer)
await writeToCacheDir(hashDir, contentType, expireAt, optimizedBuffer)
sendResponse(req, res, contentType, optimizedBuffer)
} catch (error) {
sendResponse(req, res, upstreamType, upstreamBuffer)
Expand All @@ -288,6 +286,19 @@ export async function imageOptimizer(
return { finished: true }
}

async function writeToCacheDir(
dir: string,
contentType: string,
expireAt: number,
buffer: Buffer
) {
await promises.mkdir(dir, { recursive: true })
const extension = getExtension(contentType)
const etag = getHash([buffer])
const filename = join(dir, `${expireAt}.${etag}.${extension}`)
await promises.writeFile(filename, buffer)
}

function sendResponse(
req: IncomingMessage,
res: ServerResponse,
Expand Down

0 comments on commit db7e514

Please sign in to comment.