- JavaScript Cloud Native Development Cookbook
- John Gilbert
- 350字
- 2021-07-16 18:03:31
How it works...
In this recipe, we are implementing an offline-first solution where the ReactJS client application stores all changes in local storage and then synchronizes the data to a Cognito dataset in the cloud when connectivity is available. This scenario is very common in mobile applications where the mobile application may not always be connected. An AWS Cognito dataset is associated with a specific user in an AWS Identity Pool. In this recipe, the identity pool supports unauthenticated users. Anonymous access is another common characteristic of mobile applications.
The bare bones ReactJS application is implemented in the ./index.html file. It contains a form for the user to enter data. The Save button saves the form's data to local storage via the Cognito SDK. The Synchronize button uses the SDK to send the local data to the cloud. In a typical application, this synchronization would be triggered behind the scenes by events in the normal flow of the application, such as on save, on load, and before exit. In the Creating a materialized view in a Cognito Dataset recipe, we show how synchronizing will also retrieve data from the cloud.
Cognito's change data capture feature is implemented via AWS Kinesis. Therefore, we create a Kinesis stream called CognitoStream that is dedicated to our Cognito datasets. The trigger function is a stream processor that is consuming sync records from this stream. The stream processor's recordToSync step extracts the domain object from each sync record, where it is stored as a JSON string. The toEvent step wraps the domain object in the standard event format, as discussed in the Creating an event stream and publishing an event recipe in Chapter 1, Getting Started with Cloud-Native. Finally, the event is written to the stream specified by the STREAM_NAME environment variable. Note that the trigger function is similar to the event-first variant. It just needs to execute quickly and leave as little to chance as possible. We write the event to a single resource, the highly available, fully managed cloud-native event stream, and trust that the downstream services will eventually consume the event.