search-wiki.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. let pageName = hit._highlightResult.pageName.value
  25. if (hit.sectionName) {
  26. pageAnchor = `#${hit.sectionName.replace(/\s/g, '_')}`
  27. pageName += ' - ' + hit.sectionName
  28. }
  29. const body = hit._highlightResult.content.value
  30. const content = body
  31. .split('\n')
  32. .filter(line => line.includes('<em>') && !line.includes('[edit]'))
  33. .join('\n...\n')
  34. const url = `/learn/${pagePath}/${pageSlug}${pageAnchor}`
  35. return { url, pageName, content }
  36. }