【问题标题】:Unclear use of Storage存储使用不清楚
【发布时间】:2020-10-30 14:28:39
【问题描述】:

如何在 Vapor 4 中使用存储?

我尝试了以下方法:

if let someValue = req.storage.get(theKey) as? String {
    // do something
} else {
    req.storage.set(theKey, to: "Some Value")
}

但是我得到以下错误:

error: type of expression is ambiguous without more context
    if let original: String = req.storage.get(theKey) {
                              ~~~~~~~~~~~~^~~~~~~~~~~
error: type of expression is ambiguous without more context
    req.storage.set(theKey, to: "Some Value")
    ~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我也没有找到关于这个主题的任何文档。

【问题讨论】:

  • 尝试查看你项目的依赖来源,你会发现很多最佳实践。
  • @imike 示例请 - 如果那里有很多最佳实践,它们很容易找到,对吧?
  • 这假设只有 1 个已知的密钥。我需要设置一个任意键。
  • 我认为您可以通过复制仅 80 行的 Vapor 实现来实现自己的存储,并将其 [ObjectIdentifier: AnyStorageValue] 字典更改为所需的 [String: AnyStorageValue]

标签: vapor


【解决方案1】:

输入键实际上是一个使用必须实现的协议。如果您想查看如何使用 Store 的示例,请按照 @imike 所说的那样查找 Storage 类的用法。

【讨论】:

  • 所以我让 String 符合那个协议?
【解决方案2】:

存储不是基于字符串的键对象存储。您必须声明一个符合StorageKeystruct,实现代表您要存储的对象类型的typealias 值。

如果您需要存储一个字符串,让我们以这个例子为例:

struct MyStringKey: StorageKey {
     typealias Value = String
}

...

request.storage.set(MyStringKey.self, to: "my string")
var myString: String? = request.storage.get(MyStringKey.self)

【讨论】:

  • 我认为 Redis 是存储这类缓存变量的首选方式。
  • 是的,也许可以这样做(即使在字符串键基值的情况下它不是最佳的......)
【解决方案3】:

Key 不可能是任意字符串。密钥必须是预定义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2011-05-09
    • 2018-03-17
    • 2011-11-14
    • 1970-01-01
    相关资源
    最近更新 更多