如何扩展EJSON以序列化RegEx以进行Meteor客户端 - 服务器交互?

aza*_*tar 2 javascript regex json coffeescript meteor

我有一个任意的(E)JSON,可以在我的Meteor应用程序中通过网络从客户端发送到服务器.它使用RegExp对象将结果置于零上:

# on the client
selector = 
  "roles.user": { "$ne": null } 
  "profile.email": /^admin@/gi 
Run Code Online (Sandbox Code Playgroud)

所有在客户端都很好,但如果我通过Meteor.call或传递给服务器Meteor.subscribe,结果(E)JSON采用这种形式:

# on the server
selector =
  "roles.user": { "$ne": null }
  "profile.email": {}
Run Code Online (Sandbox Code Playgroud)

......某个工程师在里面死了一点.

Web上有大量资源解释了RegEx通过JSON.stringify/ JSON.parse或等效EJSON方法无法排序的原因.

我不相信RegEx序列化是不可能的.那怎么办呢?

aza*_*tar 6

在查看了此HowToMeteor EJSON文档后,我们可以使用该EJSON.addType方法序列化RegEx .

扩展RegExp - 为RegExp提供EJSON.addType实现所需的方法.

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
    return false
  return EJSON.stringify(self) is EJSON.stringify(other)

RegExp::typeName = ->
  return "RegExp"

RegExp::toJSONValue = ->
  self = @
  return {
    'regex': self.source
    'options': self.options()
  }
Run Code Online (Sandbox Code Playgroud)

调用EJSON.addType - 在任何地方执行此操作.最好将它提供给客户端和服务器.这将反序列化toJSONValue上面定义的对象.

EJSON.addType "RegExp", (value) ->
  return new RegExp(value['regex'], value['options'])
Run Code Online (Sandbox Code Playgroud)

在你的控制台测试 - 不要相信我的话.你自己看.

> o = EJSON.stringify(/^Mooo/ig)
"{"$type":"RegExp","$value":{"regex":"^Mooo","options":"ig"}}"
> EJSON.parse(o)
/^Mooo/gi
Run Code Online (Sandbox Code Playgroud)

在那里,你有一个RegExp在客户端和服务器上被序列化和解析,能够通过网络传递,保存在Session中,甚至可能存储在查询集合中!

编辑加入IE10 +错误:在严格模式下不允许分配给只读属性由@Tim Fletcher在评论中提供

import { EJSON } from 'meteor/ejson';

function getOptions(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 = function clone() {
  return new RegExp(this.source, getOptions(this));
};

RegExp.prototype.equals = function equals(other) {
  if (!(other instanceof RegExp)) return false;
  return EJSON.stringify(this) === EJSON.stringify(other);
};

RegExp.prototype.typeName = function typeName() {
  return 'RegExp';
};

RegExp.prototype.toJSONValue = function toJSONValue() {
  return { regex: this.source, options: getOptions(this) };
};

EJSON.addType('RegExp', value => new RegExp(value.regex, value.options));
Run Code Online (Sandbox Code Playgroud)