Skip to content
This repository has been archived by the owner on Oct 6, 2020. It is now read-only.

Cache fetch fallbacks #1

Open
Mordil opened this issue Dec 8, 2018 · 0 comments
Open

Cache fetch fallbacks #1

Mordil opened this issue Dec 8, 2018 · 0 comments
Labels
enhancement New feature or request

Comments

@Mordil
Copy link
Member

Mordil commented Dec 8, 2018

extension KeyedCache {
    func fetch<T: Codable>(key: String, on worker: Worker, fallback: @escaping () -> Future<T>) -> Future<T> {
        return get(key, as: T.self)
            .flatMap { cached in
                if let cached = cached {
                    return worker.future(cached)
                }

                return fallback()
                    .flatMap { self.set(key, to: $0).transform(to: $0) }
            }
    }
}

Usage

router.get("cached") { req -> Future<[Cat]> in
    let cache: KeyedCache = try req.make()

    return cache.fetch(key: "cats", on: req) {
        Cat.query(on: req).all() // <-- only executed once
    }
}
router.get("cachedOne") { req -> Future<Cat> in
    let cache: KeyedCache = try req.make()

    guard let name: String = req.query["name"] else {
        throw Abort(.badRequest)
    }

    return cache.fetch(key: "cat-\(name)", on: req) {
        Cat.query(on: req)
            .filter(\Cat.name == name)
            .first()
            .unwrap(or: Abort(.notFound))
    }
}
@tanner0101 tanner0101 added the enhancement New feature or request label Jun 12, 2019
@tanner0101 tanner0101 changed the title Add extension for fallback values for Redis caches Cache fetch fallbacks Mar 6, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants