0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-06 20:40:08 -05:00

refactor(core,cloud): disable cache for index files

This commit is contained in:
Gao Sun 2023-03-11 16:09:22 +08:00
parent 6b12d345a7
commit 844d6d2e8c
No known key found for this signature in database
GPG key ID: 13EBE123E4773688
2 changed files with 23 additions and 4 deletions

View file

@ -30,6 +30,11 @@ export type WithSpaConfig = {
* @default 'index.html'
*/
indexPath?: string;
/**
* Explicitly disable cache for the index file in order to keep fresh and avoid cache invalidation issues.
* @default true
*/
disableIndexCache?: boolean;
};
export default function withSpa<InputContext extends RequestContext>({
@ -38,6 +43,7 @@ export default function withSpa<InputContext extends RequestContext>({
pathname: rootPathname = '/',
ignorePathnames,
indexPath: index = 'index.html',
disableIndexCache = true,
}: WithSpaConfig) {
assert(root, new Error('Root directory is required to serve files.'));
@ -69,6 +75,7 @@ export default function withSpa<InputContext extends RequestContext>({
return next({ ...context, status: 404 });
}
const [originalPath] = result;
const [pathLike, stat, compression] = (await tryCompressedFile(request, result[0])) ?? result;
return next({
@ -77,9 +84,12 @@ export default function withSpa<InputContext extends RequestContext>({
...headers,
...(compression && { 'Content-Encoding': compression }),
...(!compression && { 'Content-Length': stat.size }),
'Content-Type': mime.lookup(result[0]), // Use the original path to lookup
'Content-Type': mime.lookup(originalPath),
'Last-Modified': stat.mtime.toUTCString(),
'Cache-Control': `max-age=${maxAge}`,
'Cache-Control':
disableIndexCache && originalPath === indexPath
? 'no-cache, no-store, must-revalidate'
: `max-age=${maxAge}`,
ETag: `"${stat.size.toString(16)}-${stat.mtimeMs.toString(16)}"`,
},
stream: createReadStream(pathLike),

View file

@ -7,23 +7,32 @@ import send from 'koa-send';
import assertThat from '#src/utils/assert-that.js';
const index = 'index.html';
export default function serve(root: string) {
assertThat(root, new Error('Root directory is required to serve files.'));
const options: send.SendOptions = {
root: path.resolve(root),
index: 'index.html',
index,
};
const serve: MiddlewareType = async (ctx, next) => {
if (ctx.method === 'HEAD' || ctx.method === 'GET') {
await send(ctx, ctx.path, {
const filePath = await send(ctx, ctx.path, {
...options,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
...(!['/', `/${options.index || ''}`].some((path) => ctx.path.endsWith(path)) && {
maxage: 604_800_000 /* 7 days */,
}),
});
const filename = path.basename(filePath);
// No cache for the index file
if (filename === index || filename.startsWith(index + '.')) {
ctx.set('Cache-Control', 'no-cache, no-store, must-revalidate');
}
}
return next();