From ad7cf21d0e29b2e6299757b41eb4ef46d37c640d Mon Sep 17 00:00:00 2001 From: Juan Picado Date: Mon, 17 Apr 2017 15:52:36 +0200 Subject: [PATCH] Migrate Search to class --- lib/search.js | 104 ++++++++++++++++++++++++++++---------------------- 1 file changed, 58 insertions(+), 46 deletions(-) diff --git a/lib/search.js b/lib/search.js index 6bed026da..b04d617f9 100644 --- a/lib/search.js +++ b/lib/search.js @@ -1,49 +1,61 @@ -var lunr = require('lunr') +"use strict"; -function Search() { - var self = Object.create(Search.prototype) - self.index = lunr(function() { - this.field('name' , { boost: 10 }) - this.field('description' , { boost: 4 }) - this.field('author' , { boost: 6 }) - this.field('readme') - }) - return self +const lunr = require('lunr') + +class Search { + constructor() { + this.index = lunr(function() { + this.field('name' , { boost: 10 }) + this.field('description' , { boost: 4 }) + this.field('author' , { boost: 6 }) + this.field('readme') + }) + } + + query(q) { + return q === '*' + ? this.storage.config.localList.get().map( function( pkg ) { + return { ref: pkg, score: 1 }; + }) : this.index.search(q); + } + + add(pkg) { + this.index.add({ + id: pkg.name, + name: pkg.name, + description: pkg.description, + author: pkg._npmUser ? pkg._npmUser.name : '???', + }) + } + + add(pkg) { + this.index.add({ + id: pkg.name, + name: pkg.name, + description: pkg.description, + author: pkg._npmUser ? pkg._npmUser.name : '???', + }) + } + + remove(name) { + this.index.remove({ id: name }) + } + + reindex() { + var self = this + this.storage.get_local(function(err, packages) { + if (err) throw err // that function shouldn't produce any + var i = packages.length + while (i--) { + self.add(packages[i]) + } + }) + } + + configureStorage(storage) { + this.storage = storage + this.reindex() + } } -Search.prototype.query = function(q) { - return q === '*' - ? this.storage.config.localList.get().map( function( package ){ return { ref: package, score: 1 }; } ) - : this.index.search(q); -} - -Search.prototype.add = function(package) { - this.index.add({ - id: package.name, - name: package.name, - description: package.description, - author: package._npmUser ? package._npmUser.name : '???', - }) -}, - -Search.prototype.remove = function(name) { - this.index.remove({ id: name }) -} - -Search.prototype.reindex = function() { - var self = this - this.storage.get_local(function(err, packages) { - if (err) throw err // that function shouldn't produce any - var i = packages.length - while (i--) { - self.add(packages[i]) - } - }) -} - -Search.prototype.configureStorage = function(storage) { - this.storage = storage - this.reindex() -} - -module.exports = Search() +module.exports = new Search();