queryBus.executeSync¶
The executeSync
method allows to execute a query synchronously.
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 any
which is a query handler return type if such handler exists. This will be shown in the examples below.
Example¶
To executeSync a query of the Query Bus you can use the executeSync
method:
useStorefront(async (storefront) => {
storefront.queryBus.executeSync({
name: 'my-query',
type: 'query',
body: 'query body'
});
});
Your body can contain any data type you need:
useStorefront(async (storefront) => {
storefront.commandBus.executeSync({
name: 'my-body',
type: 'body',
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 synchronously 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);
const bodyLength = storefront.queryBus.executeSync({
name: 'get-body-length',
type: 'query',
body: 'query body'
});
console.log('body length:', bodyLength);
});