Skip to content

Instantly share code, notes, and snippets.

@st3fan
Created January 19, 2021 00:05
Show Gist options
  • Select an option

  • Save st3fan/d38315f67d619f2e2569cda4725f2d16 to your computer and use it in GitHub Desktop.

Select an option

Save st3fan/d38315f67d619f2e2569cda4725f2d16 to your computer and use it in GitHub Desktop.
import Vapor
import Redis
struct Counter: Content {
let id: UUID
let name: String
let value: Int
}
struct CreateCounterRequest: Content {
let name: String
let value: Int
}
struct GetCounterResponse: Content {
let counter: Counter
}
struct UpdateCounterRequest: Content {
let name: String
let value: Int
}
func routes(_ app: Application) throws {
app.get { req in
return "It works!"
}
app.get("hello") { req -> String in
return "Hello, world!"
}
// Create a counter
app.post("user", ":userId", "counter") { req -> EventLoopFuture<Counter> in
guard let userId = req.parameters.get("userId", as: UUID.self) else {
throw Abort(.notFound)
}
guard let createCounterRequest = try? req.content.decode(CreateCounterRequest.self) else {
throw Abort(.badRequest)
}
let counter = Counter(id: UUID(), name: createCounterRequest.name, value: createCounterRequest.value)
return app.redis.set("\(userId):\(counter.id)", toJSON: counter)
.flatMap { req.eventLoop.makeSucceededFuture(counter) }
}
// Get a counter
app.get("user", ":userId", "counter", ":counterId") { req -> EventLoopFuture<GetCounterResponse> in
guard let userId = req.parameters.get("userId", as: UUID.self), let counterId = req.parameters.get("counterId", as: UUID.self) else {
throw Abort(.badRequest)
}
return app.redis.get("\(userId):\(counterId)", asJSON: Counter.self)
.unwrap(or: Abort(.notFound))
.map { GetCounterResponse(counter: $0) }
}
// Update a counter
app.put("user", ":userId", "counter", ":counterId") { req -> EventLoopFuture<GetCounterResponse> in
guard let userId = req.parameters.get("userId", as: UUID.self), let counterId = req.parameters.get("counterId", as: UUID.self) else {
throw Abort(.badRequest)
}
guard let updateCounterRequest = try? req.content.decode(UpdateCounterRequest.self) else {
throw Abort(.notFound)
}
return app.redis.get("\(userId):\(counterId)", asJSON: Counter.self).flatMap { counter in
guard let counter = counter else {
return req.eventLoop.future(error: Abort(.notFound))
}
let updatedCounter = Counter(id: counter.id, name: updateCounterRequest.name, value: updateCounterRequest.value)
return app.redis.set("\(userId):\(counter.id)", toJSON: updatedCounter)
.flatMap { req.eventLoop.makeSucceededFuture(GetCounterResponse(counter: updatedCounter)) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment