Trait limiting_factor::api::replies::ApiResponse[][src]

pub trait ApiResponse<T> {
    fn into_json_response(self) -> ApiJsonResponse<T>;
}
Expand description

This trait allows to consume an object into an HTTP response.

Required methods

Consumes the value and creates a JSON or a Status result response.

Implementations on Foreign Types

Prepares an API response from a query result.

The result is the data structure prepared by the Diesel ORM after a SELECT query with one result, for example using first method. You can also you use it to parse the returning result (… RETURNING *), which is a default for Diesel after an INSERT query.

So result can be:

  • Ok(T)
  • Err(E) where E is a Status containing an HTTP error code according the situation

Examples

To offer a /player/foo route to serve player information from the players table:

use limiting_factor::api::ApiResponse;
use limiting_factor::api::ApiJsonResponse;

#[get("/player/<name>")]
pub fn get_player(connection: DatabaseConnection, name: String) -> ApiJsonResponse<Player> {
    players
        .filter(username.eq(&name))
        .first::<Player>(&*connection)
        .into_json_response()
}

This will produce a JSON representation when the result is found, a 404 error when no result is found, a 500 error if there is a database issue.

To insert a new player in the same table:

use limiting_factor::api::ApiResponse;
use limiting_factor::api::ApiJsonResponse;

#[post("/register", format="application/json", data="<user>")]
pub fn register(connection: DatabaseConnection,  user: Json<UserToRegister>) -> ApiJsonResponse<Player> {
    let user: UserToRegister = user.into_inner();
    let player_to_create = user.to_new_player();

    diesel::insert_into(players)
        .values(&player_to_create)
        .get_result::<Player>(&*connection)
        .into_json_response()
}

This will produce a JSON representation of the newly inserted player if successful. If the insert fails because of an unique constraint violation (e.g. an username already taken), it returns a 409 Conflict. If the failure is from a foreign key integrity constraint, it returns a 400. If there is any other database issue, it returns a 500.

Prepares an API response from a JSON.

Implementors

Prepares an API response from a Serde-serializable result.

This is probably the easiest way to convert most struct into API responders.

Examples