bootstrap-wikidata.ts 1.73 KB
Newer Older
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
import { queryTaxonomy } from 'wikidata-taxonomy';
import util = require('util');

export interface InterfaceProperty  {
  name: string;
  qid: string;
}

export class BootstrapWikidata {
  /**
   * An array of properties to load from wikidata
   * @type {any[]}
   */
  private properties = [];

  /**
   * Load a list of properties with subclasses from wikidata
   * @param {InterfaceProperty[]} properties
   * @returns {Promise<void>}
   */
  public async init(properties: InterfaceProperty[]){
    await properties.forEach(async (property) => {
      const sublclasses = await this.getProperties(property.qid);
      // add the main property to the list
      sublclasses.push(property.qid);
      this.properties.push({name: property.name, properties: sublclasses});
    });
  }

  /**
   * Get a collection of subclasses for a named property
   * @param {string} name
   * @returns {string[]}
   */
  public get(name: string): string[] {
    const property = this.properties.find((p) => {
      return p.name === name;
    });
    return property.properties;
  }

  /**
   * Get a property with his subclasses from wikidata
   * @param {string} property
   * @returns {Promise<any>}
   */
  private async getProperties(property: string) {
    // P1647 = subproperty
    return await queryTaxonomy(property, {brief: true, property: ['P1647']})
      .then((taxonomy) => {
        const properties = [];
        taxonomy.concepts.forEach((concept) => {
          const qid = concept.notation[0];
          properties.push(qid);
        });
        return properties.filter((d, i, a) => {
          return a.indexOf(d) === i;
        });
      })
      .catch((error) => {
        console.log('error while collectin Qids');
        console.log(error);
      });
  }
}