| 99 | * @returns {Promise<{ source: string; filename: string }>} |
| 100 | */ |
| 101 | const _getMarkdownFile = async (locale = '', pathname = '') => { |
| 102 | const normalizedPathname = normalize(pathname).replace('.', ''); |
| 103 | |
| 104 | // This verifies if the given pathname actually exists on our Map |
| 105 | // meaning that the route exists on the website and can be rendered |
| 106 | if (pathnameToFilename.has(normalizedPathname)) { |
| 107 | const filename = pathnameToFilename.get(normalizedPathname); |
| 108 | const filepath = normalize(`${pagesDirectory}/${locale}/${filename}`); |
| 109 | |
| 110 | // We verify if our Markdown cache already has a cache entry for a localized |
| 111 | // version of this file, because if not, it means that either |
| 112 | // we did not cache this file yet or there is no localized version of this file |
| 113 | if (cachedMarkdownFiles.has(`${locale}${normalizedPathname}`)) { |
| 114 | const fileContent = cachedMarkdownFiles.get( |
| 115 | `${locale}${normalizedPathname}` |
| 116 | ); |
| 117 | |
| 118 | return { source: fileContent, filename }; |
| 119 | } |
| 120 | |
| 121 | // Attempts to read a file or simply (and silently) fail, as the file might |
| 122 | // simply not exist or whatever other reason that might cause the file to not be read |
| 123 | const fileLanguageContent = await readFile(filepath, 'utf8').catch( |
| 124 | () => undefined |
| 125 | ); |
| 126 | |
| 127 | // No cache hit exists, so we check if the localized file actually |
| 128 | // exists within our file system and if it does we set it on the cache |
| 129 | // and return the current fetched result; |
| 130 | if (fileLanguageContent && typeof fileLanguageContent === 'string') { |
| 131 | cachedMarkdownFiles.set( |
| 132 | `${locale}${normalizedPathname}`, |
| 133 | fileLanguageContent |
| 134 | ); |
| 135 | |
| 136 | return { source: fileLanguageContent, filename }; |
| 137 | } |
| 138 | |
| 139 | // Prevent infinite loops as if at this point the file does not exist with the default locale |
| 140 | // then there must be an issue on the file system or there's an error on the mapping of paths to files |
| 141 | if (locale === defaultLocale.code) { |
| 142 | return { filename: '', source: '' }; |
| 143 | } |
| 144 | |
| 145 | // We attempt to retrieve the source version (defaultLocale) of the file as there is no localised version |
| 146 | // of the file and we set it on the cache to prevent future checks of the same locale for this file |
| 147 | const { source: fileContent } = await _getMarkdownFile( |
| 148 | defaultLocale.code, |
| 149 | pathname |
| 150 | ); |
| 151 | |
| 152 | // We set the source file on the localized cache to prevent future checks |
| 153 | // of the same locale for this file and improve read performance |
| 154 | cachedMarkdownFiles.set(`${locale}${normalizedPathname}`, fileContent); |
| 155 | |
| 156 | return { source: fileContent, filename }; |
| 157 | } |
| 158 | |