Skip to content

Commit

Permalink
add header detector.
Browse files Browse the repository at this point in the history
  • Loading branch information
sli committed May 3, 2017
1 parent f5695d2 commit 1ff4dcf
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const assert = require('assert');
import querystringLookup from './lookups/querystring';
import pathLookup from './lookups/path';
import cookieLookup from './lookups/cookie';
// import headerLookup from './lookups/header';

This comment has been minimized.

Copy link
@hobroker

hobroker Jul 5, 2017

you removed it here but not from line 55

import headerLookup from './lookups/header';
// import sessionLookup from './lookups/session';

function getDefaultsOpt() {
Expand Down
56 changes: 56 additions & 0 deletions src/lookups/header.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
export default {
name: 'header',

lookup(ctx, options) {
let found;
if (typeof ctx === 'undefined') {
return found;
}
let headers = ctx.headers;
if (!headers) {
return found;
}

let locales = [];
let acceptLanguage = headers['accept-language'];

if (acceptLanguage) {
let lngs = [];
let i;

// associate language tags by their 'q' value (between 1 and 0)
acceptLanguage.split(',').forEach(function(l) {
let parts = l.split(';'); // 'en-GB;q=0.8' -> ['en-GB', 'q=0.8']

// get the language tag qvalue: 'q=0.8' -> 0.8
let qvalue = 1; // default qvalue

for (i = 0; i < parts.length; i++) {
let part = parts[i].split('=');
if (part[0] === 'q' && !isNaN(part[1])) {
qvalue = Number(part[1]);
break;
}
}

// add the tag and primary subtag to the qvalue associations
lngs.push({ lng: parts[0], q: qvalue });
});

lngs.sort(function(a, b) {
return b.q - a.q;
});

for (i = 0; i < lngs.length; i++) {
locales.push(lngs[i].lng);
}

if (locales.length) {
found = locales;
}
}


return found;
}
};

0 comments on commit 1ff4dcf

Please sign in to comment.