Skip to content

Instantly share code, notes, and snippets.

@vzsg
Last active October 1, 2019 13:42
Show Gist options
  • Save vzsg/1bb6c215e5365d0ac7d18eeceacbbb46 to your computer and use it in GitHub Desktop.
Save vzsg/1bb6c215e5365d0ac7d18eeceacbbb46 to your computer and use it in GitHub Desktop.
Fetching remote configuration on app boot (Vapor 3)
import Dispatch
// Utility class for thread-safe access to an "app global" variable
final class DispatchBox<T>: Service {
private let queue = DispatchQueue(label: "DispatchBox_\(T.self)_Queue")
private var _value: T?
var value: T? {
get { return queue.sync { self._value }}
set { queue.async { self._value = newValue }}
}
}
import Foundation
// This sample class can be used to parse a JSON like:
// { "secret": "FOOBAR" }
struct SampleConfiguration: Decodable {
let secret: String
}
import Vapor
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
// ... other configuration ...
// Creating a holder for SampleConfiguration
let holder = DispatchBox<SampleConfiguration>()
services.register(holder)
}
import Vapor
/// Called after your application has initialized.
public func boot(_ app: Application) throws {
let client = try app.make(Client.self)
let holder = try app.make(DispatchBox<SampleConfiguration>.self)
let config = try client.get("https://api.jsonbin.io/b/5b5f00c4f24d8943d0505d0a")
.flatMap { try $0.content.decode(SampleConfiguration.self) }
.wait()
holder.value = config
}
import Foundation
import Vapor
/// Register your application's routes here.
public func routes(_ router: Router) throws {
router.get("secret") { req -> String in
let holder = try req.make(DispatchBox<SampleConfiguration>.self)
return holder.value?.secret ?? ""
}
}
@pdamonkey
Copy link

Thanks 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment