docs: fix accept-language handling

This commit is contained in:
bd_ 2023-10-11 20:26:54 +09:00
parent bd1bb55569
commit 8dd46c5576
3 changed files with 25 additions and 9 deletions

View File

@ -11,6 +11,6 @@
"publish": "wrangler publish"
},
"dependencies": {
"accept-language": "^3.0.18"
"intl-parse-accept-language": "^1.0.0"
}
}

View File

@ -3,7 +3,7 @@ import {
mapRequestToAsset,
} from "@cloudflare/kv-asset-handler";
import acceptLanguage from 'accept-language';
import { parseAcceptLanguage } from 'intl-parse-accept-language';
/**
* The DEBUG flag will do two things that help during development:
@ -20,8 +20,6 @@ addEventListener("fetch", (event) => {
const STRIP_SUFFIX_RE = new RegExp('^(/.+)(?:/(?:index\.html)?|\.html)$');
acceptLanguage.languages(['en-US', 'ja-JP']);
async function handleEvent(event) {
let options = {};
@ -46,11 +44,21 @@ async function handleEvent(event) {
const strip_match = STRIP_SUFFIX_RE.exec(path);
if (url.searchParams.get("lang") === 'auto') {
let resolvedLanguage = acceptLanguage.get(event.request.headers.get('Accept-Language'));
if (resolvedLanguage === null) {
resolvedLanguage = 'en-US';
} else {
resolvedLanguage = resolvedLanguage.split('-')[0];
const languages = parseAcceptLanguage(event.request.headers.get('Accept-Language'));
let resolvedLanguage = 'en';
if (languages !== null) {
for (const language of languages) {
if (language === 'ja' || language === 'ja-JP') {
resolvedLanguage = 'ja';
break;
}
if (language === 'en' || language.startsWith('en-')) {
resolvedLanguage = 'en';
break;
}
}
}
let destination;

View File

@ -978,6 +978,13 @@ __metadata:
languageName: node
linkType: hard
"intl-parse-accept-language@npm:^1.0.0":
version: 1.0.0
resolution: "intl-parse-accept-language@npm:1.0.0"
checksum: c1dcc0f520cb85be391f1cf4b5f691ab19183e5d8e8f5277c0d2210a78a6d01ee907b9bb70f7425c4a8d5a9ed86f8b18a8d53f089025772d89f5cbe39282f266
languageName: node
linkType: hard
"ip@npm:^2.0.0":
version: 2.0.0
resolution: "ip@npm:2.0.0"
@ -1778,6 +1785,7 @@ __metadata:
dependencies:
"@cloudflare/kv-asset-handler": ^0.2.0
accept-language: ^3.0.18
intl-parse-accept-language: ^1.0.0
wrangler: ^3.11.0
languageName: unknown
linkType: soft