1+ import fs from 'fs'
12import path from 'path'
23import slash from 'slash'
34import {
@@ -10,10 +11,24 @@ import isArchivedVersion from '../lib/is-archived-version.js'
1011import got from 'got'
1112import readJsonFile from '../lib/read-json-file.js'
1213import { cacheControlFactory } from './cache-control.js'
13- const archivedRedirects = readJsonFile (
14+
15+ function readJsonFileLazily ( xpath ) {
16+ const cache = new Map ( )
17+ // This will throw if the file isn't accessible at all, e.g. ENOENT
18+ fs . accessSync ( xpath )
19+ return ( ) => {
20+ if ( ! cache . has ( xpath ) ) cache . set ( xpath , readJsonFile ( xpath ) )
21+ return cache . get ( xpath )
22+ }
23+ }
24+
25+ // These files are huge so lazy-load them. But note that the
26+ // `readJsonFileLazily()` function will, at import-time, check that
27+ // the path does exist.
28+ const archivedRedirects = readJsonFileLazily (
1429 './lib/redirects/static/archived-redirects-from-213-to-217.json'
1530)
16- const archivedFrontmatterFallbacks = readJsonFile (
31+ const archivedFrontmatterFallbacks = readJsonFileLazily (
1732 './lib/redirects/static/archived-frontmatter-fallbacks.json'
1833)
1934
@@ -55,7 +70,9 @@ export default async function archivedEnterpriseVersions(req, res, next) {
5570 versionSatisfiesRange ( requestedVersion , `>=${ firstVersionDeprecatedOnNewSite } ` ) &&
5671 versionSatisfiesRange ( requestedVersion , `<=${ lastVersionWithoutArchivedRedirectsFile } ` )
5772 ) {
58- const redirect = archivedRedirects [ req . path ]
73+ // `archivedRedirects` is a callable because it's a lazy function
74+ // and memoized so calling it is cheap.
75+ const redirect = archivedRedirects ( ) [ req . path ]
5976 if ( redirect && redirect !== req . path ) {
6077 cacheControl ( res )
6178 return res . redirect ( 301 , redirect )
@@ -122,7 +139,9 @@ function getFallbackRedirects(req, requestedVersion) {
122139 if ( versionSatisfiesRange ( requestedVersion , `<${ firstVersionDeprecatedOnNewSite } ` ) ) return
123140 if ( versionSatisfiesRange ( requestedVersion , `>${ lastVersionWithoutArchivedRedirectsFile } ` ) ) return
124141
125- return archivedFrontmatterFallbacks . find ( ( arrayOfFallbacks ) =>
142+ // `archivedFrontmatterFallbacks` is a callable because it's a lazy function
143+ // and memoized so calling it is cheap.
144+ return archivedFrontmatterFallbacks ( ) . find ( ( arrayOfFallbacks ) =>
126145 arrayOfFallbacks . includes ( req . path )
127146 )
128147}
0 commit comments