0

我有几个这样的功能:

  import reactivemongo.play.json.collection.JSONCollection

  def quotesFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("quotes"))

 1:  def getByAuthor(author: String) = Action.async {
 2:    quotesFuture.flatMap{ quotes =>
 3:      quotes
 4:        .find(obj("author" -> author))
 5:        .cursor[JsObject](ReadPreference.primary)
 6:        .collect[List](maxQuotes)
 7:        .map(q => Ok(Json.toJson(q)))
 8:    }
 9:  }
10:
11:  def search(term: String) = Action.async {
12:    quotesFuture.flatMap{ quotes =>
13:      quotes
14:        .find(obj("$text" -> obj("$search" -> term)), textScore)
15:        .sort(textScore)
16:        .cursor[JsObject](ReadPreference.primary)
17:        .collect[List](maxQuotes)
18:        .map(q => Ok(Json.toJson(q)))
19:    }
20:  }

但是有很多重复;唯一改变的是查找和排序,所以我想重构如下:

100:  def getByAuthor(author: String) = getList { quotes =>
101:    quotes
102:      .find(obj("author" -> author))
103:  }
104:
105:  def search(term: String) = getList { quotes =>
106:    quotes
107:      .find(obj("$text" -> obj("$search" -> term)), textScore)
108:      .sort(textScore)
109:  }
110:
111:  def getList(query: (JSONCollection) => ???) = Action.async {
112:    quotesFuture.flatMap{ quotes =>
113:      query(quotes)
114:        .cursor[JsObject](ReadPreference.primary)
115:        .collect[List](maxQuotes)
116:        .map(q => Ok(Json.toJson(q)))
117:    }
118:  }

问题是???第 111 行应该是什么?

当要求 IntelliJ 从第 14-15 行中提取方法时,它会创建以下内容

  def tempdef(term: String, quotes: JSONCollection): GenericQueryBuilder[quotes.pack.type]#Self = {
    quotes
      .find(obj("$text" -> obj("$search" -> term)), textScore)
      .sort(textScore)
  }

IntelliJ 提出的结果类型非常可怕。所以,???在第 111 行应该是GenericQueryBuilder[quotes.pack.type]#Self,但这取决于变量quotes。我应该???用什么来代替它来完成这项工作?

使用 IntelliJ,我看到quotes.pack指的是:

case class JSONCollection(...) {...
  val pack = JSONSerializationPack
}

我尝试用 替换???第 111 行JSONSerializationPack.type,它编译并工作。

但是,查看 的实现细节JSONCollection是作弊,如果 JSONCollection 的实现发生变化,这可能会停止工作。

那么,???第 111 行应该是什么?

否则,您是否看到此示例中删除代码重复的更简单方法?

4

1 回答 1

0

我建议您getByAuthorsearch返回 a Cursor[JsObject],这允许它们具有不同的ReadPreference,并使用非依赖类型(与查询生成器相反,它依赖于集合的底层序列化包,IDE 不理解什么)。

导入 reactivemongo.api.Cursor

def getByAuthor(author: String): Cursor[JsObject] = ???

def search(term: String): Cursor[JsObject] = ???

def getList(cursor: JSONCollection => Cursor[JsObject] = Action.async {
  quotesFuture.flatMap { quotes =>
    val c: Cursor[JsObject] = cursor(quotes)
    ???
  }
于 2016-08-16T17:14:33.697 回答