« 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: 34718b5c773be1792e6da07e4cd2472cc43e3d62 (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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
'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);

      // Get mapped fields from thing
      let mappedResult;
      try {
        mappedResult = mapper(thing);
      } 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;
      }

      // Build doc and add to index
      const doc = {
        reference,
        ...mappedResult
      }
      // Print description of an 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);
    }
  }

  // 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,
      color: track.color,
      album: track.album.name,
      albumDirectory: track.album.directory,

      artists: [
        track.artistContribs.map(contrib => contrib.artist.name),
        ...track.artistContribs.map(contrib => contrib.artist.aliasNames)
      ].flat(),

      additionalNames: track.additionalNames.map(entry => entry.name),

      artworkKind:
        (track.hasUniqueCoverArt
          ? 'track'
       : track.album.hasCoverArt
          ? 'album'
          : 'none'),
    })
  );

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

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

  // Groups
  readCollectionIntoIndex(
    wikiData.groupData,
    indexes.groups,
    group => ({
      names: group.name,
      description: group.description,
      // category: group.category
    })
  );

  // Flashes
  readCollectionIntoIndex(
    wikiData.flashData,
    indexes.flashes,
    flash => ({
      name: flash.name,
      tracks: flash.featuredTracks.map(track => track.name),
      contributors: [
        flash.contributorContribs.map(contrib => contrib.artist.name),
        ...flash.contributorContribs.map(contrib => contrib.artist.aliasNames)
      ].flat()
    })
  );
}

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.`;
}