aboutsummaryrefslogtreecommitdiff
path: root/src/server/Search.ts
blob: e2a74b737b12abb1bd604de6e44980de62c21784 (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
import * as rp from 'request-promise';
import { Database } from './database';
import { thisExpression } from 'babel-types';

export class Search {
    public static Instance = new Search();
    private url = 'http://localhost:8983/solr/';

    public async updateDocument(document: any) {
        try {
            const res = await rp.post(this.url + "dash/update", {
                headers: { 'content-type': 'application/json' },
                body: JSON.stringify([document])
            });
            return res;
        } catch (e) {
            // console.warn("Search error: " + e + document);
        }
    }

    public async search(query: string, start: number = 0) {
        try {
            const searchResults = JSON.parse(await rp.get(this.url + "dash/select", {
                qs: {
                    q: query,
                    fl: "id",
                    start: start
                }
            }));
            const { docs, numFound } = searchResults.response;
            const ids = docs.map((field: any) => field.id);
            return { ids, numFound };
        } catch {
            return { ids: [], numFound: -1 };
        }
    }

    public async clear() {
        try {
            return await rp.post(this.url + "dash/update", {
                body: {
                    delete: {
                        query: "*:*"
                    }
                },
                json: true
            });
        } catch { }
    }
}