loopback icon indicating copy to clipboard operation
loopback copied to clipboard

POST with array of objects in payload

Open JyotiRani opened this issue 9 years ago • 11 comments

I have a requirement to set an autogenerated field to the incoming payload of POST request. I have defined 'before save' operation hook in my loopback application which does this. However for payload with single object, it works as expected, but if i have array of objects in payload, then the autogenerated field is set same for all objects in the array while i want different value to be saved for all objects. So i am wondering what is the best place/hook to modify each object in array uniquely.

Note: the autogenerated field is fetched from db, and is incremented after every fetch, so next object in array should use the incremented value and so on.

JyotiRani avatar Aug 01 '17 11:08 JyotiRani

@JyotiRani, to help accelerating the triaging, do you have a sample app? thanks.

dhmlau avatar Aug 01 '17 15:08 dhmlau

@JyotiRani You are correct in using the before save hook to do your manipulation. You can use a tool like lodash to iterate through the array and use the .extend() function on the objects to add your autogenerated field before saving. Here is an example app I created (I just used variable instead of the autogenerated field). The main file is under server/boot/script.js. I am going to close this ticket, but feel free to re-open if you are still experiencing issues.

b-admike avatar Aug 02 '17 20:08 b-admike

Example POST request and result:

{
  "contacts": [
    {"name": "Bob"},
    {"name": "Sarah"}
  ]
}

is saved as:

{
  "contacts": [
    {
      "name": "Bob",
      "counter": 1
    },
    {
      "name": "Sarah",
      "counter": 2
    }
  ],
  "id": 1
}

b-admike avatar Aug 02 '17 20:08 b-admike

@b-admike Your example work as expected, however i realized that the issue is with async call, my autogenerated number is result of db aync call response, so there, looks like aync call is initiated parallely for all object instances in array, so before the values gets updated to a new one in db, next object also requests for it and gets the old value. Can you try this at your end?

JyotiRani avatar Aug 03 '17 10:08 JyotiRani

Thank you @JyotiRani. Can you show me the SQL you use for the autogenerated field and which connector you are using? Also, which async call/method are you using?

b-admike avatar Aug 03 '17 11:08 b-admike

Its the dash db connector. Here is the snippet of the method: var query = {where: {and:[{companyId:data.1},{itemType:'TASK'}]}}; Tasks.app.models.numgenerator.findOne(query, function(err, res){ if (err) return next(err);

	nextGenNum = res.itemPrefix + leftPad(res.nextSeqNumber, res.sizeRequired - res.itemPrefix.length, '0');
	console.log(nextGenNum);
	if(iType == 'TASK') {
		data.taskCode = nextGenNum;
		console.log('setting task code as:' + data.taskCode);							
	}
	});

Schema for number generator table is: CREATE TABLE TASK_NUMGENERATOR ( "NUMBER_ID" INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1, CACHE 20), "ITEMTYPE" VARCHAR(50) , "ITEM_PREFIX" VARCHAR(10) , "COMPANYID" INTEGER , "NEXT_SEQ_NUMBER" INTEGER , "SIZE_REQUIRED" INTEGER , "CREATEDDATE" TIMESTAMP , "MODIFIEDDATE" TIMESTAMP, CONSTRAINT PK_NUMGEN_ID PRIMARY KEY (NUMBER_ID) );

JyotiRani avatar Aug 03 '17 11:08 JyotiRani

Here is complete function which fetches and then updates the field in db:

function fetchGenNumberAndProceed(data, next, iType) { var query = {}; if(data.companyId) query = {where: {and:[{companyId:data.companyId},{itemType:iType}]}}; else query = {where: {and:[{companyId:null},{itemType:iType}]}};

var nextGenNum;
Tasks.app.models.numgenerator.findOne(query, function(err, res){
	if (err) return next(err);
	
	nextGenNum = res.itemPrefix + leftPad(res.nextSeqNumber, res.sizeRequired - res.itemPrefix.length, '0');
	console.log(nextGenNum);
	if(iType == 'TASK') {
		data.taskCode = nextGenNum;
		console.log('setting task code as:' + data.taskCode);							
	} else {
		data.workItemId = nextGenNum;
		console.log('setting workitemId as:' + data.workItemId + nextGenNum);	
	}
	if(data.companyId)
		query = {"companyId":data.companyId, "itemType":iType};
	else
		query = {"companyId":null, "itemType":iType};

	Tasks.app.models.numgenerator.updateAll(query, {"nextSeqNumber": res.nextSeqNumber + 1}, function(err, updated) {
		if (err) return next(err);
		else {
			console.log("updated sequence number:" + updated.count);													
		}
	});
});	

}

JyotiRani avatar Aug 03 '17 12:08 JyotiRani

@b-admike any further inputs on this?

JyotiRani avatar Aug 09 '17 10:08 JyotiRani

Any update on this?

JyotiRani avatar Aug 23 '17 09:08 JyotiRani

Sorry for the late reply @JyotiRani. Could you provide a sample app to help reproduce your issue?

b-admike avatar Aug 23 '17 11:08 b-admike

@JyotiRani Looking at the function you posted, I think it is ok, but in order for me to get the full picture I'd need you to provide a sample app which can reproduce the issue. I am going to close this issue, but feel free to re-open once you have it ready. Thank you.

b-admike avatar Sep 11 '17 12:09 b-admike