I am trying to dynamically create handlers for a set of specific urls that come from wordpress. The requirement comes from the need to have a set of top level slugs for a CPT.
To do this I call an endpoint and get a list of the slugs, then the idea is to add a handler (or multiple handlers) to catch these and serve the correct page.
I hit an issue when I try to run any async code before I add the handler in the index file, for example:
const before = async ({ libraries, actions }) => {
libraries.source.handlers.push(menuHandler);
libraries.source.handlers.push(officeHandler);
const slugs = await getOfficeNames(libraries, actions);
libraries.source.handlers.push(officePageHandler(libraries, actions,"/slug"));
await actions.source.fetch("primaryMenu");
await actions.source.fetch("offices");
};
This function is called in both Both beforeSSR and beforeCSR:
beforeSSR: async ({ libraries, actions }) => {
await before({ libraries, actions });
},
beforeCSR: async ({ libraries, actions }) => {
await before({ libraries, actions });
},
The getOfficeNames function currently does nothing for testing (it will get the list of slugs):
async function getOfficeNames(libraries, actions) {
// const requestUrl = "/wp/v2/office?per_page=100&parent=0&page=";
const x = new Promise((resolveInner) => {
setTimeout(resolveInner, 1000);
});
const y = await x;
return "TEST";
When I run it in this configuration it doesnt work navigating to /slug. However in this configuration:
const before = async ({ libraries, actions }) => {
libraries.source.handlers.push(menuHandler);
libraries.source.handlers.push(officeHandler);
libraries.source.handlers.push(officePageHandler(libraries, actions,"/slug"));
const slugs = await getOfficeNames(libraries, actions);
await actions.source.fetch("primaryMenu");
await actions.source.fetch("offices");
};
it works.
Does any one know why running something async before adding to the handlers cause it to break? I have checked the handler list and it seems to have added the handler correctly, it just doesnt get called.
{
name: 'Office Pages TEST',
priority: 10,
pattern: 'RegExp:(/slug/)',
func: [AsyncFunction: func]
}