convert spreadsheet | output google sheet template | collect external content and resources | Search

The code is a JavaScript function named collectRoutes that collects and processes URL paths as part of a routing mechanism, using functions from the ../Core module to generate Google Sheets templates. The function iterates over the URL paths, removes duplicates, and creates new templates associated with each link, returning a promise that resolves when all links have been processed.

Run example

npm run import -- "find known routes to sheets"

find known routes to sheets

var importer = require('../Core')
var wrapTemplate = importer.import("output google sheet template")
var getTemplateProperties = importer.import("google sheet template properties")
var getTemplateByUrl = importer.import("convert sheet helper functions")

var TRIM = /^\s*\/\s*|\s*\/\s*$/ig;

var isFiltered = (url) => url.split('/').length > 1

// combine with "getSections" by using fake "{{> url/path}}" include
function collectRoutes(routes, properties, templates, rendered) {
    var local = routes.concat(properties['render'] || [])
        .filter((link, i, arr) => !rendered.includes(link)
                // protocol means it's absolute remote path and not to try to generate it
                && arr.indexOf(link) == i && !link.includes(':'))

    local.forEach(link => rendered[rendered.length] = link)
    
    var promises = local
        // promise in series so there is no data collisions
        .map(link => resolve => {
            
            var trimmedBase = (properties['base'] || '').replace(TRIM, '')
            link = link.replace(/#.*$/, '') // remove hash #
            link = link.replace(TRIM, '') // remove extra slashes
            
            if(link.substr(0, trimmedBase.length) === trimmedBase) {
                link = link.substr(trimmedBase.length).replace(TRIM, '');
            }
            // any part of a path can contain the reference to a page template
            var key = getTemplateByUrl(templates, link);
            var newProps = Object.assign({}, properties);
        
            // create a temporary template to filter by
            newProps[key + '-' + key + '-link'] = link;
            templates[key + '-' + key] = {template: {rows: [[
                isFiltered(link)
                    ? `{{> ${key}/${key}-${key}-link}}`
                    : `{{> ${key}}}`
            ]]}}
        
            return getTemplateProperties(key + '-' + key, newProps, templates)
                .then(() => wrapTemplate(link, key, newProps[key + '-' + key], newProps))
                .then(page => {
                    var pages = {};
                    pages[link] = page;
                    resolve(pages)
                })
        })
    
    return importer.runAllPromises(promises)
        .then(results => results.reduce((obj, r) => Object.assign(obj, r), {}))
}

module.exports = collectRoutes;

What the code could have been:

/**
 * Import required modules
 */
const { importer, TRIM } = require('../Core');

/**
 * Import helper functions
 */
const { getTemplateProperties, wrapTemplate, getTemplateByUrl } = importer.import([
  'google sheet template properties',
  'output google sheet template',
  'convert sheet helper functions'
]);

/**
 * Check if a URL is filtered
 *
 * @param {string} url - The URL to check
 * @returns {boolean} Whether the URL is filtered
 */
const isFiltered = (url) => url.split('/').length > 1;

/**
 * Collect routes by combining 'routes' and 'properties' with fake include templates
 *
 * @param {array} routes - The list of routes
 * @param {object} properties - The properties object
 * @param {object} templates - The templates object
 * @param {object} rendered - The rendered object
 * @returns {Promise<object>} A promise resolving to the collected routes
 */
function collectRoutes(routes, properties, templates, rendered) {
  const local = routes
   .concat(properties.render || [])
   .filter((link, i, arr) =>!rendered.includes(link) && arr.indexOf(link) === i &&!link.includes(':'));

  local.forEach((link) => rendered[rendered.length] = link);

  const promises = local.map((link) => (resolve) => {
    const trimmedBase = (properties.base || '').replace(TRIM, '');
    const filteredLink = link.replace(/#.*$/, '').replace(TRIM, '');

    if (filteredLink.startsWith(trimmedBase)) {
      filteredLink = filteredLink.substring(trimmedBase.length).replace(TRIM, '');
    }

    const key = getTemplateByUrl(templates, filteredLink);
    const newProps = {...properties };

    newProps[key + '-' + key + '-link'] = link;
    templates[key + '-' + key] = {
      template: {
        rows: [
          isFiltered(link)
           ? `{{> ${key}/${key}-${key}-link}}`
            : `{{> ${key}}}`
        ]
      }
    };

    return getTemplateProperties(key + '-' + key, newProps, templates)
     .then(() => wrapTemplate(link, key, newProps[key + '-' + key], newProps))
     .then((page) => {
        const pages = {};
        pages[link] = page;
        resolve(pages);
      });
  });

  return importer.runAllPromises(promises)
   .then((results) => results.reduce((obj, r) => ({...obj,...r }), {}));
}

module.exports = collectRoutes;

Code Breakdown

Import Statements

The code imports several modules using the require function:

Regular Expression and Helper Function

A regular expression TRIM is defined to remove leading and trailing slashes from a string. The isFiltered function checks if a URL has more than one path segment.

collectRoutes Function

The collectRoutes function takes four arguments: routes, properties, templates, and rendered. It appears to be part of a routing mechanism, collecting and processing URL paths.

Here's a step-by-step breakdown:

  1. Combine Routes: Merges routes and properties['render'] arrays, filters out any duplicate links, and adds them to the rendered array.
  2. Process Each Link: Iterates over the combined array, processing each link:

Return Value

The collectRoutes function returns a promise that resolves when all links have been processed.

Documentation

The code uses Markdown formatting for comments. Unfortunately, the code does not contain any explicit function or variable documentation.