Skip to content

Instantly share code, notes, and snippets.

@alobanov
Created November 14, 2017 15:09
Show Gist options
  • Save alobanov/30dec2f118532b4cc32d82bc321ac1bd to your computer and use it in GitHub Desktop.
Save alobanov/30dec2f118532b4cc32d82bc321ac1bd to your computer and use it in GitHub Desktop.
Middleware example
class CheckNilMiddleware: Middleware {
override func check(value: MiddlewareItem) -> MiddlewareItem {
switch value {
case .value(let str):
if str == nil {
return .error("Значение равно nil")
}
default: break
}
return checkNext(value: value)
}
}
class CheckCountMiddleware: Middleware {
private let length: Int
init(length: Int) {
self.length = length
}
override func check(value: MiddlewareItem) -> MiddlewareItem {
switch value {
case .value(let str):
if str?.count != length {
return .error("Длинна должна быть \(length)")
}
default: break
}
return checkNext(value: value)
}
}
class PhoneFormatterMiddleware: Middleware {
private let format: String // "+X (XXX) XXX XX-XX"
init(format: String) {
self.format = format
}
override func check(value: MiddlewareItem) -> MiddlewareItem {
switch value {
case .value(let str):
if let s = str {
let cleanPhoneNumber = s.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
let mask = format
var result = ""
var index = cleanPhoneNumber.startIndex
for ch in mask {
if index == cleanPhoneNumber.endIndex {
break
}
if ch == "X" {
result.append(cleanPhoneNumber[index])
index = cleanPhoneNumber.index(after: index)
} else {
result.append(ch)
}
}
return .value(result)
}
default: break
}
return checkNext(value: value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment