From b229b0a16c8292f9bb5447488a218b0c2cf84ac9 Mon Sep 17 00:00:00 2001 From: Mike Stead Date: Thu, 22 Dec 2016 09:32:14 +1100 Subject: [PATCH] Fix issue where regex is stripped during json stringify 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"});'); + }); });