search-wiki.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import _ from 'lodash'
  2. import AlgoliaSearch from 'algoliasearch'
  3. import getMeta from '../../utils/meta'
  4. let wikiIdx
  5. export async function searchWiki(...args) {
  6. if (!wikiIdx) {
  7. const algoliaConfig = getMeta('ol-algolia')
  8. const wikiIndex = _.get(algoliaConfig, 'indexes.wiki')
  9. if (wikiIndex) {
  10. const client = AlgoliaSearch(algoliaConfig.appId, algoliaConfig.apiKey)
  11. wikiIdx = client.initIndex(wikiIndex)
  12. }
  13. }
  14. if (!wikiIdx) {
  15. return { hits: [], nbHits: 0, nbPages: 0 }
  16. }
  17. return wikiIdx.search(...args)
  18. }
  19. export function formatWikiHit(hit) {
  20. const pageUnderscored = hit.pageName.replace(/\s/g, '_')
  21. const pageSlug = encodeURIComponent(pageUnderscored)
  22. const pagePath = hit.kb ? 'how-to' : 'latex'
  23. let pageAnchor = ''
  24. const rawPageName = hit._highlightResult.pageName.value
  25. const sectionName = hit.sectionName
  26. let pageName = rawPageName
  27. if (sectionName) {
  28. pageAnchor = `#${sectionName.replace(/\s/g, '_')}`
  29. pageName += ' - ' + sectionName
  30. }
  31. const body = hit._highlightResult.content.value
  32. const content = body
  33. .split('\n')
  34. .filter(line => line.includes('<em>') && !line.includes('[edit]'))
  35. .join('\n...\n')
  36. const url = `/learn/${pagePath}/${pageSlug}${pageAnchor}`
  37. return { url, pageName, rawPageName, sectionName, content }
  38. }