use laravel::http::{IntoResponse, Response, StatusCode};
use crate::encoders::EncoderOptions;
use crate::error::Result;
use crate::format::{FileExtension, Format, IntoFormat, MediaType};
use crate::image::Image;
pub trait ResponseFormat {
fn response_format(self, image: &Image) -> Result<Format>;
}
macro_rules! response_format {
($($type:ty),*) => {$(
impl ResponseFormat for $type {
fn response_format(self, _: &Image) -> Result<Format> {
self.into_format()
}
}
)*};
}
response_format!(Format, MediaType, FileExtension, &str, &String, String);
impl ResponseFormat for Option<Format> {
fn response_format(self, image: &Image) -> Result<Format> {
Ok(match self {
Some(format) => format,
None => Format::try_create(image.origin().media_type()).unwrap_or(Format::Jpeg),
})
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ImageResponseFactory;
impl ImageResponseFactory {
pub fn make(image: &Image, format: impl ResponseFormat, options: EncoderOptions) -> Result<Response> {
let format = format.response_format(image)?;
let encoded = image.encode_using_media_type(format.media_type(), options)?;
let content_type = format.media_type().value();
let mut response = (StatusCode::OK, encoded.into_bytes()).into_response();
if let Ok(value) = content_type.parse() {
response.headers_mut().insert("content-type", value);
}
Ok(response)
}
}
impl Image {
pub fn response(&self, format: impl ResponseFormat, options: EncoderOptions) -> Result<Response> {
ImageResponseFactory::make(self, format, options)
}
}