You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.js 1.8KB

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