Tweak documentation and import names.

This commit is contained in:
Jimmy Cuadra 2019-07-25 10:04:49 -07:00
parent 4324ab29cf
commit bb5a159412

View File

@ -1,9 +1,10 @@
//! Crate ruma_api contains core types used to define the requests and responses for each endpoint //! Crate `ruma_api` contains core types used to define the requests and responses for each endpoint
//! in the various [Matrix](https://matrix.org) API specifications. //! in the various [Matrix](https://matrix.org) API specifications.
//! These types can be shared by client and server code for all Matrix APIs. //! These types can be shared by client and server code for all Matrix APIs.
//! //!
//! When implementing a new Matrix API, each endpoint has a type that implements `Endpoint`, plus //! When implementing a new Matrix API, each endpoint has a request type which implements
//! the necessary associated types. //! `Endpoint`, and a response type connected via an associated type.
//!
//! An implementation of `Endpoint` contains all the information about the HTTP method, the path and //! An implementation of `Endpoint` contains all the information about the HTTP method, the path and
//! input parameters for requests, and the structure of a successful response. //! input parameters for requests, and the structure of a successful response.
//! Such types can then be used by client code to make requests, and by server code to fulfill //! Such types can then be used by client code to make requests, and by server code to fulfill
@ -41,25 +42,27 @@ use std::{
io, io,
}; };
use http::{self, Method, Request as HttpRequest, Response as HttpResponse, StatusCode}; use http::{self, Method, StatusCode};
use ruma_identifiers; use ruma_identifiers;
use serde_json; use serde_json;
use serde_urlencoded; use serde_urlencoded;
/// A Matrix API endpoint's Request type /// A Matrix API endpoint.
///
/// The type implementing this trait contains any data needed to make a request to the endpoint.
pub trait Endpoint: pub trait Endpoint:
TryFrom<HttpRequest<Vec<u8>>, Error = Error> + TryInto<HttpRequest<Vec<u8>>, Error = Error> TryFrom<http::Request<Vec<u8>>, Error = Error> + TryInto<http::Request<Vec<u8>>, Error = Error>
{ {
/// The corresponding Response type /// Data returned in a successful response from the endpoint.
type Response: TryFrom<HttpResponse<Vec<u8>>, Error = Error> type Response: TryFrom<http::Response<Vec<u8>>, Error = Error>
+ TryInto<HttpResponse<Vec<u8>>, Error = Error>; + TryInto<http::Response<Vec<u8>>, Error = Error>;
/// Metadata about the endpoint /// Metadata about the endpoint.
const METADATA: Metadata; const METADATA: Metadata;
} }
/// An error when converting an `Endpoint::Request` to a `http::Request` or a `http::Response` to /// An error when converting an `Endpoint` request or response to the corresponding type from the
/// an `Endpoint::Response`. /// `http` crate.
#[derive(Debug)] #[derive(Debug)]
pub struct Error(pub(crate) InnerError); pub struct Error(pub(crate) InnerError);
@ -90,16 +93,22 @@ impl StdError for Error {}
pub(crate) enum InnerError { pub(crate) enum InnerError {
/// An HTTP error. /// An HTTP error.
Http(http::Error), Http(http::Error),
/// A I/O error. /// A I/O error.
Io(io::Error), Io(io::Error),
/// A Serde JSON error. /// A Serde JSON error.
SerdeJson(serde_json::Error), SerdeJson(serde_json::Error),
/// A Serde URL decoding error. /// A Serde URL decoding error.
SerdeUrlEncodedDe(serde_urlencoded::de::Error), SerdeUrlEncodedDe(serde_urlencoded::de::Error),
/// A Serde URL encoding error. /// A Serde URL encoding error.
SerdeUrlEncodedSer(serde_urlencoded::ser::Error), SerdeUrlEncodedSer(serde_urlencoded::ser::Error),
/// A Ruma Identitifiers error. /// A Ruma Identitifiers error.
RumaIdentifiers(ruma_identifiers::Error), RumaIdentifiers(ruma_identifiers::Error),
/// An HTTP status code indicating error. /// An HTTP status code indicating error.
StatusCode(StatusCode), StatusCode(StatusCode),
} }
@ -151,15 +160,20 @@ impl From<StatusCode> for Error {
pub struct Metadata { pub struct Metadata {
/// A human-readable description of the endpoint. /// A human-readable description of the endpoint.
pub description: &'static str, pub description: &'static str,
/// The HTTP method used by this endpoint. /// The HTTP method used by this endpoint.
pub method: Method, pub method: Method,
/// A unique identifier for this endpoint. /// A unique identifier for this endpoint.
pub name: &'static str, pub name: &'static str,
/// The path of this endpoint's URL, with variable names where path parameters should be filled /// The path of this endpoint's URL, with variable names where path parameters should be filled
/// in during a request. /// in during a request.
pub path: &'static str, pub path: &'static str,
/// Whether or not this endpoint is rate limited by the server. /// Whether or not this endpoint is rate limited by the server.
pub rate_limited: bool, pub rate_limited: bool,
/// Whether or not the server requires an authenticated user for this endpoint. /// Whether or not the server requires an authenticated user for this endpoint.
pub requires_authentication: bool, pub requires_authentication: bool,
} }
@ -170,9 +184,7 @@ mod tests {
pub mod create { pub mod create {
use std::convert::TryFrom; use std::convert::TryFrom;
use http::{ use http::{self, header::CONTENT_TYPE, method::Method};
header::CONTENT_TYPE, method::Method, Request as HttpRequest, Response as HttpResponse,
};
use ruma_identifiers::{RoomAliasId, RoomId}; use ruma_identifiers::{RoomAliasId, RoomId};
use serde::{de::IntoDeserializer, Deserialize, Serialize}; use serde::{de::IntoDeserializer, Deserialize, Serialize};
use serde_json; use serde_json;
@ -180,6 +192,13 @@ mod tests {
use crate::{Endpoint, Error, Metadata}; use crate::{Endpoint, Error, Metadata};
/// A request to create a new room alias.
#[derive(Debug)]
pub struct Request {
pub room_id: RoomId, // body
pub room_alias: RoomAliasId, // path
}
impl Endpoint for Request { impl Endpoint for Request {
type Response = Response; type Response = Response;
@ -193,22 +212,10 @@ mod tests {
}; };
} }
/// A request to create a new room alias. impl TryFrom<Request> for http::Request<Vec<u8>> {
#[derive(Debug)]
pub struct Request {
pub room_id: RoomId, // body
pub room_alias: RoomAliasId, // path
}
#[derive(Debug, Serialize, Deserialize)]
struct RequestBody {
room_id: RoomId,
}
impl TryFrom<Request> for HttpRequest<Vec<u8>> {
type Error = Error; type Error = Error;
fn try_from(request: Request) -> Result<HttpRequest<Vec<u8>>, Self::Error> { fn try_from(request: Request) -> Result<http::Request<Vec<u8>>, Self::Error> {
let metadata = Request::METADATA; let metadata = Request::METADATA;
let path = metadata let path = metadata
@ -220,7 +227,7 @@ mod tests {
room_id: request.room_id, room_id: request.room_id,
}; };
let http_request = HttpRequest::builder() let http_request = http::Request::builder()
.method(metadata.method) .method(metadata.method)
.uri(path) .uri(path)
.body(serde_json::to_vec(&request_body).map_err(Error::from)?)?; .body(serde_json::to_vec(&request_body).map_err(Error::from)?)?;
@ -229,10 +236,10 @@ mod tests {
} }
} }
impl TryFrom<HttpRequest<Vec<u8>>> for Request { impl TryFrom<http::Request<Vec<u8>>> for Request {
type Error = Error; type Error = Error;
fn try_from(request: HttpRequest<Vec<u8>>) -> Result<Self, Self::Error> { fn try_from(request: http::Request<Vec<u8>>) -> Result<Self, Self::Error> {
let request_body: RequestBody = let request_body: RequestBody =
::serde_json::from_slice(request.body().as_slice())?; ::serde_json::from_slice(request.body().as_slice())?;
let path_segments: Vec<&str> = request.uri().path()[1..].split('/').collect(); let path_segments: Vec<&str> = request.uri().path()[1..].split('/').collect();
@ -248,14 +255,19 @@ mod tests {
} }
} }
#[derive(Debug, Serialize, Deserialize)]
struct RequestBody {
room_id: RoomId,
}
/// The response to a request to create a new room alias. /// The response to a request to create a new room alias.
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub struct Response; pub struct Response;
impl TryFrom<HttpResponse<Vec<u8>>> for Response { impl TryFrom<http::Response<Vec<u8>>> for Response {
type Error = Error; type Error = Error;
fn try_from(http_response: HttpResponse<Vec<u8>>) -> Result<Response, Self::Error> { fn try_from(http_response: http::Response<Vec<u8>>) -> Result<Response, Self::Error> {
if http_response.status().is_success() { if http_response.status().is_success() {
Ok(Response) Ok(Response)
} else { } else {
@ -264,14 +276,15 @@ mod tests {
} }
} }
impl TryFrom<Response> for HttpResponse<Vec<u8>> { impl TryFrom<Response> for http::Response<Vec<u8>> {
type Error = Error; type Error = Error;
fn try_from(_response: Response) -> Result<HttpResponse<Vec<u8>>, Self::Error> { fn try_from(_: Response) -> Result<http::Response<Vec<u8>>, Self::Error> {
let response = HttpResponse::builder() let response = http::Response::builder()
.header(CONTENT_TYPE, "application/json") .header(CONTENT_TYPE, "application/json")
.body(b"{}".to_vec()) .body(b"{}".to_vec())
.unwrap(); .unwrap();
Ok(response) Ok(response)
} }
} }