2017-02-24 21:45:18 +00:00
|
|
|
// Polyfill Node with `Intl` that has data for all locales.
|
|
|
|
// See: https://formatjs.io/guides/runtime-environments/#server
|
|
|
|
const IntlPolyfill = require('intl')
|
|
|
|
Intl.NumberFormat = IntlPolyfill.NumberFormat
|
|
|
|
Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat
|
|
|
|
|
2018-12-17 16:34:32 +00:00
|
|
|
const { readFileSync } = require('fs')
|
|
|
|
const { basename } = require('path')
|
|
|
|
const { createServer } = require('http')
|
2017-02-24 21:45:18 +00:00
|
|
|
const accepts = require('accepts')
|
|
|
|
const glob = require('glob')
|
|
|
|
const next = require('next')
|
|
|
|
|
2017-08-10 18:15:46 +00:00
|
|
|
const port = parseInt(process.env.PORT, 10) || 3000
|
2017-02-24 21:45:18 +00:00
|
|
|
const dev = process.env.NODE_ENV !== 'production'
|
2018-12-17 16:34:32 +00:00
|
|
|
const app = next({ dev })
|
2017-02-24 21:45:18 +00:00
|
|
|
const handle = app.getRequestHandler()
|
|
|
|
|
|
|
|
// Get the supported languages by looking for translations in the `lang/` dir.
|
2018-12-17 16:34:32 +00:00
|
|
|
const supportedLanguages = glob
|
|
|
|
.sync('./lang/*.json')
|
|
|
|
.map(f => basename(f, '.json'))
|
2017-02-24 21:45:18 +00:00
|
|
|
|
|
|
|
// We need to expose React Intl's locale data on the request for the user's
|
|
|
|
// locale. This function will also cache the scripts by lang in memory.
|
|
|
|
const localeDataCache = new Map()
|
2018-12-17 16:34:32 +00:00
|
|
|
const getLocaleDataScript = locale => {
|
2017-02-24 21:45:18 +00:00
|
|
|
const lang = locale.split('-')[0]
|
|
|
|
if (!localeDataCache.has(lang)) {
|
|
|
|
const localeDataFile = require.resolve(`react-intl/locale-data/${lang}`)
|
|
|
|
const localeDataScript = readFileSync(localeDataFile, 'utf8')
|
|
|
|
localeDataCache.set(lang, localeDataScript)
|
|
|
|
}
|
|
|
|
return localeDataCache.get(lang)
|
|
|
|
}
|
|
|
|
|
|
|
|
// We need to load and expose the translations on the request for the user's
|
|
|
|
// locale. These will only be used in production, in dev the `defaultMessage` in
|
|
|
|
// each message description in the source code will be used.
|
2018-12-17 16:34:32 +00:00
|
|
|
const getMessages = locale => {
|
2017-02-24 21:45:18 +00:00
|
|
|
return require(`./lang/${locale}.json`)
|
|
|
|
}
|
|
|
|
|
|
|
|
app.prepare().then(() => {
|
|
|
|
createServer((req, res) => {
|
|
|
|
const accept = accepts(req)
|
2018-12-03 17:10:31 +00:00
|
|
|
const locale = accept.language(accept.languages(supportedLanguages)) || 'en'
|
2017-02-24 21:45:18 +00:00
|
|
|
req.locale = locale
|
|
|
|
req.localeDataScript = getLocaleDataScript(locale)
|
|
|
|
req.messages = dev ? {} : getMessages(locale)
|
|
|
|
handle(req, res)
|
2018-12-17 16:34:32 +00:00
|
|
|
}).listen(port, err => {
|
2017-02-24 21:45:18 +00:00
|
|
|
if (err) throw err
|
2017-08-10 18:15:46 +00:00
|
|
|
console.log(`> Ready on http://localhost:${port}`)
|
2017-02-24 21:45:18 +00:00
|
|
|
})
|
|
|
|
})
|