This repository has been archived by the owner on Apr 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #33 from nodes-vapor/feature/add-slugwrapper
Wrapper for looking models using a slug
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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() | ||
} | ||
} | ||
} |