use lino_objects_codec::LinoValue;
use crate::headers::Headers;
#[derive(Debug, Clone, PartialEq)]
pub enum Body {
Empty,
Value(LinoValue),
Raw(String),
}
impl From<LinoValue> for Body {
fn from(value: LinoValue) -> Self {
Body::Value(value)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LinoResult {
pub body: Body,
pub status: u16,
pub headers: Headers,
pub etag: bool,
pub preconditions: Option<bool>,
pub require_precondition: bool,
pub media_type: Option<String>,
}
impl LinoResult {
pub fn new(status: u16, body: Body) -> Self {
Self {
body,
status,
headers: Headers::new(),
etag: true,
preconditions: None,
require_precondition: false,
media_type: None,
}
}
pub fn with_header<N: Into<String>, V: Into<String>>(mut self, name: N, value: V) -> Self {
self.headers.insert(name, value);
self
}
pub fn with_headers(mut self, headers: Headers) -> Self {
for (name, value) in headers.iter() {
self.headers.insert(name.to_string(), value.to_string());
}
self
}
pub fn without_etag(mut self) -> Self {
self.etag = false;
self
}
pub fn with_preconditions(mut self, preconditions: bool) -> Self {
self.preconditions = Some(preconditions);
self
}
pub fn requiring_precondition(mut self, require: bool) -> Self {
self.require_precondition = require;
self
}
pub fn with_media_type<S: Into<String>>(mut self, media_type: S) -> Self {
self.media_type = Some(media_type.into());
self
}
}
pub fn ok(value: LinoValue) -> LinoResult {
LinoResult::new(200, Body::Value(value))
}
pub fn created(value: LinoValue, location: &str) -> LinoResult {
LinoResult::new(201, Body::Value(value)).with_header("Location", location)
}
pub fn accepted(value: LinoValue) -> LinoResult {
LinoResult::new(202, Body::Value(value))
}
pub fn no_content() -> LinoResult {
LinoResult::new(204, Body::Empty)
}
pub fn status(status_code: u16, value: LinoValue) -> LinoResult {
LinoResult::new(status_code, Body::Value(value))
}
pub fn status_empty(status_code: u16) -> LinoResult {
LinoResult::new(status_code, Body::Empty)
}
pub fn raw_response(body: &str, media_type: &str, status_code: u16) -> LinoResult {
LinoResult::new(status_code, Body::Raw(body.to_string())).with_media_type(media_type)
}
impl From<LinoValue> for LinoResult {
fn from(value: LinoValue) -> Self {
ok(value)
}
}
impl From<()> for LinoResult {
fn from(_: ()) -> Self {
no_content()
}
}