Skip to content

Commit

Permalink
Merge pull request #27 from nemphys/custom-detection
Browse files Browse the repository at this point in the history
Implement custom locale detection using a new 'detectLocale' parameter
  • Loading branch information
niftylettuce authored Feb 26, 2021
2 parents a0eac42 + 24004ee commit 7697279
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,9 @@ This is an extremely useful method if you are using `koa-better-error-handler` p
This middleware uses custom locale detection (in order of priority):

1. Check URL (e.g. if `/de` or `/de/` then it's a `de` locale - as long as `de` is a supported locale)
2. Check the `"locale"` cookie value (or whatever the `cookie` option is defined as)
3. Check `Accept-Language` header
2. Use the custom function (if provided by the `detectLocale` parameter) for locale detection
3. Check the `"locale"` cookie value (or whatever the `cookie` option is defined as)
4. Check `Accept-Language` header

It also exposes the following:

Expand Down Expand Up @@ -150,7 +151,9 @@ const i18n = new I18N({
format: 'RFC1738',
arrayFormat: 'indices'
},
redirectTLDS: true
redirectTLDS: true,
// function that allows using a custom logic for locale detection (can return promise)
detectLocale: null
});
```

Expand Down
16 changes: 12 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class I18N {
arrayFormat: 'indices'
},
redirectTLDS: true,
detectLocale: false,
...config
};

Expand Down Expand Up @@ -112,7 +113,7 @@ class I18N {
return err;
}

middleware(ctx, next) {
async middleware(ctx, next) {
const { locales, defaultLocale, phrases, cookie } = this.config;

// expose api methods to `ctx.request` and `ctx.state`
Expand All @@ -128,9 +129,10 @@ class I18N {
// in order of priority:
//
// 1. check the URL, if === `/de` or starts with `/de/` then locale is `de`
// 2. check the cookie
// 3. check Accept-Language last
// 4. check the user's lastLocale
// 2. use a custom function, if provided in parameters
// 3. check the cookie
// 4. check Accept-Language last
// 5. check the user's lastLocale
//
// also we need to expose `ctx.pathWithoutLocale`
// as the path without locale
Expand All @@ -154,6 +156,12 @@ class I18N {
...new Set([defaultLocale, ...locales])
]);
if (
this.config.detectLocale &&
typeof this.config.detectLocale === 'function'
) {
locale = await this.config.detectLocale.call(this, ctx);
debug('found locale via custom function using %s', locale);
} else if (
ctx.cookies.get(cookie) &&
locales.includes(ctx.cookies.get(cookie))
) {
Expand Down

0 comments on commit 7697279

Please sign in to comment.