Support Topics Documentation Slack YouTube Blog

Custom Business Logic on Record Create


(Alan Oakden) #21

I did it via an API call. Via a fetch method in my app


(Vladimir Upirov) #22

is the event-handler deployed and enabled?

And does a new record appear in the Notifications table (in Data Browser) after request from your app?


(Alan Oakden) #23

Hmm, i can’t actually deplopy anything. Even if i just try to save and deploy:

Backendless.ServerCode.Persistence.afterCreate('Notifications', function(req, res) {


  
  
}, true);

It says there is an error in my code and i need to check it.


(Vladimir Upirov) #24

what’s your appId, I will check this out


(Alan Oakden) #25

My app ID is F50E3483-D88B-FA83-FFB6-D2EDC95A9500


(Vladimir Upirov) #26

it has been deployed without any changes


(Alan Oakden) #27

Thanks, how can i deploy this going forward, its like it stops me bug checking by saying there is a bug…?


(Vladimir Upirov) #28

there is a syntax mistake, just add commas in the end of the properties
Coding%20-%20BL%20-%20LHApp%20-%20Backendless%20%F0%9F%94%8A%202018-09-17%2017-40-00


(Alan Oakden) #29

Where are you reading that code?


(Vladimir Upirov) #30

in Coding section


(Alan Oakden) #31

Ah sorry, that probably needs to be deleted. I am working on the after create for notificiations.

Looks like save and deploy is now working, now that i have deleted that file!

Perhaps something to note in future, as its not obvious from the Event handlers view


(Alan Oakden) #32

OK

Thanks for your help so far.

What i am trying to understand now is…i have the following code:

 /**
* @param {Object} req The request object contains information about the request
* @param {Object} req.context The execution context contains an information about application, current user and event
* @param {Notifications} req.item An item to create
*
* @param {Object} res The response object
* @param {Notifications} res.result Created item
* @param {Object} res.error
*/
Backendless.ServerCode.Persistence.afterCreate('Notifications', function(req, res) {

 //add your code here
  
    Backendless.Logging.setLogReportingPolicy( 1, 1 );
    var logger = Backendless.Logging.getLogger( "MyLogger");
    logger.info( "informational log message" ); 
  
  var notificationQueryBuilder = Backendless.DataQueryBuilder.create();
  
  
 
 // set query builder properties
// queryBuilder.setXXXX
  notificationQueryBuilder.setProperties("description", "userLink");
  notificationQueryBuilder.setWhereClause(`userLink.organisationCode = 'e8xqdl'`);

 
Backendless.Data.of( "Notifications" ).find()
 .then( function( objectArray ) {
logger.info("queryBuilderObjectIs")
  })
 .catch( function( error ) {
 }); 
  
  
}, true);

Why is logger.info( “informational log message” ); going to the logging, but not logger.info(“queryBuilderObjectIs”) ??


(Vladimir Upirov) #33

you should add a “return” before Backendless.Data.of( “Notifications” ).find() or add “async” “await” keywords

Backendless.ServerCode.Persistence.afterCreate('Notifications', async function(req, res) {
   ....

   await Backendless.Data.of( "Notifications" ).find() 
     .then ...

}

it’s because the CodeRunner’s process is finished before Backendless.Data.of( “Notifications” ).find() is resolved, and your logger.info(“queryBuilderObjectIs”) is never processed


(Alan Oakden) #34

How do i do a POST fetch request in the business logic?

All of my code was working until i added the fetch request

 /**
* @param {Object} req The request object contains information about the request
* @param {Object} req.context The execution context contains an information about application, current user and event
* @param {Notifications} req.item An item to create
*
* @param {Object} res The response object
* @param {Notifications} res.result Created item
* @param {Object} res.error
*/
Backendless.ServerCode.Persistence.afterCreate('Notifications', function(req, res) {

 //add your code here
  
    Backendless.Logging.setLogReportingPolicy( 1, 1 );
    var logger = Backendless.Logging.getLogger( "NotificationsLogger");
    logger.info(JSON.stringify(req));
    
    logger.info(JSON.stringify("ownerId!='" + req.item.ownerId + "' AND organisationCode='" + req.item.organisationCode + "'"));
    
  //create a query builder
  var userQueryBuilder = Backendless.DataQueryBuilder.create();

 // set query builder properties
  userQueryBuilder.setProperties(["organisationCode","deviceToken"]);
  userQueryBuilder.setWhereClause("ownerId!='" + req.item.ownerId + "' AND organisationCode='" + req.item.organisationCode + "'");
  
  var expoSend = []

 //get users based on criteria
return Backendless.Data.of( "Users" ).find(userQueryBuilder)
 .then( function( objectArray ) {
    
   // build the array that is sent to the expo push service 
    for(var i=0; i<objectArray.length; i++)  {
    expoSend.push({to: objectArray[i].deviceToken, body: req.item.userName});
    
    logger.info(JSON.stringify(expoSend))
    }
    
     fetch('https://exp.host/--/api/v2/push/send', {
                  method: "POST", // or 'PUT'
                  body: JSON.stringify(expoSend), // data can be `string` or {object}!
                  headers: {
                    "Content-Type": "application/json"
                  }
                })
                  .then(res => 
                  { res.json()
                    logger.info("Link-----response", res);
                  })
                  .catch(error => console.error("Error:", error))   })   
                })

  })
 .catch( function( error ) {
   logger.info(error)
 }); 
 
  
}, true);

(Vladimir Upirov) #35

“fetch” doesn’t work in NodeJS env, instead you can use our Backendless.Request https://github.com/Backendless/Request

Backendless.Request.post('https://exp.host/--/api/v2/push/send', expoSend).then(...).catch(...)

and don’t forget to return the request promise in your promises chain

return Backendless.Data.of( "Users" ).find(userQueryBuilder)
 .then( function( objectArray ) {
    ...
     return Backendless.Request.post('https://exp.host/--/api/v2/push/send', expoSend).then(...).catch(...)

     ....