How can I access the newly published message in beforePublish?
How can I for example create an entity in PersistanceService from Messaging.beforePublish in Javascript backend? This is what I have got so far from the generated code:
Backendless.ServerCode.Messaging.beforePublish('*', function(req) {
//add your code here
var chatObject = new ChatMessage( {
text: "", // how do I get it?
userId: "",
conversationId: "",
});
var savedContact = Backendless.Persistence.of( Contact ).save( chatObject );
});
I’m looking at this in Java documentation
public void beforePublish( RunnerContext context, Object message, PublishOptions publishOptions, DeliveryOptions deliveryOptions ) throws Exception
I didn’t find anything similar in JS docs. How to get the message data so I can create a ChatMessage object?
Is there a way I can easily figure these things out myself somehow if you don’t have time to write the docs? I feel like the documentation is incomplete in this respect, not mentioning the general lack of example code.
You have removed the jsdoc annotation from generated code, explaining handler arguments.
This is how the ‘beforePublish’ generated stub looks like :
/* global Backendless */
/**
* @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 {Object} req.message
* @param {Object} req.publishOptions
* @param {Object} req.deliveryOptions
*
* @returns {Object|Promise.<Object>|void} By returning a value you can stop further event propagation and return
* a specific result to the caller
*/
Backendless.ServerCode.Messaging.beforePublish('*', function(req) {
//add your code here
});
As you can see from the jsdoc, the data you are interested in, can be accessed as:
req.message
req.publishOptions
req.deliveryOptions
Same fields set as in Java doc
FYI, you can use ‘debug’ mode just for resolving such questions by yourself :
add ‘console.log(req);’ as the first line of the beforePublish event handler,
run coderunner in debug mode (‘npm run debug’),
publish some message from your client
see the content of the ‘req’ argument printed in console
Also it’s possible to attach some IDE debugger and debug your code step by step validating your variables values.
See more information here
my bad:) Thanks for throughout explanation!