Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

main.js 1.7KB

1 månad sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { logger } from 'log';
  2. import { Cookies, SetCookie } from 'cookies';
  3. function getLanguageCookieValue(country) {
  4. let languageCookieValue = '';
  5. if (country === 'US') {
  6. languageCookieValue = 'en_US';
  7. } else if (country === 'KR') {
  8. languageCookieValue = 'ko_KR';
  9. } else if (country === 'ES') {
  10. languageCookieValue = 'es_ES';
  11. } else if (country === 'FR') {
  12. languageCookieValue = 'fr_FR';
  13. } else if (country === 'DE') {
  14. languageCookieValue = 'de_DE';
  15. }
  16. return languageCookieValue;
  17. }
  18. export function onClientRequest(request) {
  19. let cookies = new Cookies(request.getHeader('Cookie'));
  20. let languageCookie = cookies.get('language');
  21. logger.log('language cookie value: %s', languageCookie);
  22. if (languageCookie) {
  23. logger.log('language cookie exists. Do nothing.');
  24. } else {
  25. let country = request.userLocation.country;
  26. if (country) {
  27. let languageCookieValue = getLanguageCookieValue(country);
  28. if (languageCookieValue) {
  29. let headers = { 'Location': ['/'], 'X-Redirect': [languageCookieValue] };
  30. request.respondWith(302, headers, {});
  31. } else {
  32. logger.log('cannot find languageCookieValue. Do nothing.');
  33. }
  34. } else {
  35. logger.log('cannot find country code. Do nothing.');
  36. }
  37. }
  38. }
  39. export function onClientResponse(request, response) {
  40. logger.log('Adding a header in ClientResponse');
  41. let languageCookieValue = response.getHeader('X-Redirect');
  42. if (languageCookieValue) {
  43. let cookie = new SetCookie();
  44. cookie.name = 'language';
  45. cookie.value = languageCookieValue;
  46. response.setHeader('Set-Cookie', cookie.toHeader());
  47. response.setHeader('X-GeoRedirect', 'True');
  48. } else {
  49. response.setHeader('X-GeoRedirect', 'False')
  50. }
  51. }