Reputation: 973
I'm trying to save a regular expression as RegExp Object in a Meteor Session for a MongoDB query, but after Session.get() the RegExp object is just a empty object.
js
if (Meteor.isClient) {
Meteor.startup(function () {
var obj = {};
obj['regexp'] = new RegExp("test");
console.log("setting regular expression: " + obj['regexp']);
Session.set("test", obj);
});
Template.test.events({
'click button': function () {
var regex = Session.get("test");
console.log("now it is: ");
console.log(regex['regexp']);
}
});
}
if (Meteor.isServer) {
}
html
<head>
<title>meteor-regexp-session-test</title>
</head>
<body>
{{> test}}
</body>
<template name="test">
<button>hit the button and look at the console</button>
</template>
Any ideas why this is not working?
Thank in advance!
Upvotes: 1
Views: 608
Reputation: 2458
There's a handy way to teach EJSON how to serialize/parse Regular Expressions (RegExp) documented in this SO question:
How to extend EJSON to serialize RegEx for Meteor Client-Server interactions?
Basically, we can extend the RegExp object class and use EJSON.addType
to teach the serialization to both client and server. The options are enough of a critical piece of Regular Expressions that you should have the ability to store those too anywhere you want in perfectly valid JSON!
Hope this helps someone out there in the Universe. :)
Upvotes: 2
Reputation: 19544
You need to save the regex source instead:
var regex = new RegExp('test');
Session.set('regex', regex.source);
...
var restoredRegex = new RegExp(Session.get('regex'));
console.log(restoredRegex);
See: http://meteorpad.com/pad/KJHJtQPEapPhceXkx
Upvotes: 2
Reputation: 5273
Session
package uses ReactiveDict
under the hood.
ReactiveDict
serializes value passed to Sessions.set(key, value)
:
// https://github.com/meteor/meteor/blob/devel/packages/reactive-dict/reactive-dict.js
// line 3-7:
var stringify = function (value) {
if (value === undefined)
return 'undefined';
return EJSON.stringify(value);
};
Session.get(key)
deserializes it with EJSON.parse
:
// https://github.com/meteor/meteor/blob/devel/packages/reactive-dict/reactive-dict.js
// line 8-12:
var parse = function (serialized) {
if (serialized === undefined || serialized === 'undefined')
return undefined;
return EJSON.parse(serialized);
};
It means Session
doesn't support RegExp
out of the box.
The solution for your issue is to create custom reactive data source, which will work similar to Session
but will not serialize/deserialize value object.
Take a look here:
Upvotes: 1