Search code examples
javascripttypescriptmeteorasync-await

Meteor.publish with call to an async function returning error


I am trying to create a wrapper method for Meteor.publish that does an access check before actually calling it.

The access check is represented by an async-await method, which leads to the following error in my wrapper function when running it, if I convert my wrapper method to an async one.

Exception from sub alerts.notAcknowledged id 2 Error: Publish function can only return a Cursor or an array of Cursors at Subscription._publishHandlerResult (packages/ddp-server/livedata_server.js:1132:18)

If I remove the async keyword from the wrapper method and comment out the call to the async-await method, the wrapper method is working as expected.


Solution

  • I did not find any answer to solve my issue, but after checking several solutions and trying out, I got to the following solution:

    export const wrapperPublish = (metadata: any, callback: Function) => {
         Meteor.publish(metadata.name, (params: LooseObject) => {
    
            const allowAccessSync = Meteor.wrapAsync(allowAccess);
            const { error, hasAccess } = MeteorPromise.await(allowAccessSync({
                                         token: params.token,
                                         methodName: params.methodName,
                                         }, () => {}));
            check(params, metadata.checks);
            if (!hasAccess) {
                // do something 
            }
    
            return callback(params);
        });
    };
    

    In the code snippet above, the allowAccess represents the function returning a Promise and the solution was the Meteor.wrapAsync that transforms an async function into a convenient synchronous-looking function. https://docs.meteor.com/api/core.html#Meteor-wrapAsync