Marionette way to Live form validation - forms

What is that Marionette way to live (i.e. on every key press) form validation? I mean both two cases - on client-side and - at rare case - via ajax with deffereds.
We already have model's validation. So, the situation has Backbone/Marionette specifics, if we want to use model's validation for client-side live form validation also.

You can use server side validation.
The server should return error code 422 with a Json similar like:
{"errors":{"user_email":["can't be blank"]}}
Then on client side use backbone's error callback (my code is in coffee script.):
#model.save null,
update: on
success: => #afterSuccessfullSave()
error: #setErrors
The #setErrors method callback then adds error specific classes to the labels and inputs.
Or there is a gem for Ruby https://github.com/bcardarella/client_side_validations there the model branch is intended to satisfy out bacbone needs but is not maintained... soo... I can advise you the server side validation or to write your own custom validation rule serializations...

Related

REST endpoint: how to proper design an action on a resource?

I have the resource /contracts with the following structure:
{
name: "Contract name",
signedAt: 123213231,
// etc.
}
While basic CRUD operations are well clear (GET /contracts, GET /contracts/{id}, POST /contracts, etc.) some doubts come when I have to do some concrete actions on the resource.
One of these actions is the following:
sign: means the contract is signed, so the signedAt date will need to be updated with the moment (date-time) the contract was signed.
So far I've been thinking about these different approaches:
PATCH-ing the resource
This approach will mean having the following endpoint method:
PATCH /contracts/{id}
and just posting the signedAt date { signedAt: 123213231 } meaning that after this the contract will be signed.
What I don't like about this approach is that the signature date comes from the client, I was thinking that having this date initialized on the backend side whenever a contract is signed could be better and more consistent.
Totally discarded, as the signedAt date should be set on the server
side exactly at the moment the sign is done.
POST-ing a new resource
This approach will mean having the signature action as a resource:
POST /contracts/{id}/sign
with an empty body in this case as we don't need to pass anything else so, once it is posted, the backend side would be the responsible for having the signature date initialized.
POST-ing the resource using 'action'
Similar to the previous approach, in this case I would use a query parameter called action on the contract resource:
POST /contracts/{idContract}?action=sign
also with an empty body where ?action=sign. Like in the previous approach, once posted the backend side would be the responsible for having the signature date initialized.
Questions
What would be the proper way to have this designed at a REST API level?
Is any of the approaches above close to a good design or not?
Would I need to modify any of the approaches?
Is there any better alternative?
I have designed a few rest APIs myself but I am not a restful evangelist so my answer might not be the best. I would suggest some of the following:
Create a custom converter for date values in your rest service that accepts date AND other specific fields. If you checkGoogle reporting APIs for example they allow you to use specific date range and also CURRENT_WEEK, CURRENT_MONTH etc. So you can add such specific value and use it. For example PATCH signedAt=CURRENT_DATE and the API handles that properly.
Add a boolean signed field to the resource. Do a POST or PATCH with signed=true. This way you will be able to eventually query only signed resources easily ;) Also it might be the case that people care only about if it is signed than when it was signed
I wouldn't use ?action=sign or /contracts/{id}/sign because these are not RESTFUL and even if you do use GET and POST you would use them in a way to create a workaround in order to implement actions in your design which shouldn't have actions
just posting the signedAt date { signedAt: 123213231 } meaning that after this the contract will be signed.
On HTTP Patch
The set of changes is represented in a format called a "patch document" identified by a media type.
Rather than rolling your own bespoke media type, you might want to consider whether one of the standard formats is suitable.
For example: JSON Patch.
Content-Type: application/json-patch+json
[ { "op": "replace", "path": "signedAt", "value": 123213231 }
JSON Merge Patch is another reasonable option
Content-Type: application/merge-patch+json
{ signedAt: 123213231 }
From what I can see, the primary difference is that JSON Patch provides a test operation which gives you finer grain control than simply relying upon validators
But you are absolutely right - PATCH gives the client code authority to specify the time value. If that's not appropriate for your use case, then PATCH is the wrong tool in the box.
POST /contracts/{id}/sign
POST /contracts/{idContract}?action=sign
As far as REST/HTTP are concerned, these two choices are equivalent -- you are updating the state of one resource by sending an unsafe request to a different resource. There are some mild differences in how these spellings act when resolving references, but as request-targets, it doesn't make a difference to the client.
An option that you seem to have overlooked:
POST /contracts/{id}
action=sign
This has the advantage that, when successful, you get cache invalidation for free.
In a hypermedia API, the flow might go something like this: the client would GET the resource; because the resource hasn't been signed yet, the representation could include a form, with a "sign" button on it. The action on the form would be /contracts/{id}. The consumer "signs" the contract by submitting the form -- the agent gathers up the information described by the form, encodes it into the request body, and then posts the request to the server. The server responds success, and the client's cache knows to invalidate the previously fetched copy of the resource.

Using http response headers in order to communicate server-side errors from the backend to the front-end

I am working on a REST backend consumed by a javascript/ajax front-end.
I am trying to find a way to deal with invalid requests sent over by the front-end to the backend.
One of the issues I have is that HTTP status codes such as (400, 409) are not fine-grained enough to cover business logic errors such as passwords not matching (in the case of a user changing his password) or an email being unknown to the system (in the case of a user trying to signin with the application).
I am thinking of using HTTP response headers in order to communicate server-side error from the backend to the front-end.
I could for instance have an Error enum (or a class with constants) as follows:
public enum Error {
UNKNOWN_EMAIL,
PASSWORDS_DONT_MATCH,
//etc.
}
I would then use that enum in order to set the headers on the response as follows:
response.setHeader(Error.UNKNOWN_EMAIL.name(), "true");
... and deal with the error appropriately on the front-end.
Can the above architecture be improved? If so how?
Is my usage of HTTP response headers correct?
Should I use constants or enums?
Is my usage of HTTP response headers correct?
I do not think it is incorrect, however I prefer to send an error message/code directly back in the response body. This is usually more convenient for the client to access and is more explicit. As part of consuming each response, the client can check the contents of the errors (you may have multiple) and act accordingly. The following is a little contrived just to provide an example:
// ...
{
"errors": {
"username": "not found"
"password": "no match"
}
"warnings": {
"account": "expired"
}
}
// ...
The above is quite a simple approach - your JSON message can be as sophisticated as you wish but keep in mind that you should only expose the information the client needs for it to achieve its goal. This will also depend on whether you are publishing an API for 3rd parties/public consumption or whether its just for your own clients ie. your own website. If you have other parties consuming it then put some thought into it since once you publish it then you need to maintain it that way - otherwise you break any consumers.
Check out JSON API for some standardized guidance on handling errors.
Should I use constants or enums?
Since these are a related set of properties an enum is preferable over constants (I assume you are using Java).

GWT RequestFactory: Send changes twice

I need your help with the gwt requestfactory
considering following scenario:
I get an existing entity (let's say a invoice) from the server:
InvoiceEntityProxy invoice = request1.getInvoice();
I want to make some changes, so I edit it with a new request:
InvoiceEntityProxy editableInvoice = request2.edit(invoice);
//make some changes to editableInvoice
Now I send the changes made with the second request to the server, to create a preview:
request2.createPreview(editableInvoice);
When the request is sent, the invoice proxy is frozen and I re-enable editing by assigning the proxy to a new request:
editableInvoice = request3.edit(editableInvoice);
If everything is okay, i want to update the proxy and send it to the server, using the latest request:
request3.update(editableInvoice);
But the changes never arrive on the server, because the latest request (request3) doesn't know anything about the changes made to the proxy assigned to the request2.
I thought about following solutions:
I could redo the changes on the latest proxy. But for that, I've to iterate over all attributes and set them again (not very friendly solution, because I've to adjust the method each time I add some attributes to the proxy)
Another approach would be to send the proyx without an id to the server and send the id as second parameter of the update-method. But this would be a shame, because not only the deltas would be sent to the server (which is one of the greate features of the requestFactory).
So what is the best and most common practice to let the request3 know about the changes already made to the proxy, when it was assigned to another request.
You simply forget to call fire(). Example
request2.createPreview(editableInvoice).fire();
Bear in mind that if the following request depend on the result of the previous one, you should put your code in the OnSuccess methode because the request is asynchronous
It's also possible to append multiple requests
EDIT
It important to use the same request for the edit and fire operations. So replace this line
request.update(editableInvoice);
with
request3.update(editableInvoice);
Nice! I found the solution for my problem.
I still have an instance of the original proxy, because the edit() method of the context always return a new instance of the proxy. So I save the original proxy before sending any request.
After each successful request, I re-enable editing the proxy by call the edit method again:
editableInvoice = request3.edit(editableInvoice);
Now the crux:
I can set the original proxy of a proxy, which is used to consider if it changed and what changed. This is done by using AutoBean and set the PARENT_OBJECT Tag like this:
AutoBean<InvoiceEntityProxy> editableInvoiceBean = AutoBeanUtils.getAutoBean(editableInvoice);
AutoBean<InvoiceEntityProxy> originalInvoiceBean = AutoBeanUtils.getAutoBean(originalInvoice);
editableInvoiceBean.setTag(Constants.PARENT_OBJECT, originalInvoiceBean);
On the next request all changed properties are send to the server again.
Thank you for your help and thank you for the hint with the AutoBean #Zied Hamdi
You also can use AutoBeans to duplicate the object before you start changing it. You can keep the original one untouched then request.edit() it and apply changes (introspection like changes) from the "dirty" object.
You'll maybe have to do some research on how to handle EntityProxies since they are "special AutoBeans" : I had to use special utility objects to serialize them to json (available in GWT). So there might be some special handling in doing a deep copy too.
There is an issue maybe with GWT keeping only one version of each EntityProxy (I never checked if it is global or only in the context of a request)

Sending a response without calling render() from a Mojolicious::Lite application

I am writing a "partial proxy" in Mojolicious::Lite. Certain requests (depending on the query path, and on the values of the parameters) generate a request to another server, while others are handled locally.
There is a nice proxy example, but it totally overrides the request/response handling and thus is not suitable to my needs.
Currently, I am marshalling the response via
$self->render(data => $res->body, code => $res->code);
Unfortunately, this does not take into account different content types. Using Mojolicious::Type does not help,
because I need a reverse mapping from the content type
in $res to the format in render(); besides,
the number of possible render formats is significantly smaller
than the number of possible content types.
So ideally, instead of the $self->render() call above
I need a way to say "here, I got a response in $res;
please return it back to the client as is".
Any ideas? Thanks!
Ok, the trick was to replace render() call with
$self->tx->res($res);
$self->rendered($res->code);

Proper way to convey error messages during calls to a REST service?

I'm writing a REST based web service, and I'm trying to figure out the best way to handle error conditions.
Currently the service is returning HTTP Errors, such as Bad Request, but how can I return extra information to give developers using the web service an idea what they're doing wrong?
For example: creating a user with a null username returns an error of Bad Request. How can I add that the error was caused by a null username parameter?
According to the HTTP spec, the text that comes after the three digit response code, the "Reason-Phrase", can only be replaced with a logical equivalent. So you can't respond with 400 null user and expect anything useful to happen. Indeed, The client is not required to examine or display the Reason- Phrase.
In general, the HTTP response entity (typically the page that accompanies the response) should contain information useful to the client to guide them forward, even when the response is an error. On the web, most such errors are HTML, and are devoid of machine readable information, but most browsers do show the error to the user (and SO's error page is pretty good!).
So for a primarily machine readable resource you have two options:
Pass a human readable message anyway. Return 400 Bad Request with a HTML response, which the client may opt to show to the user. It's dead easy but it's a bit like throwing an unchecked exception, it passes all the hard work to the client, or indeed the end user.
Allow clients to recover. Return 400 Bad Request with a machine readable response which is part of your API, so clients can recover from known error conditions. This is harder, like throwing a checked exception, it becomes part of the API, and it allows clients to recover gracefully if they want to.
You could even make the server support both scenarios by defining a media type for the machie readable error recovery document, and allow clients to "accept" them: Accept: application/atom+xml, application/my.proprietary.errors+json
Clients that forget the mandatory field can opt in to getting machine readable errors or human readable errors by choosing to Accepting the error media type.
It's stated in the HTTP spec that most error codes should return some basic text that gives a clarification of why the error is being returned. The basic Java Servlet Spec defines the HttpServletResponse.sendError(int Code, String message) for this purpose.
String desc = "my Description";
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(desc).type("text/plain").build());