Skip to content

Instantly share code, notes, and snippets.

View vzsg's full-sized avatar

Zsolt Váradi vzsg

  • Budapest, Hungary
View GitHub Profile
@vzsg
vzsg / 1_Todo.swift
Created June 12, 2019 12:06
MongoKitten5 Todo example
import Vapor
import MongoKitten
/// A single entry of a Todo list.
final class Todo: Content {
/// The unique identifier for this `Todo`.
var id: ObjectId?
/// A title describing what this `Todo` entails.
var title: String
@vzsg
vzsg / WikiParser_playground.swift
Created May 22, 2019 21:29
Parsing parallel arrays of the Wikipedia API with Codable
import Foundation
struct WikipediaEntry {
let title: String
let summary: String
let link: URL?
}
struct WikipediaSearchResults: Decodable {
let term: String
@vzsg
vzsg / 1_Vapor+Proto.swift
Created March 3, 2019 11:19
Using SwiftProtobuf with Vapor 3
import Vapor
import SwiftProtobuf
import Foundation
extension Request {
public func decodeMessage<M: SwiftProtobuf.Message>(_ type: M.Type = M.self) throws -> M {
let data = http.body.data ?? Data()
if http.contentType == MediaType.json {
return try M(jsonUTF8Data: data)
@vzsg
vzsg / 1_configure.swift
Created December 8, 2018 09:23
Vapor 3 Sessions with PostgreSQL example
import FluentPostgreSQL
import Vapor
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
// (1) Standard PostgreSQL setup
try services.register(FluentPostgreSQLProvider())
let pgURL = Environment.get("DATABASE_URL") ?? "postgres://vapor:[email protected]:5432/vapor"
let pgConfig = PostgreSQLDatabaseConfig(url: pgURL)!
@vzsg
vzsg / 1_IkigaJSON+Vapor.swift
Last active April 24, 2019 14:09
Using IkigaJSON instead of Foundation in Vapor 3
import Vapor
import IkigaJSON
extension IkigaJSONDecoder: DataDecoder {
public func decode<D>(_ decodable: D.Type, from data: LosslessDataConvertible) throws -> D where D : Decodable {
return try self.decode(decodable, from: data.convertToData())
}
}
extension IkigaJSONEncoder: DataEncoder {
@vzsg
vzsg / LongPoll.swift
Created November 4, 2018 13:20
An attempt to tame long polling with chunked streams in Vapor 3
import Foundation
import NIO
import Vapor
final class LongPollManager<T: Encodable> {
private var longPolls: [LongPoll<T>] = []
private let queue = DispatchQueue(label: "LongPollManager-\(T.self)-Queue")
func add(_ longPoll: LongPoll<T>) {
queue.async {
@vzsg
vzsg / 1_JSONTag.swift
Last active November 25, 2020 13:06
Automatically encoding data to JSON with Leaf (for embedding into scripts)
import Leaf
import Foundation
final class JSONTag: TagRenderer {
private let encoder = JSONEncoder()
func render(tag: TagContext) throws -> EventLoopFuture<TemplateData> {
try tag.requireNoBody()
try tag.requireParameterCount(1)
let json = try encoder.encode(tag.parameters[0])
@vzsg
vzsg / 1_EmailSender.swift
Created October 4, 2018 19:40
Custom service and DirectoryConfig usage example (Vapor 3)
import Service
import Foundation
import SwiftSMTP
struct EmailSenderConfig: Service {
let fromEmail: String
let fromName: String
let smtpHostname: String
let smtpPort: Int
let smtpEmail: String
@vzsg
vzsg / 1_Fetch.swift
Last active June 25, 2021 10:37
A solution for the N+1 problem when fetching children for parents (Fluent 3)
import Fluent
func fetchChildren<Parent, ParentID, Child: Model, Result>(
of parents: [Parent],
idKey: KeyPath<Parent, ParentID?>,
via reference: KeyPath<Child, ParentID>,
on conn: DatabaseConnectable,
combining: @escaping (Parent, [Child]) -> Result) -> Future<[Result]> where ParentID: Hashable & Encodable {
let parentIDs = parents.compactMap { $0[keyPath: idKey] }
let children = Child.query(on: conn)
@vzsg
vzsg / 1_AppStoreReceiptValidation.swift
Last active September 15, 2023 18:42
Starting point for App Store receipt validation with Vapor 3
import Foundation
struct AppStoreReceiptValidationRequest: Encodable {
let receiptData: String
let password: String?
let excludeOldTransactions: Bool
private enum CodingKeys: String, CodingKey {
case receiptData = "receipt-data"
case password