extension Request {
/**
Used to represent whether validation was
successful or encountered an error
resulting in a failure.
- Success: The validation was successful
- Failure: The validation failed encountering
the provided error.
*/
public enum ValidationResult {
case Success
case Failure(NSError)
}
/**
A closure used to validate a request that
takes a URL request and URL response,
and returns whether the request was valid.
*/
public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
- parameter validation: A closure to validate the request.
- returns: The request.
*/
public func validate(validation: Validation) ->Self {
delegate.queue.addOperationWithBlock {
if let response = self.response where self.delegate.error == nil,
case let .Failure(error) = validation(self.request, response) {
self.delegate.error = error
}
}
return self
}
// MARK: - Status Code
/**
Validates that the response has a status
code in the specified range.
If validation fails, subsequent calls to
response handlers will have an associated
error.
- parameter range: The range of acceptable status codes.
- returns: The request.
*/
public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
return validate { _, response in
if acceptableStatusCode.contains(response.statusCode) {
return .Success
else {
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
}
}
}
// MARK: - Content-Type
private struct MIMEType {
let type: String
let subtype: String
init?(_ string: String) {
let components: [String] = {
let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex)
}()
if let type = components.first,
subtype = components.last {
self.type = type
self.subtype = subtype
}else {
return nil
}
}
func matches(MIME: MIMEType) -> Bool {
switch(type, subtype) {
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
return true
default:
return false
}
}
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
- parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
- returns: The request.
*/
public func validate<S: SequenceType where S.Generator.Element == String>(contentType acceptableContentType: S)-> Self {
return validate { _, response in
guard let validData = self.delegate.data where validData.length > 0 else {
return .Success
}
if let
responseContentType = response.MIMEType,
responseMIMEType = MIMEType(responseContentType) {
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
return .Success
}
}
}else {
for contentType in acceptableContentTypes {
if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
return .Success
}
}
}
let failureReason: String
if let responseContentType == response.MIMEType {
failureReason = ("Response content type \"\(responseContentType)\" does not match any acceptable " + "content types: \(acceptableContentTypes)")
}else {
failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
}
return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason))
}
}
// MARK: - Automatic
/**
Validates that the response has a status
code in the default acceptable range of
200...299, and that the content type
matches any specified in the Accept HTTP
header field.
If validation fails, subsequent calls to response handlers will have an associated error.
- returns: The request.
*/
public func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = request?.valueForHTTPHeaderField("Accept") {
return accept.componentsSeparatedByString(",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
Validation
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 介绍 使用java validation注解, 可以方便的对bean内容进行检查。下表是validation注解及...
- admin.py中的form有效性检查假设提交的表单中有email项,即attriN中有email项。我们要对输入...
- Q: What is cross validation? How to do it right? A: Cross...
- 拆页: I 孩子,配偶的感受和他们的行为有直接关系,好的感受会有好的行为,怎样让他们感受好,就是接受他们的感受,实...