Skip to content

Commit

Permalink
refactor: optimize start handler and service for better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
wangeguo committed Jan 18, 2024
1 parent 4299efe commit 54f3378
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
4 changes: 4 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ pub enum ApiError {

#[error("Failed to delete playbook: {0}")]
FailedToDeletePlaybook(HTTPError),

#[error("Failed to start playbook: {0}")]
FailedToStartPlaybook(HTTPError),
}

impl IntoResponse for ApiError {
Expand All @@ -47,6 +50,7 @@ impl IntoResponse for ApiError {
Self::NotFoundPlaybook(e) => (StatusCode::NOT_FOUND, e.to_string()),
Self::FailedToCreatePlaybook(e) => (StatusCode::BAD_REQUEST, e.to_string()),
Self::FailedToDeletePlaybook(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
Self::FailedToStartPlaybook(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
};

error!("{} - {}", status, message);
Expand Down
6 changes: 4 additions & 2 deletions src/handlers/playbook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,17 @@ pub async fn delete(Path(id): Path<Uuid>, State(ctx): State<Arc<Context>>) -> Re

Ok(StatusCode::NO_CONTENT)
}

/// start a playbook
#[utoipa::path(
post, path = "/v1/playbooks/{id}/actions/start",
params(
("id" = Uuid, description = "The id of playbook"),
),
responses(
(status = 204, description = "Playbook deleted successfully"),
(status = 404, description = "Playbook not found")
(status = 204, description = "Playbook start successfully"),
(status = 404, description = "Playbook not found"),
(status = 500, description = "Failed to start playbook")
),
tag = "Playbooks"
)]
Expand Down
13 changes: 11 additions & 2 deletions src/services/playbook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,17 @@ impl PlaybookService {
}

pub async fn start(ctx: Arc<Context>, id: Uuid) -> Result<u16> {
info!("Start playbooks in {}...", id);
ctx.client.playbooks().start(&id.to_string()).map_err(ApiError::NotFoundPlaybook)
let playbooks = ctx.client.playbooks();
match playbooks.get(&id.to_string()) {
Ok(_) => {
info!("Start playbooks in {}...", id);
playbooks.start(&id.to_string()).map_err(ApiError::FailedToStartPlaybook)
}
Err(e) => {
error!("Not found playbooks in {}, error: {}", id, e.to_string());
Err(ApiError::NotFoundPlaybook(e))
}
}
}

pub async fn logs(_ctx: Arc<Context>, _id: Uuid) {
Expand Down

0 comments on commit 54f3378

Please sign in to comment.