I want to write a server side script that will execute on its own after i insert a record into the table. I am having trouble understanding how the scripts are actually used in dreamfactory so i need some friendly aid to tell me how i would implement such a script… below is some pseudo code:
for (each record in table){
if(record.field1 == record_i_just_insterted.field1
&& record.field2 == record_i_just_insterted.field2){
record.field3 =record.field3 - 0.1;
}
}
How would i write this to happen every time i insert a record into that table? do i have to wait until we can do stored procedures or can this be done now with the scripts tab… i am not a JS guy, so if someone could rewrite this for me, i’d buy them a virtual beer.
Hey Erik, you can implement this logic. We’ll post a code snippet soon.
Here is a sample that will work in 1.6 which is coming out this week.
print("\n***Enter db.pizzashops.post.pre_process***\n");
if (event.request.body.record) {
// loop through each record in request, might be just one
_.each(event.request.body.record, function (record) {
print("\nUpdating records with lat = " + record.lat + " and lon = " + record.lon + "\n");
updateRecords(record.lat, record.lon);
});
}
function updateRecords(lat, lon) {
var results = platform.api.get("db/pizzashops", { "fields": "id,lat,lon,scale", "filter": "lat=" + lat + " and lon=" + lon});
print("\n" + results.record.length + " matching records found\n");
var_dump(results.record);
if (results.record.length > 0) {
// loop through each matching record and update scale
_.each(results.record, function (record) {
record.scale -= 0.1;
});
// write back updated records to db
var putResult = platform.api.put("db/pizzashops", {"record": results.record});
var_dump(putResult);
}
}
print("\n***Exit db.pizzashops.post.pre_process***\n");