使用功能在Firebase上服务i18n角度应用

时间:2019-01-24 05:41:21

标签: angular firebase express internationalization google-cloud-functions

我正在尝试正确处理对Firebase上托管的本地化角度应用程序的请求。目标是根据以下条件加载正确的应用程序捆绑包:1)名为locale的cookie。 2)accept-language标头。 3)当其他人不可用时,默认设置为en-us

在使用i18n本地化角度应用程序时,angular-cli会为angular.json中存在的每种语言/地区生成捆绑包(您的应用程序的版本)。 Firebase将您的捆绑包作为静态内容提供,并且具有严格的安全度量,不允许遍历路径。

我尝试在firebase.json中设置 rewrites redirects ,但是没有拦截locale cookie的功能。然后,我使用云函数来读取Cookie,解析请求并使用expresscookie-parserexpress-locale返回正确的资源。

1。仅使用托管

firebase.json

{
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/en-us/**",
        "destination": "/en-us/index.html"
      },
      {
        "source": "/es-co/**",
        "destination": "/es-co/index.html"
      },
      {
        "source": "/zh-hans/**",
        "destination": "/zh-hans/index.html"
      },
      {
        "source": "**",
        "destination": "/en-us/index.html"
      }
    ]
  }
}

2。使用云功能并表达

firebase.json

{
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ]
  },
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "function": "multilang"
      }
    ]
  }
}

functions / index.js

const express = require('express')
const expressLocale = require('express-locale')
const cookieParser = require('cookie-parser')
const functions = require('firebase-functions')
const path = require('path')
const fs = require('fs')
const _ = require('lodash')

const app = express()

const localeMap = {
  en: 'en_US',
  es: 'es_CO',
  zh: 'zh_TW',
  'en-US': 'en_US',
  'es-CO': 'es_CO',
  'zh-TW': 'zh_TW',
  'zh-Hans': 'zh_TW',
  en_US: 'en_US',
  es_CO: 'es_CO',
  zh_TW: 'zh_TW',
  zh_Hans: 'zh_TW'
}

const defaultLocale = 'en_US'

const baseMap = {
  en_US: 'en-us',
  es_CO: 'es-co',
  zh_TW: 'zh-hans'
}

app
  .use(cookieParser())
  .use(expressLocale({
    priority: ['cookie', 'accept-language', 'map', 'default'],
    default: defaultLocale,
    map: localeMap
  }))
  .use('**', (req, res, next) => {
    const locale = localeMap[req.locale.language]
    const sanitized = req.originalUrl.replace(/\.{2,}/g, '').replace(/\/{2,}/g, '/')
    const url = sanitized.split('/')
    const idx = url.length === 1 ? 0 : 1

    url[0] = _.values(baseMap).includes(url[idx]) ?
      url[idx] : (baseMap[locale] || baseMap[defaultLocale])

    if (url.length > 1 && url[0] === url[1]) {
      url.shift()
    }

    let file = path.resolve(`dist/${url.join('/')}`)

    if (!url[url.length - 1].match(/^[\w,\s-]+\.[a-z0-9]{2,4}$/) || !fs.existsSync(file)) {
      file = path.resolve(`dist/${url[0]}/index.html`)
    }

    res.sendFile(file)
  })

exports.multilang = functions.https.onRequest(app)

最后的设置非常适合index.html或任何其他请求文件的本地Firebase仿真解析路径(例如,ngsw-worker.js为渐进式应用程序支持)。

部署到Firebase时,即使将路径更改为:

,它也无法解析并找到托管文件(例如index.html)。

  • /${url[0]}/index.html
  • ../${url[0]}/index.html
  • /public/${url[0]}/index.html

或将req.sendFile重写为req.redirect

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

对于面临相同问题的任何人,这是使用Firebase函数的幼稚解决方案:

functions / index.js

char guess = '\0';
bool guessInputSuccess = false;

while (!guessInputSuccess)
{ 
    Console.Write("Guess your letter: ");

    char.TryParse(Console.ReadLine().ToLower(), out guess); 

    if (!char.IsLetter(guess))
    { 
        Console.Write("You have not entered a letter from a-z."); 
    }
    else
    { 
        guessInputSuccess = true; 
    } 
}

return guess; 

firebase.json

const express = require('express')
const cookieParser = require('cookie-parser')
const expressLocale = require('express-locale')
const functions = require('firebase-functions')

const localeMap = {
  en: 'en_US',
  es: 'es_CO',
  zh: 'zh_CN',
  en_US: 'en_US',
  es_CO: 'es_CO',
  zh_Hans: 'zh_CN'
}

const prefixMap = {
  en_US: 'en-us',
  es_CO: 'es-co',
  zh_CN: 'zh-hans',
}

const defaultLocale = 'en_US'
const app = express()

app
  .use(cookieParser())
  .use(expressLocale({
    priority: ['cookie', 'accept-language', 'map', 'default'],
    default: defaultLocale,
    map: localeMap
  }))
  .use('*', (req, res, next) => {
    const locale = localeMap[req.locale.language]
    const prefix = prefixMap[locale] || prefixMap[defaultLocale]
    res.redirect(`/${prefix}${req.originalUrl}`)
  })

exports.multilang = functions.https.onRequest(app)