d3xter-dev / sitemap-module-nuxt-3

Sitemap Module for Nuxt 3
https://sitemap.nuxtjs.org
MIT License
63 stars 12 forks source link

How to use dynamic routes #1

Closed jmdmacapagal closed 2 years ago

jmdmacapagal commented 2 years ago

am I doing it wrong? sitemap is not generating

Im doing npm run build npm run dev

package.json

"@funken-studio/sitemap-nuxt-3": "^3.1.1",
"nuxt": "^3.0.0-rc.3",
/helpers/dynamicRoutes

import { getAllJournalSlugs } from "../queries/journal.queries";
import { getCategorySlugs } from "../queries/category.queries";
import { getAllProductSlugs } from "../queries/product.queries";

export default async () => {
  const config = useRuntimeConfig();

  const getContentfulData = async (query) => {
    const fetchUrl = `https://graphql.contentful.com/content/v1/spaces/${config.CONTENTFUL_SPACE_ID}/environments/${config.CONTENTFUL_ENVIRONMENT}`;
    const fetchOptions = {
      method: "POST",
      headers: {
        Authorization: `Bearer ${config.CONTENTFUL_ACCESS_TOKEN}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        query
      })
    };

    try {
      const response = await fetch(fetchUrl, fetchOptions).then((r) => r.json());
      return response.data;
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    }
  };

  const journals = await getContentfulData(getAllJournalSlugs);
  const journalCategories = await getContentfulData(getCategorySlugs);
  const products = await getContentfulData(getAllProductSlugs);

  const modifiedJournalSlugs = journals.journalCollection.items.map((journal) => {
    return `${config.MYURL}/journal/${journal.slug}`;
  });

  const modifiedJournalCategoriesSlugs = journalCategories.categoryCollection.items.map((category) => {
    return `${config.MYURL}/journal/category/${category.slug}`;
  });

  const modifiedProductSlugs = products.productCollection.items.map((product) => {
    return `${config.MYURL}/product/${product.slug}`;
  });

  return [...modifiedJournalSlugs, ...modifiedJournalCategoriesSlugs, ...modifiedProductSlugs];
};
nuxt.config.ts

import dynamicRoutes from "./helpers/dynamicRoutes";

export default defineNuxtConfig({
  sitemap: {
    hostname: "{{ MYURL }}",
    cacheTime: 1,
    routes: dynamicRoutes,
    defaults: {
      changefreq: "daily",
      priority: 1,
      lastmod: new Date().toISOString()
    }
  }
});
d3xter-dev commented 2 years ago

OUTDATED ANSWERE

You can't use import in the dynamicRoutes, make sure to use require directly in the function. (Like I did, in the example which can be found in the readme)

Otherwise this won't work. That's an issue which can't be solved, since the dynamicRoutes function is converted to a string and then executed on the server.

export default async () => {
  const config = useRuntimeConfig();
  const path = require('path');

  const { getAllJournalSlugs } = require( "../../queries/journal.queries");
  const { getCategorySlugs }  = require("../../queries/category.queries");
  const { getAllProductSlugs }  = require("../../queries/product.queries");

  const getContentfulData = async (query) => {
    const fetchUrl = `https://graphql.contentful.com/content/v1/spaces/${config.CONTENTFUL_SPACE_ID}/environments/${config.CONTENTFUL_ENVIRONMENT}`;
    const fetchOptions = {
      method: "POST",
      headers: {
        Authorization: `Bearer ${config.CONTENTFUL_ACCESS_TOKEN}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        query
      })
    };

    try {
      const response = await fetch(fetchUrl, fetchOptions).then((r) => r.json());
      return response.data;
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    }
  };

  const journals = await getContentfulData(getAllJournalSlugs);
  const journalCategories = await getContentfulData(getCategorySlugs);
  const products = await getContentfulData(getAllProductSlugs);

  const modifiedJournalSlugs = journals.journalCollection.items.map((journal) => {
    return `${config.MYURL}/journal/${journal.slug}`;
  });

  const modifiedJournalCategoriesSlugs = journalCategories.categoryCollection.items.map((category) => {
    return `${config.MYURL}/journal/category/${category.slug}`;
  });

  const modifiedProductSlugs = products.productCollection.items.map((product) => {
    return `${config.MYURL}/product/${product.slug}`;
  });

  return [...modifiedJournalSlugs, ...modifiedJournalCategoriesSlugs, ...modifiedProductSlugs];
};
d3xter-dev commented 2 years ago

OR what maybe could be done is: that we remove support for directly setting a function in the nuxt.config and replace it with support for file paths, a Path to a .js file which then gets executed in the server-side middleware to retrieve dynamic routes.

Would that be a better solution?

jmdmacapagal commented 2 years ago

@d3xter-dev yeah I think, since the require is not working with relative path, tried jsut now

d3xter-dev commented 2 years ago

If I find some more time I will add an option to use a file path instead of an function.
Maybe you can find a workaround in the mean time, I will close that here for now.

One more thing: be aware that your relative path would need to be relative to .nuxt/dev or .output/server, so in order to access the package.json for example it would have to be

  const json = require('../../package.json')
d3xter-dev commented 2 years ago

@jmdmacapagal I just updated the README with a new example of how to use dynamic routes plesae check if that works for you, and let me know :) thanks!