javascriptmeteorclient-sidemeteor-methods

Running code before and after each Method call in Meteor


I´m running several method calls that need to show the end user a loading modal and hide it when the method resturns a result. I was looking for a way to run this pre-call code and post-call code for every method without repeating code.

swal({
  title: "Saving...",
  onBeforeOpen: () => swal.showLoading()
});
Meteor.call("method", {/*params*/}, (err, res) => {
 //Do something
 swal.hide();
});

I want to be able to run those 2 swal codes without writing that code in each call. Is there some way to configure Meteor.call to do something before and after the call to the method?


Solution

  • You could abstract the code into a wrapper function that accepts your method name, parameters and callback function as arguments:

    const call = ({ title, name, params, callback }) => {
     swal({
      title: title,
      onBeforeOpen: () => swal.showLoading()
     });
     Meteor.call(name, params, (err, res) => {
       callback(err, res);
       swal.hide();
     });
    }
    

    Note here, that callback is not the "real" callback but just put inside the statements and receives the arguments from the "real" callback itself as arguments.

    Use the method for example like so:

    call({ 
      title: 'Saving...', 
      name: 'method', 
      params: {/*params*/}, 
      callback: (err, res) => {
        console.log('I am executed before hide');
      }
    });
    

    If you need this function a lot you can put it in an own file and use export to make it available to other files/modules.