我正在使用蒸气进行身份验证,并想知道在路由中是否有一种好的方法可以在rest和web前端上重用逻辑。
struct AuthenticationController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
routes.group("auth") { auth in
auth.post("register", use: register)
auth.post("login", use: login)
}
auth.group("email-verification") { emailVerificationRoutes in
emailVerificationRoutes.post("", use: sendEmailVerification)
emailVerificationRoutes.get("", use: verifyEmail)
}
...
}
private func register(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
...
}
private func login(_ req: Request) throws -> EventLoopFuture<LoginResponse> {
...
}
...
}然后我将在api下添加这个auth集合
app.group("api") { api in
try! api.register(collection: AuthenticationController())
}当没有返回时,所有返回值都是HTTPStatus的HTTPStatus,或者实现以json形式返回对象的Content的结构
我想知道的是,在auth中如何进行重构和重构,并为其应用html web接口,这是一个很好的方法吗?因此,可以在/auth/login等下使用的post位、get页面、错误响应等web表单以及/api/auth/login。
我想我可能可以在方法中返回flatMap或类似的EventLoopFutures,并通过返回Views来转换它们,但我不知道该如何实现。
还是仅仅从AuthenticationController中提取所有逻辑,并创建一个WebAuthenticationController路由集合--例如,使用两个控制器中调用逻辑处理程序的处理程序构建类似的路由?
我尝试过搜索,但未能找到用于多种目的重用处理程序的任何示例。
发布于 2022-09-28 07:49:53
您可以创建一个符合ResponseEncodable的新结构,如下所示:
struct MixedResponse: ResponseEncodable {
var view: View?
var response: Response?
static func view(_ view: View) -> MixedResponse {
MixedResponse(view: view)
}
static func response(_ response: Response) -> MixedResponse {
MixedResponse(response: response)
}
}然后在encodeResponse函数中检查什么是nill &返回相关数据:
func encodeResponse(for request: Request) -> EventLoopFuture<Response> {
if let view {
//do something
}else if let response {
//do something
}
}您只返回MixedResponse,而不是返回特定的响应。我强烈鼓励你尝试async/await而不是期货。
https://stackoverflow.com/questions/73877850
复制相似问题