Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.