Part 3 - Conditional Operations
In the previous section, you found out how to turn on Spring Data REST’s hypermedia controls, have the UI navigate by paging, and dynamically resize based on changing the page size. You added the ability to create and delete employees and have the pages adjust. But no solution is complete with taking into consideration updates made by other users on the same bit of data you are currently editing.
Feel free to grab the code from this repository and follow along. This section is based on the previous section’s app with extra things added.
To PUT or not to PUT, that is the question
When you fetch a resource, there is risk is that it might go stale if someone else updates it. To deal with this, Spring Data REST integrates two technologies: versioning of resources and ETags.
By versioning resources on the backend and using ETags in the frontend, it is possible to conditially PUT a change. In other words, you can detect if a resource has changed and prevent a PUT (or a PATCH) from stomping on someone else’s update. Let’s check it out.
Versioning REST resources
To support versioning of resources, define a version attribute for your domain objects that need this type of protection.
The version field is annotated with
javax.persistence.Version. It causes a value to be automatically stored and updated everytime a row is inserted and updated.
When fetching an individual resource (not a collection resource), Spring Data REST will automatically add an ETag response header with the value of this field.
Fetching individual resources and their headers
In the previous section you used the collection resource to gather data and populate the UI’s HTML table. With Spring Data REST, the _embedded data set is considered a preview of data. While useful for glancing at data, to get headers like ETags, you need to fetch each resource individually.
In this version,
loadFromServer is updated to fetch the collection and then use the URIs to retrieve each individual resource.
follow()function goes to the employees collection resource.
then(employeeCollection ⇒ …)clause creates a call to fetch JSON Schema data. This has a sub-then clause to store the metadata and navigational links in the
Notice that this embedded promise returns the employeeCollection. That way, the collection can be passed onto the next call while letting you grab the metadata along the way.
then(employeeCollection ⇒ …)clause converts the collection of employees into an array of GET promises to fetch each individual resource. This is what you need to fetch an ETag header for each employee.
then(employeePromises ⇒ …)clause takes the array of GET promises and merges them into a single promise with
when.all(), resolved when all the GET promises are resolved.
loadFromServerwraps up with
done(employees ⇒ …)where the UI state is updated using this amalgamation of data.
This chain is implemented in other places as well. For example,
onNavigate(), which is used to jump to different pages, has been updated to fetch individual resources. Since it’s mostly the same as what’s shown above, it’s been left out of this section.
Updating existing resources
In this section, you are adding an
UpdateDialog React component to edit existing employee records.
This new component has both a
handleSubmit() function as well as the expected
render() function, similar to the
<CreateDialog /> component.
Let’s dig into these functions in reverse order, and first look at the
This component uses the same CSS/HTML tactics to show and hide the dialog as the
<CreateDialog /> from the previous section.
It converts the array of JSON Schema attributes into an array of HTML inputs, wrapped in paragraph elements for styling. This is also the same as the
<CreateDialog /> with one difference: the fields are loaded with this.props.employee. In the CreateDialog component, the fields are empty.
The id field is built differently. There is only one CreateDialog link on the entire UI, but a separate UpdateDialog link for every row displayed. Hence, the id field is based on the self link’s URI. This is used in both the <div> element’s React key as well as the HTML anchor tag and the hidden pop-up.
Handling user input
The submit button is linked to the component’s
handleSubmit() function. This handily uses
React.findDOMNode() to extract the details of the pop-up using React refs.
After the input values are extracted and loaded into the
updatedEmployee object, the top-level
onUpdate() method is invoked. This continues React’s style of one-way binding where the functions to call are pushed from upper level components into the lower level ones. This way, state is still managed at the top.
So you’ve gone to all this effort to embed versioning in the data model. Spring Data REST has served up that value as an ETag response header. Here is where you get to put it to good use!
PUT with an If-Match request header causes Spring Data REST to check the value against the current version. If the incoming If-Match value doesn’t match the data store’s version value, Spring Data REST will fail with an HTTP 412 Precondition Failed.
The spec for Promises/A+ actually defines their API as
Putting it all together
UpdateDialog React component defined and nicely linked to the top-level
onUpdate function, the last step is to wire it into the existing layout of components.
CreateDialog created in the previous section was put at the top of the
EmployeeList because there is only one instance. However,
UpdateDialog is tied directly to specific employees. So you can see it plugged in below in the
Employee React component:
In this section, you switch from using the collection resource to individual resources. The fields for an employee record are now found at
this.props.employee.entity. It gives us access to
this.props.employee.headers where we can find ETags.
There are other headers supported by Spring Data REST (like Last-Modified) which aren’t part of this series. So structuring your data this way is handy.
The structure of
Seeing things in action
Start up the app (
Open up a tab and navigate to http://localhost:8080.
Pull up the edit dialog for Frodo.
Open another tab in your browser and pull up the same record.
Make a change to the record in the first tab.
Try to make a change in the second tab.
With these mods, you have increased data integrity by avoiding collisions.
In this section:
You configured your domain model with an
@Versionfield for JPA-based optimistic locking.
You adjusted the frontend to fetch individual resources.
You plugged the ETag header from an individual resource into an If-Match request header to make PUTs conditional.
You coded a new UpdateDialog for each employee shown on the list.
With this plugged in, it’s easy to avoid colliding with other users, or simply overwriting their edits.
It’s certainly nice to know when you’re editing a bad record. But is it best to wait until you click "Submit" to find out?
The logic to fetch resources is very similar in both
onNavigate. Do you see ways to avoid duplicate code?
You put the JSON Schema metadata to good use in building up the
CreateDialog and the
UpdateDialog inputs. Do you see other places to use the metadata to makes things more generic? Imagine you wanted to add five more fields to
Employee.java. What would it take to update the UI?