用于缩短UUID,特别是在URL中使用时;以及与Vapor一起使用。
...
dependencies: [
...
// UUID Shortener ✂️
.package(url: "https://github.com/Dean151/uuid-shortener", from: "1.0.0"),
...
],
targets: [
.target(
...
dependencies: [
...
.product(name: "UUIDShortener", package: "uuid-shortener"),
...
],
...
// Shorten any UUID
let uuid = UUID() // F0E07462-68F1-4219-96FE-D98C8449CAF0
let base32 = try uuid.shortened(using: .base32) // e9dlbzsyrie7pfu5hhx66b1m8
let base58 = try uuid.shortened(using: .base58) // vKbtaFgee2NLZVnLW6yuuq
let base62 = try uuid.shortened(using: .base62) // 7kwJxwyrgxEyZAKcDMFE1W
let base66 = try uuid.shortened(using: .base64) // 3MU7hyqf526pr-SoO4isHM
let base90 = try uuid.shortened(using: .base90) // n#g|6HlzuCBbxY~bho1!
// And get the original UUID back:
let original = try UUID(shortened: base62, using: .base62)
您可以在URL中使用短标识符,而不是使用完整的base16 UUID。
对于URL来说,最好的选择之一是base62(没有特殊字符),尽管base64在这里也可以工作。
如果您需要消除字符歧义,则最好使用去除相似字符的base58。
struct TodosController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
routes.get("todo", ":identifier", use: getTodo)
}
private func getTodo(req: Request) throws -> EventLoopFuture<Todo> {
guard let shortIdentifier = req.parameters.get("identifier"),
let identifier = try? UUID(shortened: shortIdentifier, using: .base62) else {
throw Abort(.badRequest, reason: "Missing or unparsable identifier")
}
return Todo.find(identifier, on: req.db)
.unwrap(or: Abort(.notFound))
}
...
}