22// to quickly search for Help articles by title and insert the link to
33// the article into a reply to a customer.
44const path = require ( 'path' )
5- const fs = require ( 'fs' )
5+ const fs = require ( 'fs' ) . promises
66const matter = require ( 'gray-matter' )
77const dotcomDir = path . join ( __dirname , '../content/github' )
88const dotcomIndex = path . join ( dotcomDir , 'index.md' )
99const linkRegex = / { % (?: t o p i c _ ) ? l i n k _ i n _ l i s t ? \/ ( .* ?) ? % } / g
1010
1111module . exports = async ( req , res , next ) => {
1212 if ( req . path !== '/categories.json' ) return next ( )
13- const categories = generateCategories ( )
13+ const categories = await generateCategories ( )
1414 return res . json ( categories )
1515}
1616
17- function generateCategories ( ) {
17+ async function generateCategories ( ) {
1818 // get links included in dotcom index page.
1919 // each link corresponds to a dotcom subdirectory
2020 // example: getting-started-with-github
21- const links = getLinks ( fs . readFileSync ( dotcomIndex , 'utf8' ) )
22-
23- const categories = [ ]
21+ const links = getLinks ( await fs . readFile ( dotcomIndex , 'utf8' ) )
2422
2523 // get links included in each subdir's index page
2624 // these are links to articles
27- links . forEach ( link => {
25+ const categories = await Promise . all ( links . map ( async link => {
2826 const category = { }
2927 const indexPath = getPath ( link , 'index' )
30- const indexContents = fs . readFileSync ( indexPath , 'utf8' )
28+ const indexContents = await fs . readFile ( indexPath , 'utf8' )
3129 const { data, content } = matter ( indexContents )
3230
3331 // get name from title frontmatter
@@ -36,29 +34,23 @@ function generateCategories () {
3634 // get child article links
3735 const articleLinks = getLinks ( content )
3836
39- const publishedArticles = [ ]
40-
41- articleLinks . forEach ( articleLink => {
42- const publishedArticle = { }
43-
37+ category . published_articles = ( await Promise . all ( articleLinks . map ( async articleLink => {
4438 // get title from frontmatter
4539 const articlePath = getPath ( link , articleLink )
46- const articleContents = fs . readFileSync ( articlePath , 'utf8' )
40+ const articleContents = await fs . readFile ( articlePath , 'utf8' )
4741 const { data } = matter ( articleContents )
4842
4943 // do not include map topics in list of published articles
5044 if ( data . mapTopic ) return
5145
52- publishedArticle . title = data . title
53- publishedArticle . slug = articleLink
54-
55- publishedArticles . push ( publishedArticle )
56- } )
57-
58- category . published_articles = publishedArticles
46+ return {
47+ title : data . title ,
48+ slug : articleLink
49+ }
50+ } ) ) ) . filter ( Boolean )
5951
60- categories . push ( category )
61- } )
52+ return category
53+ } ) )
6254
6355 return categories
6456}
0 commit comments