From 9b141d6c6f022dad1e622a5b0627c8d4b9fe62ef Mon Sep 17 00:00:00 2001 From: Hiroshi Nakagoe Date: Sun, 12 Jul 2020 22:02:36 +0900 Subject: [PATCH] support font files --- index.js | 23 ++++++++++++++++++----- test/test.js | 26 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index c359075..be9b149 100644 --- a/index.js +++ b/index.js @@ -48,19 +48,30 @@ module.exports = exports = (app) => (args) => { app.action_params = args; + // use buffer to have custom parer that stores data chunks flagged as binary data + req + .buffer(true) + .parse((res, cb) => { + res.setEncoding('binary'); + res.data = ''; + res.on('data', (chunk) => res.data += chunk); + res.on('end', () => cb(null, Buffer.from(res.data, 'binary'))); + }); + req.end((err, res) => { - if (err) + if (err || !res.body) return resolve({ statusCode: 500, body: JSON.stringify(err) }); - let body = res.text || res.body; - + let body; let contentType = res.headers['content-type'] || 'text/plain'; contentType = contentType.split(';')[0]; if (isBinary(contentType)) - body = new Buffer(body).toString('base64'); + body = res.body.toString('base64'); + else + body = res.body.toString('utf-8'); // Convert response back to a OpenWhisk response object. return resolve({ @@ -77,6 +88,7 @@ const mediaTypes = { "application/base64": true, "application/excel": true, "application/font-woff": true, + "application/font-woff2": true, // backward compatibility: woff2 had been proposed as this "application/gnutar": true, "application/java-archive": true, "application/javascript": false, @@ -148,7 +160,8 @@ const mediaTypes = { function isBinary(contentType) { if (contentType.startsWith('text/') || contentType.startsWith('message/')) return false; - if (contentType.startsWith('audio/') || contentType.startsWith('image/') || contentType.startsWith('video/')) + if (contentType.startsWith('audio/') || contentType.startsWith('image/') || + contentType.startsWith('video/') || contentType.startsWith('font/')) return true; return mediaTypes[contentType]; } diff --git a/test/test.js b/test/test.js index 2f236dd..2eb4318 100644 --- a/test/test.js +++ b/test/test.js @@ -38,6 +38,11 @@ app.patch('/', (req, res) => { res.send(req.body); }); +app.get('/font', (req, res) => { + res.set('Content-Type', 'font/woff'); + res.send(sampleFont); +}); + const forward = require('../index.js')(app); describe('get', () => { @@ -99,3 +104,24 @@ describe('put', () => { }); }); }); + +describe('get', () => { + describe('font', () => { + it('should return encoded font', (done) => { + forward({ + __ow_method: 'get', + __ow_path: '/font', + }).then(res => { + assert.equal(wantEncodedFont, res.body); + done(); + }); + }); + }); +}); + +let sampleFont = ''; +for (i = 0; i < 50000; i++) { + sampleFont += Math.random().toString(36).substring(2, 15); +} +let wantEncodedFont = Buffer.from(sampleFont, 'binary').toString('base64'); +