Skip to content

queryBus.execute

The execute method allows to execute a query asynchronously.

Input parameters

query

query is a mandatory parameter of the BaseMessage type which represents the query to be executed.

type of the Query Bus messages should always be query

options (optional)

options is a mandatory parameter of the TMessageExecutionOptions type which represents the additional options of a query.

Returned value

A returned value has a type of Promise<any> which fulfills when the query executes and returns a type of a query handler return type if it exists. This will be shown in the examples below.

Example

To execute a query of the Query Bus you can use the execute method:

useStorefront(async (storefront) => {
    storefront.queryBus.execute({
        name: 'my-query',
        type: 'query',
        body: 'query body'
    });
});

Your body can contain any data type you need:

useStorefront(async (storefront) => {
    storefront.queryBus.execute({
        name: 'my-query',
        type: 'query',
        body: [
            {
                name: 'example1',
                values: [1, 2, 3]
            },
            {
                name: 'example2',
                values: [10, 20, 30]
            }
        ]
    });
});

Example

In this example we execute a query of the Query Bus asynchronously and listen to it:

useStorefront(async (storefront) => {
    function getBodyLength(query) {
        // whenever this query executes return the length of a body
        return typeof query.body === 'string' ? query.body.length : 0;
    }

    storefront.queryBus.on('get-body-length', getBodyLength);

    storefront.queryBus.execute({
        name: 'get-body-length',
        type: 'query',
        body: 'query body'
    }).then((bodyLength) => {
        console.log('body length:', bodyLength);
    });
});

Methods reference