search-wiki.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import _ from 'lodash'
  2. import AlgoliaSearch from 'algoliasearch'
  3. import getMeta from '../../utils/meta'
  4. interface WikiHit {
  5. pageName: string
  6. sectionName?: string
  7. kb?: boolean
  8. _highlightResult: {
  9. pageName: {
  10. value: string
  11. }
  12. content: {
  13. value: string
  14. }
  15. }
  16. }
  17. export interface FormattedWikiHit {
  18. url: string
  19. pageName: string
  20. rawPageName: string
  21. sectionName?: string
  22. content: string
  23. }
  24. interface AlgoliaSearchResponse {
  25. hits: WikiHit[]
  26. nbHits: number
  27. nbPages: number
  28. }
  29. let wikiIdx: AlgoliaSearch.Index | undefined
  30. export async function searchWiki(
  31. query: string,
  32. options?: AlgoliaSearch.QueryParameters
  33. ): Promise<AlgoliaSearchResponse> {
  34. if (!wikiIdx) {
  35. const algoliaConfig = getMeta('ol-algolia')
  36. const wikiIndex = _.get(algoliaConfig, 'indexes.wiki')
  37. if (wikiIndex && algoliaConfig) {
  38. const client = AlgoliaSearch(algoliaConfig.appId, algoliaConfig.apiKey)
  39. wikiIdx = client.initIndex(wikiIndex)
  40. }
  41. }
  42. if (!wikiIdx) {
  43. return { hits: [], nbHits: 0, nbPages: 0 }
  44. }
  45. return wikiIdx.search({ query, ...options }) as Promise<AlgoliaSearchResponse>
  46. }
  47. export function formatWikiHit(hit: WikiHit): FormattedWikiHit {
  48. const pageUnderscored = hit.pageName.replace(/\s/g, '_')
  49. const pageSlug = encodeURIComponent(pageUnderscored)
  50. const pagePath = hit.kb ? 'how-to' : 'latex'
  51. let pageAnchor = ''
  52. const rawPageName = hit._highlightResult.pageName.value
  53. const sectionName = hit.sectionName
  54. let pageName = rawPageName
  55. if (sectionName) {
  56. pageAnchor = `#${sectionName.replace(/\s/g, '_')}`
  57. pageName += ' - ' + sectionName
  58. }
  59. const body = hit._highlightResult.content.value
  60. const content = body
  61. .split('\n')
  62. .filter(line => line.includes('<em>') && !line.includes('[edit]'))
  63. .join('\n...\n')
  64. const url = `/learn/${pagePath}/${pageSlug}${pageAnchor}`
  65. return { url, pageName, rawPageName, sectionName, content }
  66. }