Skip to content

Commit

Permalink
feat(core): add edge and last-modified header, close DIYgod#338
Browse files Browse the repository at this point in the history
  • Loading branch information
DIYgod committed Apr 26, 2019
1 parent 6692c4a commit 801f75c
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
23 changes: 23 additions & 0 deletions lib/middleware/header.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const etagCalculate = require('etag');
const logger = require('../utils/logger');
const config = require('../config');
const headers = {
Expand All @@ -11,5 +12,27 @@ const headers = {
module.exports = async (ctx, next) => {
logger.info(`${ctx.url}, user IP: ${ctx.ips[0] || ctx.ip}`);
ctx.set(headers);

await next();

let body = ctx.body;
if (!body || typeof body !== 'string' || ctx.response.get('ETag')) {
return;
}

const status = (ctx.status / 100) | 0;
if (2 !== status) {
return;
}

const match = body.match(/<lastBuildDate>(.*)<\/lastBuildDate>/);
if (match) {
ctx.set({
'Last-Modified': body.match(/<lastBuildDate>(.*)<\/lastBuildDate>/)[1],
});
}

body = body.replace(/<lastBuildDate>(.*)<\/lastBuildDate>/, '');

ctx.response.etag = etagCalculate(body);
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"co-redis": "2.1.1",
"currency-symbol-map": "4.0.4",
"dayjs": "1.8.12",
"etag": "1.8.1",
"form-data": "2.3.3",
"git-rev-sync": "1.12.0",
"googleapis": "39.2.0",
Expand Down
2 changes: 2 additions & 0 deletions test/middleware/header.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@ describe('header', () => {
expect(response.headers['access-control-allow-methods']).toBe('GET');
expect(response.headers['content-type']).toBe('application/xml; charset=utf-8');
expect(response.headers['cache-control']).toBe(`max-age=${config.cacheExpire / 2}`);
expect(response.headers['last-modified']).toBe(response.text.match(/<lastBuildDate>(.*)<\/lastBuildDate>/)[1]);
expect(response.headers.etag).toBe('"b37-MORyrF0tJ8BFw0xLLZL/zBYAFPY"');
});
});
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3877,7 +3877,7 @@ esutils@^2.0.2:
resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b"
integrity sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=

etag@~1.8.1:
etag@1.8.1, etag@~1.8.1:
version "1.8.1"
resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887"
integrity sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=
Expand Down

0 comments on commit 801f75c

Please sign in to comment.