All files / src indexer.js

97.32% Statements 109/112
90.91% Branches 60/66
100% Functions 9/9
97.22% Lines 105/108

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426                                                                                                        5x                                       24x   1x   23x   1x   22x   1x   21x   1x   20x   1x   19x   1x   18x   1x   17x   1x   16x   1x   15x   1x   14x   1x   13x   1x   12x   1x   11x   1x   10x   1x   9x   1x   8x   1x   7x   1x     6x     6x     6x   6x       6x       6x   6x                         6x                                         6x                   6x                     6x               6x   6x   6x   6x   6x   6x               6x   18x 18x   36x 36x         36x   36x   36x                   6x   6x 6x         6x           6x   6x             6x                 6x   90x 90x   6x   84x         84x   84x   84x                 72x   36x   60x             36x 36x 36x         36x                                     18x   84x 84x   84x   78x   84x   42x   84x         84x   84x   84x   6x   84x   36x   84x                   6x   6x 6x         6x       6x       6x            
/*
 * Part of Pleiar.no - a collection of tools for nurses
 *
 * Copyright (C) Fagforbundet 2019
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
 
// @flow
 
import lunr from './helper.lunr.js';
import { removeMarkdown } from './helper.markdown.js';
import type {
    QuizDataContainer,
    DictionaryEntry,
    ExternalResourcesEntry,
    LabValueEntry,
    HandbookDataEntry,
    HandbookDataStructure,
    LabValueDataStructure,
    DictionaryDataStructure,
    ExternalResourcesDataStructure,
    ToolsListDataStructure,
    NutritionDataStructure,
    ExternallyIndexedList
} from './types/data';
 
/**
 * A single entry in the search index
 */
export type IndexEntry = {|
    id: string,
    tittel?: string,
    body?: string,
    keywords?: string,
    url?: string
|};
 
type LunrObject = typeof lunr;
 
const PleiarIndexer = {
    /**
     * Method that performs the actual indexing. This has no data import of its
     * own, so you have to supply all of the datastructures yourself.
     */
    index (
        externalResources: ExternalResourcesDataStructure,
        dictionary: DictionaryDataStructure,
        labValues: LabValueDataStructure,
        handbook: HandbookDataStructure,
        tools: ToolsListDataStructure,
        nutrition: NutritionDataStructure,
        externallyIndexed: ExternallyIndexedList,
        quickref: HandbookDataStructure,
        quizData: QuizDataContainer,
    ): LunrObject
    {
        /*
         * Validate parameters
         */
        if(externalResources === undefined)
        {
            throw('Missing parameter to PleiarIndexer.index: externalResources');
        }
        else if (!Array.isArray(externalResources))
        {
            throw('Invalid parameter to PleiarIndexer.index: externalResources');
        }
        if(dictionary === undefined)
        {
            throw('Missing parameter to PleiarIndexer.index: dictionary');
        }
        else if (!Array.isArray(dictionary))
        {
            throw('Invalid parameter to PleiarIndexer.index: dictionary');
        }
        if(labValues === undefined)
        {
            throw('Missing parameter to PleiarIndexer.index: labValues');
        }
        else if(!Array.isArray(labValues.values))
        {
            throw('Invalid parameter to PleiarIndexer.index: labValues');
        }
        if(handbook === undefined)
        {
            throw('Missing parameter to PleiarIndexer.index: handbook');
        }
        else if(!Array.isArray(handbook.order))
        {
            throw('Invalid parameter to PleiarIndexer.index: handbook');
        }
        if(tools === undefined)
        {
            throw('Missing parameter to PleiarIndexer.index: tools');
        }
        else if(!Array.isArray(tools))
        {
            throw('Invalid parameter to PleiarIndexer.index: tools');
        }
        if(nutrition === undefined)
        {
            throw('Missing parameter to PleiarIndexer.index: nutrition');
        }
        else if(nutrition.basicGroups === undefined)
        {
            throw('Invalid parameter to PleiarIndexer.index: nutrition');
        }
        if(externallyIndexed === undefined)
        {
            throw('Missing parameter to PleiarIndexer.index: externallyIndexed');
        }
        else if(!Array.isArray(externallyIndexed))
        {
            throw('Invalid parameter to PleiarIndexer.index: externallyIndexed');
        }
        if(quickref === undefined)
        {
            throw('Missing parameter to PleiarIndexer.index: quickref');
        }
        else if(!Array.isArray(quickref.order))
        {
            throw('Invalid parameter to PleiarIndexer.index: quickref');
        }
        if(quizData === undefined)
        {
            throw("Missing parameter to PleiarIndexer.index: quizData");
        }
        else if(Object.keys(quizData).length === 0)
        {
            throw("Invalid parameter to PleiarIndexer.index: quizData");
        }
 
        const index = lunr( function ()
            {
                // The title field is most important
                this.field('tittel',{
                    boost: 2.0
                });
                this.field('body');
                // Keywords are not quite as important as title and body
                this.field('keywords',{
                    boost: 0.5
                });
                // Url is not important at all
                this.field('url',{
                    boost: 0.1
                });
                // Enable storing of positional metadata in the index
                this.metadataWhitelist = ['position'];
                // Build the index
                PleiarIndexer.constructIndex({
                    external: externalResources,
                    dict: dictionary,
                    labValues: labValues.values,
                    handbook: handbook,
                    tools: tools,
                    nutrition: nutrition,
                    externallyIndexed: externallyIndexed,
                    quickref: quickref,
                    quizData,
                    indexer: this
                });
            });
        return index;
    },
 
    /**
     * This constructs the actual index, providing data and title maps
     * to `indexFromSource`.
     */
    constructIndex (idxData: {|
        external: ExternalResourcesDataStructure,
        dict: DictionaryDataStructure,
        labValues: Array<LabValueEntry>,
        handbook: HandbookDataStructure,
        tools: ToolsListDataStructure,
        nutrition: NutritionDataStructure,
        externallyIndexed: ExternallyIndexedList,
        quickref: HandbookDataStructure,
        indexer: LunrObject,
        quizData: QuizDataContainer,
    |})
    {
        /* External resources */
        PleiarIndexer.indexFromSource({
            source: idxData.external,
            indexer: idxData.indexer,
            titleField: "title",
            descriptionField: "description",
            keywordField: "keywords",
            urlField: "url",
            sourceName: "externalResources"
        });
        /* Dictionary */
        PleiarIndexer.indexFromSource({
            source: idxData.dict,
            indexer: idxData.indexer,
            descriptionMarkdown: true,
            titleField: "expression",
            descriptionField: "description",
            keywordField: "keywords",
            alternateKeywords: "seeAlso",
            sourceName: "dictionary"
        });
        /* Lab values */
        PleiarIndexer.indexFromSource({
            source: idxData.labValues,
            indexer: idxData.indexer,
            keywordField: "keywords",
            titleField: "navn",
            sourceName: "labValue",
        });
        /* Handbook entries */
        PleiarIndexer._recursiveLunrIndexFromHandbook(idxData.indexer, idxData.handbook, 'handbook');
        /* Tools */
        PleiarIndexer._indexFromTools(idxData.indexer, idxData.tools);
        /* Nutrition entries */
        PleiarIndexer._indexFromNutriData(idxData.indexer, idxData.nutrition);
        /* Externally indexed data */
        PleiarIndexer._indexFromExternal(idxData.indexer, idxData.externallyIndexed);
        /* Quickref entries */
        PleiarIndexer._recursiveLunrIndexFromHandbook(idxData.indexer, idxData.quickref, 'quickref');
        /* Quickref entries */
        PleiarIndexer._indexFromElearn(idxData.indexer, idxData.quizData );
    },
 
    /**
     * Adds tools to the index
     */
    _indexFromTools (idx: LunrObject, tools: ToolsListDataStructure)
    {
        for(let categoryNO: number = 0; categoryNO < tools.length; categoryNO++)
        {
            const category = tools[categoryNO];
            for(let entryNO: number = 0; entryNO < category.tools.length; entryNO++)
            {
                const entry = category.tools[entryNO];
                const doc : IndexEntry = {
                    id: 'tool/'+categoryNO+'/'+entryNO,
                    tittel: entry.title,
                    url: entry.path
                };
                Eif(entry.keywords)
                {
                    doc.keywords = entry.keywords;
                }
                idx.add(doc);
            }
        }
    },
 
    /**
     * Adds externally indexed items to the index
     */
    _indexFromExternal(idx: LunrObject, indexList: ExternallyIndexedList)
    {
        for(let indexNO: number = 0; indexNO < indexList.length; indexNO++)
        {
            const item = indexList[indexNO];
            const keywordmap = {
                'fagprat':'Fagprat, podkast',
                'other':'',
            };
            let keywords: ?string;
            Iif(item.keywords)
            {
                keywords = item.keywords;
            }
            else
            {
                keywords = keywordmap[item.type];
            }
            const doc : IndexEntry = {
                id: 'external/'+indexNO,
                tittel: item.title,
                url: item.url,
                body: item.text,
                keywords,
            };
            idx.add(doc);
        }
    },
 
    /**
     * Adds nutrition data to the index
     */
    _indexFromNutriData (idx: LunrObject, nutrition: NutritionDataStructure)
    {
        for(const ident in nutrition.basicGroups)
        {
            const entry = nutrition.basicGroups[ident];
            if(entry.name === nutrition.customLabel)
            {
                continue;
            }
            const doc : IndexEntry = {
                id: 'nutrition/'+ident,
                tittel: "",
                body: entry.name
            };
            Eif(doc.tittel !== ident)
            {
                doc.keywords = ident;
            }
            idx.add(doc);
        }
    },
 
    /**
     * Recursively indexes the handbook datastructure
     */
    _recursiveLunrIndexFromHandbook (idx: LunrObject, handbook : HandbookDataEntry | HandbookDataStructure, idxType: 'handbook' | 'quickref')
    {
        if(handbook.tree !== undefined)
        {
            for(const subentry in handbook.tree)
            {
                PleiarIndexer._recursiveLunrIndexFromHandbook(idx, handbook.tree[subentry], idxType);
            }
        }
        else
        {
            // Flow isn't very smart, if we don't have tree then this is a HandbookDataEntry,
            // not a HandbookDataStructure
            handbook = ((handbook: $UnsafeRecast): HandbookDataEntry);
            const content = removeMarkdown( handbook.content );
            const doc : IndexEntry = {
                id: idxType+'/'+handbook.path.join('/'),
                body: content,
                tittel: handbook.title
            };
            idx.add(doc);
        }
    },
 
    /**
     * Adds a single data source to the index, based upon the fields provided.
     */
    indexFromSource(src: {|
            source: Array<ExternalResourcesEntry> | Array<DictionaryEntry> | Array<LabValueEntry>,
            indexer: LunrObject,
            titleField: string,
            descriptionField?: string,
            descriptionMarkdown?: boolean,
            keywordField?: string,
            urlField?: string,
            sourceName: string,
            alternateKeywords?: string,
    |})
    {
        for(let no: number = 0; no < src.source.length; no++)
        {
            const entry = src.source[no];
            const id = src.sourceName+'/'+no;
            let body: string;
            if(src.descriptionField)
            {
                body = entry[ src.descriptionField ];
            }
            if (src.descriptionMarkdown && src.descriptionField)
            {
                body = removeMarkdown( entry[ src.descriptionField ] );
            }
            const doc: IndexEntry = {
                id,
                tittel: entry[ src.titleField ],
                body
            };
            Eif(src.keywordField)
            {
                doc.keywords = entry[ src.keywordField ];
            }
            if( src.alternateKeywords && (!doc.keywords || doc.keywords.length == 0) && Array.isArray( entry[ src.alternateKeywords ] ))
            {
                doc.keywords = entry[ src.alternateKeywords ].join(', ');
            }
            if(src.urlField)
            {
                doc.url = entry[ src.urlField ];
            }
            src.indexer.add(doc);
        }
    },
 
 
    /**
     * Adds tools to the index
     */
    _indexFromElearn(idx: LunrObject, quiz: QuizDataContainer)
    {
        for(const name of Object.keys(quiz))
        {
            const entry = quiz[name];
            const doc : IndexEntry = {
                id: 'quiz/'+name,
                tittel: entry.title,
                url: '/elaering/'+name,
            };
            Iif(entry.description)
            {
                doc.body = entry.description;
            }
            Iif(entry.keywords)
            {
                doc.keywords = entry.keywords;
            }
            idx.add(doc);
        }
    },
};
 
export default PleiarIndexer;