File size: 1,832 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// eslint-disable-next-line import/no-nodejs-modules
import { readFile } from 'fs/promises';
import { defaultI18n } from '@wordpress/i18n';
import { I18N } from 'i18n-calypso';
import getAssetFilePath from 'calypso/lib/get-asset-file-path';
import { getLanguageFile } from 'calypso/lib/i18n-utils/switch-locale';
import config from 'calypso/server/config';
import { LOCALE_SET } from 'calypso/state/action-types';

export function ssrSetupLocaleMiddleware() {
	const translationsCache = {};

	return function ssrSetupLocale( context, next ) {
		function setLocaleData( localeData ) {
			const i18n = new I18N();
			i18n.setLocale( localeData );
			if ( localeData ) {
				defaultI18n.setLocaleData( localeData );
			} else {
				defaultI18n.resetLocaleData();
			}

			const localeSlug = i18n.getLocaleSlug();
			const localeVariant = i18n.getLocaleVariant();
			context.store.dispatch( { type: LOCALE_SET, localeSlug, localeVariant } );
			context.lang = localeVariant || localeSlug;
			context.i18n = i18n;
			next();
		}

		const { lang } = context.params;

		if ( ! lang ) {
			setLocaleData( null );
			return;
		}

		if ( ! config( 'magnificent_non_en_locales' ).includes( lang ) ) {
			context.res.redirect( context.path.replace( `/${ lang }`, '' ) );
			return;
		}

		const cachedTranslations = translationsCache[ lang ];
		if ( cachedTranslations ) {
			setLocaleData( cachedTranslations );
		} else {
			readFile( getAssetFilePath( `languages/${ lang }-v1.1.json` ), 'utf-8' )
				.then( ( data ) => JSON.parse( data ) )
				// Fall back to the remote one if the local translation file is not found.
				.catch( () => getLanguageFile( lang ) )
				.then( ( translations ) => {
					translationsCache[ lang ] = translations;
					setLocaleData( translations );
				} )
				.catch( () => setLocaleData( null ) );
		}
	};
}