-
Notifications
You must be signed in to change notification settings - Fork 0
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 #61 from yumemi-inc/f-err
エラーレスポンス対応
- Loading branch information
Showing
3 changed files
with
55 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
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,49 @@ | ||
// | ||
// APIQualityMiddleware.swift | ||
// | ||
// | ||
// Created by 古宮 伸久 on 2024/06/20. | ||
// | ||
|
||
import Vapor | ||
|
||
/// API の品質を表現します。 | ||
enum APIQuality: Sendable { | ||
case sometimesFails(probability: Double) | ||
case alwaysFails | ||
case neverFails | ||
|
||
func test() -> Bool { | ||
return switch self { | ||
case .sometimesFails(let probability): | ||
shouldFail(probability: probability) | ||
case .alwaysFails: | ||
true | ||
case .neverFails: | ||
false | ||
} | ||
} | ||
|
||
private func shouldFail(probability: Double) -> Bool { | ||
return (0 ..< probability).contains(Double.random(in: 0 ..< 1)) | ||
} | ||
} | ||
|
||
final class APIQualityMiddleware: Middleware, Sendable { | ||
|
||
let apiQuality: APIQuality | ||
let onError: Error | ||
|
||
init(apiQuality: APIQuality, onError: Error) { | ||
self.apiQuality = apiQuality | ||
self.onError = onError | ||
} | ||
|
||
func respond(to request: Vapor.Request, chainingTo next: any Vapor.Responder) -> NIOCore.EventLoopFuture<Vapor.Response> { | ||
if apiQuality.test() { | ||
request.eventLoop.makeFailedFuture(onError) | ||
} else { | ||
next.respond(to: request) | ||
} | ||
} | ||
} |
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