Skip to content
This repository has been archived by the owner on Jun 7, 2024. It is now read-only.

Latest commit

 

History

History

conditional

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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 without 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 but with extra features added.

To PUT or Not to PUT? That is the Question.

When you fetch a resource, the 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 conditionally PUT a change. In other words, you can detect whether a resource has changed and prevent a PUT (or a PATCH) from stomping on someone else’s update.

Versioning REST Resources

To support versioning of resources, define a version attribute for your domain objects that need this type of protection. The following listing shows how to do so for the Employee object:

Example 1. src/main/java/com/greglturnquist/payroll/Employee.java
link:src/main/java/com/greglturnquist/payroll/Employee.java[role=include]
  • The version field is annotated with javax.persistence.Version. It causes a value to be automatically stored and updated every time a row is inserted and updated.

When fetching an individual resource (not a collection resource), Spring Data REST automatically adds 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. Then you can use the URIs to retrieve each individual resource:

Example 2. src/main/js/app.js - Fetching each resource
link:src/main/js/app.js[role=include]
  1. The follow() function goes to the employees collection resource.

  2. The first then(employeeCollection ⇒ …​) clause creates a call to fetch JSON Schema data. This has an inner then clause to store the metadata and navigational links in the <App/> component.

    Notice that this embedded promise returns the employeeCollection. That way, the collection can be passed onto the next call, letting you grab the metadata along the way.

  3. The second 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.

  4. The then(employeePromises ⇒ …​) clause takes the array of GET promises and merges them into a single promise with when.all(), which is resolved when all the GET promises are resolved.

  5. loadFromServer wraps 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 is mostly the same as what is shown here, it has been left out of this section.

Updating Existing Resources

In this section, you are adding an UpdateDialog React component to edit existing employee records:

Example 3. src/main/js/app.js - UpdateDialog component
link:src/main/js/app.js[role=include]

This new component has both a handleSubmit() function and the expected render() function, similar to the <CreateDialog /> component.

We dig into these functions in reverse order and first look at the render() function.

Rendering

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 the <div> element’s React key, 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 by 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.

Conditional PUT

So you have 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:

Example 4. src/main/js/app.js - onUpdate function
link:src/main/js/app.js[role=include]

A 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 does not match the data store’s version value, Spring Data REST will fail with an HTTP 412 Precondition Failed.

Note
The specification for Promises/A+ actually defines their API as then(successFunction, errorFunction). So far, you have seen it used only with success functions. In the preceding code fragment, there are two functions. The success function invokes loadFromServer, while the error function displays a browser alert about the stale data.

Putting It All Together

With your 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.

The 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:

Example 5. src/main/js/app.js - Employee with UpdateDialog
link:src/main/js/app.js[role=include]

In this section, you switch from using the collection resource to using 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 (such as Last-Modified) that are not part of this series. So structuring your data this way is handy.

Important
The structure of .entity and .headers is only pertinent when using rest.js as the REST library of choice. If you use a different library, you will have to adapt as necessary.

Seeing Things in Action

To see the modified application work:

  1. Start the application by running ./mvnw spring-boot:run.

  2. Open a browser tab and navigate to http:https://localhost:8080.

    You should see a page similar to the following image:

    conditional 1
  3. Pull up the edit dialog for Frodo.

  4. Open another tab in your browser and pull up the same record.

  5. Make a change to the record in the first tab.

  6. Try to make a change in the second tab.

    You should see the browser tabs change, as the following images show

    conditional 2
conditional 3

With these modifications, you have increased data integrity by avoiding collisions.

Review

In this section:

  • You configured your domain model with a @Version field 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, itis easy to avoid colliding with other users or overwriting their edits.

Issues?

It is certainly nice to know when you are 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 loadFromServer and 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?