I was wondering how you guys would solve the following problem
I have an actix api the following thoughts about my response model. it's a document based response (not field based resposne filtering atm although I am thinking about it)
the first 2 parameters are just for the user to make decisions before accessing the data.
the reason I got 2 branches instead just a code + data setting is in theory you could get 100 okay things and 1 failed things. (debatable I know - not sure myself)
# models.rs
#[derive(Serialize, Deserialize, PartialEq)]
pub struct AppResponse<T=String, E=String> {
pub status: i16,
pub message: Option<String>,
pub success: Option<T>,
pub error: Option<E>,
}
impl <T>AppResponse<T> {
pub fn success(success: T, message: String) -> AppResponse<T> {
AppResponse {
status: 1,
message: Some(message.clone()),
success: Some(success),
error: None
}
}
}
impl <E>AppResponse<E> {
pub fn fail(error: E, message: String) -> AppResponse<Option<String>, E> {
AppResponse {
status: 1,
message: Some(message.clone()),
success: None,
error: Some(error),
}
}
}
impl <T, E>AppResponse<T, E> {
pub fn mixed(success: T, error: E, message: String) -> AppResponse<T, E> {
AppResponse {
status: 1,
message: Some(message.clone()),
success: Some(success),
error: Some(error),
}
}
}
This is how I currently solved it. I am pretty sure there is a better solution than just defaulting to string, probably defaulting to bool ... not sure. it works that's step one.
I am curious about different normalized response models. I should probably add partial equals and filter over map so a more matrix like approach for data. So go for it :) give me feedback :).
The
impls are quiet interesting, I hadn't actually seen that...But I do think it has a problem, in that this does not compile for me:
let _ = AppResponse::fail(1, 17); expected struct `std::string::String`, found integral variableI'm not sure it's wise... It'll create an AppResponse<String, int> if you do
fail(1, 17)after fixing, but isn't it better to leaveStringfree? If you want a failedAppResponse<int, int>(e.g. because the method can fail or succeed with anint), do you have any way to create one? Or is mixed the only way?I may be mistaken about the above, I haven't seen the pattern. Some other notes:
Is the mixed mode really necessary? I don't like the idea... If some items can fail, isn't it better to record a result per item? It feels like, if you get a mixed-mode result, currently all you can really do is treat it as a full error...
If it's necessary to keep mixed mode, I'd still consider using an
enuminstead ofOptions. That way you can ensure that a success result never has errors:enum AppResponse<T=String, E=String> { Success(T), Error(E), Mixed(T, E), }Maybe that's my personal preference.
Of course the
codeisn't useful this way but I presume its a placeholder.And why clone
message?