Skip to content
This repository has been archived by the owner on Apr 20, 2024. It is now read-only.

Commit

Permalink
Merge pull request #33 from nodes-vapor/feature/add-slugwrapper
Browse files Browse the repository at this point in the history
Wrapper for looking models using a slug
  • Loading branch information
steffendsommer authored May 18, 2017
2 parents c4171da + f2ab4cc commit 1e9950a
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions Sources/SlugWrapper.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import Vapor
import Fluent

protocol SlugWrapable {
static var slugField: String { get }
}

enum SlugWrapper<T: Parameterizable> {
case id(value: Int)
case slug(value: String)
}

extension SlugWrapper {
static func make(for parameter: String) throws -> SlugWrapper {
if let id = Int(parameter) {
return SlugWrapper.id(value: id)
} else {
return SlugWrapper.slug(value: parameter)
}
}
}

extension SlugWrapper: Parameterizable {
public static var uniqueSlug: String {
return T.uniqueSlug
}
}

extension SlugWrapper where T: Entity & SlugWrapable {
internal func resolve() throws -> T {
switch self {
case .id(let id):
guard let lookup = try T.find(id) else {
throw Abort.notFound
}
return lookup
case .slug(let value):
return try T.makeQuery().filter(T.slugField, value).firstOrFail()
}
}
}

0 comments on commit 1e9950a

Please sign in to comment.