reference-index.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import Bib2Json from './bib2json'
  2. import { AdvancedReferenceSearchResult, Bib2JsonEntry, Changes } from './types'
  3. export abstract class ReferenceIndex {
  4. keys: Set<string> = new Set()
  5. abstract updateIndex({ updates, deletes }: Changes): void
  6. async search(_query: string): Promise<AdvancedReferenceSearchResult> {
  7. return { hits: [] }
  8. }
  9. getKeys(): Set<string> {
  10. return this.keys
  11. }
  12. parseEntries(content: string): Bib2JsonEntry[] {
  13. const allowedFields = ['author', 'journal', 'title', 'year', 'date']
  14. // @ts-expect-error Bib2Json works as both a constructor and a function
  15. const { entries } = Bib2Json(content, allowedFields)
  16. for (const entry of entries) {
  17. if (entry.Fields?.year) {
  18. entry.Fields.year = parseInt(entry.Fields.year).toString()
  19. if (entry.Fields.year === 'NaN') {
  20. delete entry.Fields.year
  21. }
  22. }
  23. setDefaultFields(entry.Fields)
  24. }
  25. return entries
  26. }
  27. }
  28. function setDefaultFields(
  29. fields: Partial<Bib2JsonEntry['Fields']>
  30. ): Bib2JsonEntry['Fields'] {
  31. const requiredFields = ['author', 'journal', 'title', 'date', 'year'] as const
  32. for (const field of requiredFields) {
  33. if (!fields[field]) {
  34. fields[field] = ''
  35. }
  36. }
  37. return fields as Bib2JsonEntry['Fields']
  38. }