首页 > 数据库 > 数据库开发技术 > 【大家的项目】Poem-openapi
create_user接口创建一个用户,由于它的请求对象类型是Json,所以它只支持content-type为application/json的请求。返回的CreateUserResponse定义了不同状态码对应的响应类型。API宏描述的操作都会自动生成OpenAPI 3.0规范的文档,你可以clone仓库 https://github.com/poem-web/poem-openapi ,然后执行cargo run --example users,浏览器打开http://localhost:3000,就能看到一个非常奢华的Swagger UI(尽管我觉得它离GraphQL Playground的易用度还差得远)。😎use std::collections::HashMap;
use poem_openapi::{payload::Json, types::Password, OpenAPI, Response, Schema, API};
use tokio::sync::Mutex;
/// Create user schema
#[derive(Debug, Schema, Clone, Eq, PartialEq)]
struct User {
/// Id
id: String,
/// Name
name: String,
/// Password
password: Password,
}
/// Update user schema
#[derive(Debug, Schema, Clone, Eq, PartialEq)]
struct UpdateUser {
/// Name
name: Option<String>,
/// Password
password: Option<Password>,
}
#[derive(Response)]
enum CreateUserResponse {
/// Returns when the user is successfully created.
#[oai(status = 200)]
Ok,
/// Returns when the user already exists.
#[oai(status = 409)]
UserAlreadyExists,
}
#[derive(Response)]
enum FindUserResponse {
/// Return the specified user.
#[oai(status = 200)]
Ok(Json<User>),
/// Return when the specified user is not found.
#[oai(status = 404)]
NotFound,
}
#[derive(Response)]
enum DeleteUserResponse {
/// Returns when the user is successfully deleted.
#[oai(status = 200)]
Ok,
/// Return when the specified user is not found.
#[oai(status = 404)]
NotFound,
}
#[derive(Response)]
enum UpdateUserResponse {
/// Returns when the user is successfully updated.
#[oai(status = 200)]
Ok,
/// Return when the specified user is not found.
#[oai(status = 404)]
NotFound,
}
#[derive(Default)]
struct Api {
users: Mutex<HashMap<String, User>>,
}
#[API]
impl Api {
/// Create a new user
#[oai(path = "/users", method = "post", tag = "user")]
async fn create_user(&self, user: Json<User>) -> CreateUserResponse {
let mut users = self.users.lock().await;
if users.contains_key(&user.0.id) {
return CreateUserResponse::UserAlreadyExists;
}
users.insert(user.0.id.clone(), user.0);
CreateUserResponse::Ok
}
/// Find user by id
#[oai(path = "/users/:user_id", method = "get", tag = "user")]
async fn find_user(
&self,
#[oai(name = "user_id", in = "path")] user_id: String,
) -> FindUserResponse {
let users = self.users.lock().await;
match users.get(&user_id) {
Some(user) => FindUserResponse::Ok(Json(user.clone())),
None => FindUserResponse::NotFound,
}
}
/// Delete user by id
#[oai(path = "/users/:user_id", method = "delete", tag = "user")]
async fn delete_user(
&self,
#[oai(name = "user_id", in = "path")] user_id: String,
) -> DeleteUserResponse {
let mut users = self.users.lock().await;
match users.remove(&user_id) {
Some(_) => DeleteUserResponse::Ok,
None => DeleteUserResponse::NotFound,
}
}
/// Update user by id
#[oai(path = "/users/:user_id", method = "put", tag = "user")]
async fn put_user(
&self,
#[oai(name = "user_id", in = "path")] user_id: String,
update: Json<UpdateUser>,
) -> UpdateUserResponse {
let mut users = self.users.lock().await;
match users.get_mut(&user_id) {
Some(user) => {
if let Some(name) = update.0.name {
user.name = name;
}
if let Some(password) = update.0.password {
user.password = password;
}
UpdateUserResponse::Ok
}
None => UpdateUserResponse::NotFound,
}
}
}
#[tokio::main]
async fn main() {
poem::Server::bind("127.0.0.1:3000")
.await
.unwrap()
.run(
OpenAPI::new(Api::default())
.title("poem-openapi")
.version("0.1.0")
.server_with_description("http://localhost:3000", "localhost")
.tag_with_description("user", "Operations about user")
.ui_path("/"),
)
.await
.unwrap();
}
原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。