|
| 1 | +const path = require('path') |
| 2 | +const renderOpts = { textOnly: true, encodeEntities: true } |
| 3 | + |
| 4 | +// This middleware exposes a list of all categories and child articles at /categories.json. |
| 5 | +// GitHub Support uses this for internal ZenDesk search functionality. |
| 6 | +module.exports = async function categoriesForSupport (req, res, next) { |
| 7 | + const englishSiteTree = req.context.siteTree.en |
| 8 | + |
| 9 | + const allCategories = [] |
| 10 | + |
| 11 | + await Promise.all(Object.keys(englishSiteTree).map(async (version) => { |
| 12 | + await Promise.all(englishSiteTree[version].childPages.map(async (productPage) => { |
| 13 | + if (productPage.page.relativePath.startsWith('early-access')) return |
| 14 | + if (!productPage.childPages) return |
| 15 | + |
| 16 | + await Promise.all(productPage.childPages.map(async (categoryPage) => { |
| 17 | + // We can't get the rendered titles from middleware/render-tree-titles |
| 18 | + // here because that middleware only runs on the current version, and this |
| 19 | + // middleware processes all versions. |
| 20 | + const name = categoryPage.page.title.includes('{') |
| 21 | + ? await categoryPage.page.renderProp('title', req.context, renderOpts) |
| 22 | + : categoryPage.page.title |
| 23 | + |
| 24 | + allCategories.push({ |
| 25 | + name, |
| 26 | + published_articles: await findArticlesPerCategory(categoryPage, [], req.context) |
| 27 | + }) |
| 28 | + })) |
| 29 | + })) |
| 30 | + })) |
| 31 | + |
| 32 | + return res.json(allCategories) |
| 33 | +} |
| 34 | + |
| 35 | +async function findArticlesPerCategory (currentPage, articlesArray, context) { |
| 36 | + if (currentPage.page.documentType === 'article') { |
| 37 | + const title = currentPage.page.title.includes('{') |
| 38 | + ? await currentPage.page.renderProp('title', context, renderOpts) |
| 39 | + : currentPage.page.title |
| 40 | + |
| 41 | + articlesArray.push({ |
| 42 | + title, |
| 43 | + slug: path.basename(currentPage.href) |
| 44 | + }) |
| 45 | + } |
| 46 | + |
| 47 | + if (!currentPage.childPages) return articlesArray |
| 48 | + |
| 49 | + // Run recursively to find any articles deeper in the tree. |
| 50 | + await Promise.all(currentPage.childPages.map(async (childPage) => { |
| 51 | + await findArticlesPerCategory(childPage, articlesArray, context) |
| 52 | + })) |
| 53 | + |
| 54 | + return articlesArray |
| 55 | +} |
0 commit comments