« get me outta code hell

search.js « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/search.js
blob: b83bb0e078e739f572bc234f921f2033e63819b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
'use strict';

import {mkdir, writeFile} from 'node:fs/promises';
import * as path from 'node:path';

import FlexSearch from 'flexsearch';

import {logError, logInfo, logWarn} from '#cli';
import Thing from '#thing';

import {makeSearchIndexes} from './util/searchSchema.js';

const DEBUG_DOC_GEN = true;

async function populateSearchIndexes(indexes, wikiData) {

  const haveLoggedDocOfThing = {}; // debugging only

  function readCollectionIntoIndex(
    collection,
    index,
    mapper
  ) {
    // Add a doc for mapper(thing) to index for each thing in collection.
    for (const thing of collection) {
      const reference = Thing.getReference(thing);
      try {
        const doc = {
          reference,
          ...mapper(thing)
        };
        // Print description of output doc, if debugging enabled.
        if (DEBUG_DOC_GEN && !haveLoggedDocOfThing[thing.constructor.name]) {
          logInfo(JSON.stringify(doc, null, 2));
          haveLoggedDocOfThing[thing.constructor.name] = true;
        }
        index.add(doc);
      } catch (e) {
        // Enrich error context
        logError`Failed to write searchable doc for thing ${reference}`;
        const thingSchemaSummary = Object.fromEntries(
          Object.entries(thing)
          .map(([k, v]) => [k, v ? (v.constructor.name || typeof v) : v])
        );
        logError("Availible properties: " + JSON.stringify(thingSchemaSummary, null, 2));
        throw e;
      }
    }
  }

  // Albums
  readCollectionIntoIndex(
    wikiData.albumData,
    indexes.albums,
    album => ({
      name: album.name,
      groups: album.groups.map(group => group.name),
    })
  );

  // Tracks
  readCollectionIntoIndex(
    wikiData.trackData,
    indexes.tracks,
    track => ({
      name: track.name,
      album: track.album.name,
      artists: [
        track.artistContribs.map(contrib => contrib.artist.name),
        ...track.artistContribs.map(contrib => contrib.artist.aliasNames)
      ].flat(),
      additionalNames: track.additionalNames.map(entry => entry.name),
    })
  );

  // Artists
  const realArtists =
    wikiData.artistData
      .filter(artist => !artist.isAlias);

  readCollectionIntoIndex(
    realArtists,
    indexes.artists,
    artist => ({
      names: [artist.name, ...artist.aliasNames],
    })
  );


async function exportIndexesToJson(indexes) {
  const searchData = {};

  // Map each index to an export promise, and await all.
  await Promise.all(
    Object.entries(indexes)
      .map(([indexName, index]) => {
        searchData[indexName] = {};
        return index.export((key, data) => {
          searchData[indexName][key] = data;
        });
      }));

  return searchData;
}

export async function writeSearchJson({
  wikiCachePath,
  wikiData,
}) {
  if (!wikiCachePath) {
    throw new Error(`Expected wikiCachePath to write into`);
  }

  // Basic flow is:
  // 1. Define schema for type
  // 2. Add documents to index
  // 3. Save index to exportable json

  const indexes = makeSearchIndexes(FlexSearch);

  await populateSearchIndexes(indexes, wikiData);

  const searchData = await exportIndexesToJson(indexes);

  const outputDirectory =
    path.join(wikiCachePath, 'search');

  const outputFile =
    path.join(outputDirectory, 'index.json');

  await mkdir(outputDirectory, {recursive: true});
  await writeFile(outputFile, JSON.stringify(searchData));

  logInfo`Search index successfully written.`;
}