Skip to content

Instantly share code, notes, and snippets.

@ukyo
Last active December 18, 2018 03:39
Show Gist options
  • Save ukyo/a6a4ae1b5197c18328d2 to your computer and use it in GitHub Desktop.
Save ukyo/a6a4ae1b5197c18328d2 to your computer and use it in GitHub Desktop.
ServiceWorker sample fetch with LZ4+MessagePack
node_modules/

ServiceWorker sample fetch with LZ4+MessagePack

git clone https://gist.github.com/a6a4ae1b5197c18328d2.git sw-test
cd sw-test
npm install
node app.js
var express = require('express');
var bodyParser = require('body-parser');
var lz4 = require('lz4-asm');
var msgpack = require('msgpack-lite');
var app = express();
app.use(express.static('.'));
app.use(bodyParser.raw({type: '*/*'}))
app.post('/api', function(req, res) {
var buff = new Uint8Array(req.body);
var obj, ret;
console.log('byte length: ' + buff.length);
if (req.headers['x-content-encoding'] === 'lz4') {
buff = lz4.decompress(buff);
}
if (req.headers['content-type'] === 'application/x-msgpack') {
obj = msgpack.decode(new Buffer(buff));
} else {
obj = JSON.parse(new Buffer(buff).toString('utf8'));
}
obj.contentType = req.headers['content-type'];
obj.contentEncoding = req.headers['x-content-encoding'];
console.log(obj);
if (req.headers['x-accept-encoding'] === 'lz4') {
ret = new Buffer(lz4.compress(new Uint8Array(msgpack.encode(obj))));
} else {
ret = new Buffer(JSON.stringify(obj));
}
res.send(ret);
});
app.listen(3333);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>sw test</title>
<script src="script.js"></script>
</head>
<body>
<h1>Input JSON</h1>
<textarea rows="8" cols="40"></textarea>
<button id="sendButton">send</button>
<button id="formatButton">format</button>
<pre></pre>
</body>
</html>
{
"name": "sw-test",
"version": "1.0.0",
"dependencies": {
"body-parser": "^1.14.1",
"express": "^4.13.3",
"lz4-asm": "^0.2.0",
"msgpack-lite": "^0.1.13"
}
}
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// 登録成功
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
// 登録失敗 :(
console.log('ServiceWorker registration failed: ', err);
});
}
window.onload = function() {
var textarea = document.querySelector('textarea');
var sendButton = document.querySelector('#sendButton');
var formatButton = document.querySelector('#formatButton');
var pre = document.querySelector('pre');
formatButton.addEventListener('click', function() {
textarea.value = JSON.stringify(JSON.parse(textarea.value), null, 2);
});
sendButton.addEventListener('click', function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json';
xhr.send(textarea.value);
xhr.onload = function() {
pre.textContent = JSON.stringify(xhr.response, null, 2);
};
});
};
importScripts(
'node_modules/lz4-asm/lz4.js',
'node_modules/msgpack-lite/dist/msgpack.min.js'
);
self.addEventListener('fetch', event => {
// apiだけlz4+messagepackで通信するようにする(手抜き)
if (/api/.test(event.request.url)) {
var headers = new Headers();
headers.append('X-Content-Type', 'application/x-msgpack');
headers.append('X-Content-Encoding', 'lz4');
headers.append('X-Accept-Encoding', 'lz4');
event.respondWith(
event.request.json().then(o => {
return fetch(event.request.url, {
method: event.request.method,
body: new Blob([lz4.compress(msgpack.encode(o))], {type: 'application/x-msgpack'}),
headers: headers
});
})
.then(response => response.arrayBuffer())
.then(buffer => new Response(new Blob([JSON.stringify(msgpack.decode(lz4.decompress(new Uint8Array(buffer))))])))
);
} else {
event.respondWith(fetch(event.request));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment