Skip to content

Instantly share code, notes, and snippets.

View cweinberger's full-sized avatar

Christian Weinberger cweinberger

View GitHub Profile
@cweinberger
cweinberger / vapor-custom-arguments.md
Last active December 12, 2019 10:03
Custom arguments when running Vapor

How to add (and read) custom arguments when launching a vapor app.

In app.swift I have added a struct AppOptions to keep track of custom options and added another parameter options to the app(_:) function:

import Vapor

public struct AppOptions {
    public var foo: String?
    
import Vapor
func routes(_ app: Application) throws {
}
import Vapor
final class BookAPIController {
// 1
struct Book: Content {
let id: Int
let title: String
let author: String
}
func routes(_ app: Application) throws {
// 1
// a GET request to /hello1
app.get("hello1") { req -> String in
return "hello1"
}
// 2
// a GET request to /hello2
// 1
let bookAPIController = BookAPIController()
// 2
try app.register(collection: bookAPIController)
// 1
let apiRoutes = app.grouped("api", "v1")
// 2
try apiRoutes.grouped("books").register(collection: bookAPIController)
func getBook(req: Request) throws -> Book {
guard
// 1
let bookIDString = req.parameters.get("bookID"),
// 2
let bookID = Int(bookIDString),
// 3
let book = Self.books.first(where: { $0.id == bookID })
else {
// 4
func boot(routes: RoutesBuilder) throws {
routes.get("", use: getBooks)
routes.get(":bookID", use: getBook)
}
@cweinberger
cweinberger / 1-MySQLDataConvertibleEnum.swift
Last active April 13, 2020 15:54
Auto-conform your enums types that you want to store in MySQL to `MySQLDataConvertible` and `ReflectionDecodable`. Avoids a lot of boilerplate!
/* NOTE: check out 3-MySQLDataConvertibleEnum_Better_Version.swift. */
import Fluent
import FluentMySQL
import Vapor
protocol MySQLDataConvertibleEnum: MySQLDataConvertible, ReflectionDecodable, CaseIterable { }
extension MySQLDataConvertibleEnum where Self: RawRepresentable, Self.RawValue == String {
func convertToMySQLData() -> MySQLData {
@cweinberger
cweinberger / MySQL+Database.swift
Last active May 31, 2020 12:48
Vapor 3 with Swift 5.2
import FluentMySQL
/*
Starting with Swift 5.2 the compiler is not able to resolve this automatically:
`migrations.add(model: Todo.self, database: .mysql)`
See: https://forums.swift.org/t/vapor-3-swift-5-2-regression/34764
Instead of adding this to each model, I added these extensions.