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

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

# on the client
selector = 
  "roles.user": { "$ne": null } 
  "profile.email": /^admin@/gi 

所有在客户端都很好,但如果我通过Meteor.call或Meteor.subscribe将其传递给服务器,则生成的(E)JSON采用以下形式:

# on the server
selector =
  "roles.user": { "$ne": null }
  "profile.email": {}

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

Web上有大量资源解释了为什么RegEx可以通过JSON.stringify / JSON.parse或等效的EJSON方法进行反序列化.

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

解决方法:

在查看this HowTothe Meteor EJSON Docs之后,我们可以使用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()
  }

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

EJSON.addType "RegExp", (value) ->
  return new RegExp(value['regex'], value['options'])

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

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

在那里,你有一个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));
上一篇:javascript – node.js堆栈跟踪线中冒号后面的第二个数字是什么意思?


下一篇:在多维数组javascript或coffeescript中获得最大价值