Skip to content

Instantly share code, notes, and snippets.

@hsharghi
hsharghi / flatMap.swift
Created December 13, 2019 01:01
virgool-blog-0002
struct PostAndComments {
var post: Post
var comments: [Comment]
}
func showPostsWithComments() -> Future<[PostAndComments]> {
return getPostsFromDatabase().flatMap { posts -> Future<[PostAndComments]> in
return posts.flatMap { post -> Future<[PostAndComments]> in
return post.getComments().map { comments -> [PostAndComments] in
return PostAndComment(post: post, comments: comments)
@hsharghi
hsharghi / PostController.swift
Last active December 21, 2019 11:12
virgool-post-controller-0015
import Vapor
/// Controls basic CRUD operations on `Post`s.
final class PostController {
/// Returns a list of all `Posts`s.
/// GET /posts
func index(_ req: Request) throws -> Future<[Post]> {
return Post.query(on: req).all() //1
@hsharghi
hsharghi / routes.swift
Last active December 21, 2019 12:35
virgool-blog-0008
import Vapor
public func routes(_ router: Router) throws {
let postController = PostController() // 1
// 2
/// GET /posts
router.get("posts", use: postController.index)
@hsharghi
hsharghi / configure.swift
Last active December 21, 2019 12:38
virgool-blog-0020
import FluentSQLite
import Vapor
/// Called before your application initializes.
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
// Register providers first
try services.register(FluentSQLiteProvider())
// Register routes to the router