From 3b816c030cf0fc8a9d6bbd32f97d993da642b4c3 Mon Sep 17 00:00:00 2001 From: Mike Stead Date: Fri, 23 Dec 2016 04:46:22 +1100 Subject: [PATCH] Fix issue where regex is stripped during json stringify (#228) JSON.stringify stringifys RegExp as an empty object literal. This fix post process the toolbox origin regex if one exists so we have it when code generating. --- lib/sw-precache.js | 11 ++++++++++- test/test.js | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/sw-precache.js b/lib/sw-precache.js index 1d0a27d..0f45a30 100644 --- a/lib/sw-precache.js +++ b/lib/sw-precache.js @@ -104,13 +104,22 @@ function generateRuntimeCaching(runtimeCaching) { // include its body inline. (typeof curr.handler === 'string' ? 'toolbox.' : '') + curr.handler, // Default to no options. - JSON.stringify(curr.options || {})); + stringifyToolboxOptions(curr.options)); } return prev + line; }, ''); } +function stringifyToolboxOptions(options) { + options = options || {}; + var str = JSON.stringify(options); + if (options.origin instanceof RegExp) { + str = str.replace(/("origin":)\{\}/, '$1' + options.origin); + } + return str; +} + function generate(params, callback) { return new Promise(function(resolve, reject) { params = defaults(params || {}, { diff --git a/test/test.js b/test/test.js index af060c2..5bb1770 100644 --- a/test/test.js +++ b/test/test.js @@ -445,4 +445,26 @@ describe('generateRuntimeCaching', function() { }]); assert.equal(code, '\ntoolbox.router.get(/test/, toolbox.testHandler, {});'); }); + + it('should handle origin regex', function() { + var code = generateRuntimeCaching([{ + urlPattern: '/*', + handler: 'testHandler', + options: { + origin: /http:\/\/www.example\.com/ + } + }]); + assert.equal(code, '\ntoolbox.router.get("/*", toolbox.testHandler, {"origin":/http:\\/\\/www.example\\.com/});'); + }); + + it('should handle origin string', function() { + var code = generateRuntimeCaching([{ + urlPattern: '/*', + handler: 'testHandler', + options: { + origin: 'http://www.example.com' + } + }]); + assert.equal(code, '\ntoolbox.router.get("/*", toolbox.testHandler, {"origin":"http://www.example.com"});'); + }); });