Access the routes object inside the routes function

thisischrisj
0
thisischrisj
commented 3 months ago

The filter function passes the routes object to the function call. Is it possible to access that same object from within the routes function call?

We have nuxt.js frontend that pulls data from a WordPress backend. To generate the sitemap we are pulling all the permalink structures from Wordpress inside the routes function:

...
  routes () {
    var endpoint = 'https://xxxx.yyyy/permalinks';
    return axios.get(endpoint)
    .then(res => res.data.map(page => page.permalink))
    .catch((err) => {  });
  }
...

The problem is that the permalinks we get back from WordPress are not necessarily aligned 1-to-1 with the nuxt routes. The ones that aren't can be removed as they are not needed.

What we'd like to do is get all the data from the endpoint and test each page.permalink against the structure of the nuxt routes. If the permalink matches a valid route then include it, otherwise, omit it.

So, imagine we have the following route structures:

blog/:id
news/:id

And the call to the endpoint returns:

[
    { permalink: 'blog/123' },
    { permalink: 'news/123' },
    { permalink: 'case-studies/123' }
}

We want to filter the endpoint results so that 'case-studies/123' is omitted from the sitemap because it is not a valid route.

0
NicoPennec
1.4k
NicoPennec
commented 3 months ago

why not reverse the solution?

That is to say, don't inject your permalinks in the routes() {...} declaration, but directly in the filter function

eg.

{
  sitemap: {
    filter ({ routes, options }) {

      const endpoint = 'https://xxxx.yyyy/permalinks';
      return axios.get(endpoint)
         .then(res => {
            const permalinks = res.data.map(page => page.permalink);
            let permalinkRoutes = []

            // here you populate the permalinkRoutes array by union of permalinks and routes array, according to your conditions
           //eg. 
           // permalinks.forEach(permalink => {
           //    routes.forEach(route => {
           // 
           //      // here your custom condition (my following condition is dummy ^^)
           //      if (route.url === permalink) {
           //        permalinkRoutes.push({
           //          url: permalink
           //        })
           // 
           //     )
           //  ) 

            routes.push(permalinkRoutes)
            return routes;
         })
         .catch((err) => {  });
  }
}
0
Informations
Question โ€ข Unresolved
#c56 - Created 3 months ago