mirror of
https://github.com/puppeteer/puppeteer
synced 2024-06-14 14:02:48 +00:00
feat(Response): add Response.fromCache / Response.fromServiceWorker (#1971)
This patch: - introduces `test/assets/cached` folder and teaches server to cache all the assets from the folder - introduces `test/assets/serviceworkers` folder that stores all the service workers and makes them register with unique URL prefix - introduces `Response.fromCache()` and `Response.fromServiceWorker()` methods Fixes #1551.
This commit is contained in:
@@ -68,6 +68,9 @@ class SimpleServer {
|
||||
this._server.listen(port);
|
||||
this._dirPath = dirPath;
|
||||
|
||||
this._startTime = new Date();
|
||||
this._cachedPathPrefix = null;
|
||||
|
||||
/** @type {!Set<!net.Socket>} */
|
||||
this._sockets = new Set();
|
||||
|
||||
@@ -90,6 +93,13 @@ class SimpleServer {
|
||||
socket.once('close', () => this._sockets.delete(socket));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} pathPrefix
|
||||
*/
|
||||
enableHTTPCache(pathPrefix) {
|
||||
this._cachedPathPrefix = pathPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
* @param {string} username
|
||||
@@ -189,15 +199,27 @@ class SimpleServer {
|
||||
let pathName = url.parse(request.url).path;
|
||||
if (pathName === '/')
|
||||
pathName = '/index.html';
|
||||
pathName = path.join(this._dirPath, pathName.substring(1));
|
||||
const filePath = path.join(this._dirPath, pathName.substring(1));
|
||||
|
||||
fs.readFile(pathName, function(err, data) {
|
||||
if (err) {
|
||||
response.statusCode = 404;
|
||||
response.end(`File not found: ${pathName}`);
|
||||
if (this._cachedPathPrefix !== null && filePath.startsWith(this._cachedPathPrefix)) {
|
||||
if (request.headers['if-modified-since']) {
|
||||
response.statusCode = 304; // not modified
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
response.setHeader('Content-Type', mime.lookup(pathName));
|
||||
response.setHeader('Cache-Control', 'public, max-age=31536000');
|
||||
response.setHeader('Last-Modified', this._startTime.toString());
|
||||
} else {
|
||||
response.setHeader('Cache-Control', 'no-cache, no-store');
|
||||
}
|
||||
|
||||
fs.readFile(filePath, function(err, data) {
|
||||
if (err) {
|
||||
response.statusCode = 404;
|
||||
response.end(`File not found: ${filePath}`);
|
||||
return;
|
||||
}
|
||||
response.setHeader('Content-Type', mime.lookup(filePath));
|
||||
response.end(data);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user