Hi all,
I’m trying to create build patients via REST and javascript.I have read https://wiki.openmrs.org/display/docs/Create+Patient and according to the docs to create a patient I first have to create a person and use the uuid of the created person to create a patient. That was easy when saving creating one patient. Now I want to create a bulk of patients in an array. My javascript code looks something like this
var patients = [] // array of patient objects to be created
// I defined my patient object to be something like
/*
patient = {
address: {
address1: "Town one",
address2: "Town two",
},
identifiers: [
{
identifier: "123",
identifierType: "uuid",
location: "Unknown",
preferred: true
}
],
person: {
birthdate: "2017-06-11",
gender: "M",
names: [
{
familyName: "Doe",
givenName: "John"
}
]
}
}
*/
var post = function(theUrl, theData, callback) {
$.ajax({
type: "POST",
url: theUrl,
data: theData,
success: callback,
contentType: "application/json"
});
}
var createPatient = function(patient) {
// patient created
}
var saveAddress = function(address) {
// address saved
}
var createPerson = function(person) {
// use person uuid to add address and create patient
// get address stored inside localStorage
var address = localStorage.getItem('address');
post("/openmrs/ws/rest/v1/person/" + person.uuid, address, saveAddress);
// get identifiers stored in localStorage and construct patient json data for post
var identifiers = localStorage.getItem();
var patient = {};
patient.person = person.uuid;
patient.identifiers = JSON.parse();
post("/openmrs/ws/rest/v1/patient", JSON.stringify(patient), createPatient);
}
// save all patients in array
for (var i = 0;i < patients.length;i++) {
var person = patients[i].person;
localStorage.setItem('identifiers', patients[i].identifiers); // will need it later inside createPerson() but not sure how to pass it as a parameter to it since it's a call back function for a post event
localStorage.setItem('address', patients[i].address); // same reason as above
post("/openmrs/ws/rest/v1/person", JSON.stringify(person), createPerson);
}
When I first wrote this code, my assumption was that for every value of i, I will have the following function calls
post -> createPerson -> saveAddress -> createPatient
But instead for each value of i only the first post is called and the call backs are only called after the loop has finished executing, for example if I have 3 patients in my array, I will have the following call backs
post -> post -> post ->createPerson…
Due to this error, the code correctly creates the person objects but only creates a patient for the first one. I’m fairly new to javascript and will appreciate all the help I can get to solve this.