Last active
January 28, 2019 18:57
-
-
Save timbaev/f69658a55887eea4657a07007e7de58b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vapor | |
import FluentSQLite | |
struct DefaultTodoService: TodoService { | |
func create(request: Request, todoDto: TodoDto) throws -> Future<TodoDto> { | |
return try request.authorizedUser().flatMap { user in | |
return Todo(title: todoDto.title, userID: try user.requireID()).save(on: request).flatMap { todo in | |
return request.future(TodoDto(id: try todo.requireID(), title: todo.title)) | |
} | |
} | |
} | |
func fetch(request: Request) throws -> Future<[TodoDto]> { | |
return try request.authorizedUser().flatMap { user in | |
return try user.todos.query(on: request).all().flatMap { todos in | |
return request.future(try todos.map { TodoDto(id: try $0.requireID(), title: $0.title) }) | |
} | |
} | |
} | |
func delete(request: Request, todoID: Int) throws -> Future<TodoDto> { | |
return try request.authorizedUser().flatMap { user in | |
return try user | |
.todos | |
.query(on: request) | |
.filter(\.id == todoID) | |
.first() | |
.unwrap(or: Abort(.badRequest, reason: "User don't have todo with id \(todoID)")) | |
.delete(on: request) | |
.flatMap { todo in | |
return request.future(TodoDto(id: try todo.requireID(), title: todo.title)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment