How To Extend Ejson To Serialize Regex For Meteor Client-server Interactions?
Solution 1:
After reviewing this HowTo and the Meteor EJSON Docs, we may serialize RegEx using the EJSON.addType
method.
Extend RegExp - Provide RegExp with the methods EJSON.addType
requires for implementation.
RegExp::options = ->
opts = []
opts.push 'g'if @global
opts.push 'i'if @ignoreCase
opts.push 'm'if @multiline
return opts.join('')
RegExp::clone = ->self = @
return new RegExp(self.source, self.options())
RegExp::equals = (other) ->self = @
if other isnt instanceOf RegExp
returnfalsereturn EJSON.stringify(self) is EJSON.stringify(other)
RegExp::typeName = ->return"RegExp"
RegExp::toJSONValue = ->self = @
return {
'regex': self.source
'options': self.options()
}
Call EJSON.addType - Do this anywhere. It's best to make it available to client AND server though. This is going to deserialize the object defined in toJSONValue
above.
EJSON.addType"RegExp", (value) ->
returnnewRegExp(value['regex'], value['options'])
Test In Your Console - Don't take my word for it. See for yourself.
> o = EJSON.stringify(/^Mooo/ig)
"{"$type":"RegExp","$value":{"regex":"^Mooo","options":"ig"}}"
> EJSON.parse(o)
/^Mooo/gi
And there you have a RegExp being serialized and parsed on client and server, able to be passed in over the wire, saved in a Session, and even possibly stored in a Collection of queries!
EDIT to addess IE10+ Error: Assignment to read-only properties is not allowed in strict mode Courtesy of @Tim Fletcher in the comments
import { EJSON } from'meteor/ejson';
functiongetOptions(self) {
const opts = [];
if (self.global) opts.push('g');
if (self.ignoreCase) opts.push('i');
if (self.multiline) opts.push('m');
return opts.join('');
}
RegExp.prototype.clone = functionclone() {
returnnewRegExp(this.source, getOptions(this));
};
RegExp.prototype.equals = functionequals(other) {
if (!(other instanceofRegExp)) returnfalse;
returnEJSON.stringify(this) === EJSON.stringify(other);
};
RegExp.prototype.typeName = functiontypeName() {
return'RegExp';
};
RegExp.prototype.toJSONValue = functiontoJSONValue() {
return { regex: this.source, options: getOptions(this) };
};
EJSON.addType('RegExp', value =>newRegExp(value.regex, value.options));
Solution 2:
There is a far simpler solution:
stringify your RegExp via .toString()
, send it to the server and then parse it back to RegExp.
Post a Comment for "How To Extend Ejson To Serialize Regex For Meteor Client-server Interactions?"