Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1. Creat a basic type that can easily hold data.
- import Service
- public class Storage: Service {
- public var cache: [String: Codable] = [:]
- public init() {}
- }
- // 2. Register the service as a singleton with the rest of your applications services in `configure`.
- // Make sure you set the return type of the closuer!
- services.register(isSingleton: true) { (container) -> (Storage) in
- return Storage()
- }
- // 3. Make it from a request! I created a couple of helper methods for this:
- extension Request {
- public func get(_ key: String)throws -> Codable? {
- let storage = try self.privateContainer.make(Storage.self, for: Request.self)
- return storage.cache[key]
- }
- public func set(_ key: String, to value: Codable)throws {
- var storage = try self.privateContainer.make(Storage.self, for: Request.self)
- storage.cache[key] = value
- }
- }
- // usage:
- try request.set("user", to: user)
Add Comment
Please, Sign In to add comment