Why do I get errors when I try to create patients from a service worker using background sync

I’ve been building an OWA that will make it possible to do patient registration and other form submissions offline. Here is the repository for the app

Currently the app is able to serve static resources while offline and responses to GET requests are cached and these are accessed when the app goes offline so patient searches still work offline. See the demo below

Now what I’ve been struggling to implement is creating patients offline. My logic is

  1. When creating a patient, check if connection is available
  2. If connection is available, make a normal POST
  3. If connections is not available, save request in indexedDB and register a one-off sync
  4. When connection is regained, from service worker make a POST to create the patient

Now step 1 to 3 works fine. In step 4, when connection is regained, the service worker attempts to create a patient with the data from the queue but fails with this error.

At first I thought my data was not valid but when doing a normal POST(that is when server is reachable) with the same json data, it works fine. So I’m not sure as to whether there is something in OpenMRS that prevents POST from service workers.

Below is the code where I attempt to save a patient from my app

In the above code, I attempt to save a patient. If client is offline, the request will be saved in indexedDB and register a one off sync. I used localforage library since it has an elegant API to work with indexedDB.

Now when the sync event is called(when connection is regained) the code below attempts to execute all saved requests but fail

When you resume from offline to online, how does your post data look like?

        "person":  {
            "names": [{
                "givenName": "John",
            "addresses": [{
         "identifiers": [{

Sorry if it’s not looking clean. That is from the console.

I edited to make more readable.

Can you try to always authenticate when you get online before posting?

I will research on how to do that. But I think I’m still authenticated when this background sync is called because to have the service worker fire the sync event in chrome, what I do is just disconnect from the network and reconnect. Note this does not log me out as my server is actually running on localhost.

Can you try to authenticate again as mentioned here under the Authentication section? https://wiki.openmrs.org/display/docs/REST+Web+Services+API+For+Clients

Daniel is right it fails because you are not authorized. Somewhere in the logs there is the line Caused by: org.openmrs.api.APIAuthenticationException: Privileges required: Get Identifier Types .

@ivange94 it seems you are logged out once the connection is re-established. Or is it that you don’t have privilege to view the identifier types?

Thanks for spotting this.

I will try that and let you know how it goes. Thanks.