How to manipulate data on the fly with server side scripts


#1

Hi, I am new to Dreamfactory. I am trying to modify a field on all of the records of a REST call using get.post_process event script. I am struggling to get my head around it a little. I have manipulated some examples I have found online but my attempts don’t seem to be the correct method.

Here is an example of what I have tried.

 if (event.request.body) {
_.each(event.request.body, function (record) {
    record.name = 'New Name Here';
});
} 

If anybody could give me any assistance or lead me in the right direction I would be very appreciative.

Thank you.


#2

Try this

 if (event.request.body.record) {
_.each(event.request.body.record, function (record) {
    record.name = 'New Name Here';
});
}

#3

Also have a few examples on the wiki.

https://github.com/dreamfactorysoftware/dsp-core/wiki/Server-Side-Scripting


#4

Thanks for the help. Unfortunately this still doesn’t seem to be working for me. Could it be a conflict with the fact my data is a mySQL database which I am accessing from another remote server? I can get custom scripts to work but not the event scripts. I don’t see any effect on the data from API docs nor test_rest.html.

I am using a custom script to access ‘eventmaster’ table and only display future items (no items who’s ‘startdate’ is 48 hours older than current date).

function getDate()
{
var dNow = new Date();
var theDate = (dNow.getTime()/1000);
return parseInt(theDate);
}
function initialise()
{
var queryString = getDate()+172800;
var filter_data = {"filter": "startdate>'" +queryString+ "'"};
var request = platform.api.get("buzzn/eventmaster",filter_data);
return request;
}
result = initialise();
return result;

Is there some way I can maybe do the manipulation as a part of this custom script instead?


#5

When I create an error with a script it does affect my call so it seems the script is being called on the event yet when I use the below script the ‘name’ field’s data remains unchanged. What could be the reason for this?

if (event.request.body.record) {
_.each(event.request.body.record, function (record) {
record.name = 'New Name Here';
});
}

#6

The correct script for this to work was…

if (event.response.record) {
_.each(event.response.record, function (record, index, list) {
record.name = 'New Name Here';
});
}

#7

If you want to change the value in the database, it needs to be done in the pre_process script like Ben’s example. If you just want to change the value returned to the client but not the value in the db then do it in the post_process script like you showed.


#8

Ok, thank you. Perhaps I should have been more specific in my initial question. I dumbed the script down a little. What I really intended to do was pass a description value off to another JS function to turn URLs in to clickable hyperlinks and then change the description to this new modified text on the fly without changing the database. All is working great now.