Advertisement
Guest User

Janus.ts

a guest
May 11th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // import { EntityType, RelationType } from 'kpb-core-pkg';
  2. import * as request from 'request-promise-native';
  3. import { Logger, LoggerCst } from 'kpb-logger-pkg';
  4. // import * as tagProcesser from './tagFunctions';
  5. import { EntityInterface, RelationInterface, VertexInterface, EdgeInterface, ResponsedPath } from './graphInterfaces';
  6. import { formatBasicProperties, gremlinQuery, formatAddRelationProperties, buildAddVertexQuery, buildAddRelationQuery, buildCountVerticesQuery, buildGetVerticesQuery, buildGetRelationsQuery, formatFindPathProperties, buildFindPathQuery } from './gremlinQueryBuilder';
  7.  
  8. process.env.LOGGER_LVL = 'info';
  9.  
  10. const log: Logger = new Logger('Janus.ts', LoggerCst.LEVELS[process.env.LOGGER_LVL]);
  11.  
  12. export class Janus {
  13.   constructor(
  14.     private _graphName: string,
  15.     private _host: string,
  16.     private _port: number,
  17.     private _username: string,
  18.     private _password: string,
  19.     private _token: string,
  20.   ) { }
  21.  
  22.   get graphName(): string {
  23.     return this._graphName;
  24.   }
  25.   get host(): string {
  26.     return this._host;
  27.   }
  28.   get port(): number {
  29.     return this._port;
  30.   }
  31.   get username(): string {
  32.     return this._username;
  33.   }
  34.   get password(): string {
  35.     return this._password;
  36.   }
  37.   get token(): string {
  38.     return this._token;
  39.   }
  40.  
  41.   set token(token) {
  42.     this._token = token;
  43.   }
  44.  
  45.   static async refreshToken(
  46.     username: string,
  47.     password: string,
  48.     host: string,
  49.     port: number,
  50.   ): Promise<request.RequestPromise> {
  51.     const baseUrl: string = `https://${username}:${password}@${host}:${port}/session`;
  52.     const options = {
  53.       uri: baseUrl,
  54.       json: true,
  55.       resolveWithFullResponse: true,
  56.     };
  57.     return await request.get(options);
  58.   }
  59.  
  60.   static async authenticate(
  61.     host: string,
  62.     port: number,
  63.     username: string,
  64.     password: string,
  65.     graphName: string,
  66.   ): Promise<Janus> {
  67.     const response = await this.refreshToken(username, password, host, port);
  68.     const token = response.body.token;
  69.     return new Janus(graphName, host, port, username, password, token);
  70.   }
  71.  
  72.   async createGraph(graphName: string): Promise<string> {
  73.     try {
  74.       const response =
  75.         await gremlinQuery(this, `def g=ConfiguredGraphFactory.create('${graphName}');0;`);
  76.       if (response.body.status.code === 200) {
  77.         return `${graphName} created!`;
  78.       }
  79.     } catch {
  80.       return `${graphName} already exists.`;
  81.     }
  82.   }
  83.  
  84.   async addVertex(entity: EntityInterface): Promise<VertexInterface> {
  85.     const formatedProperties = formatBasicProperties(entity);
  86.     const query = buildAddVertexQuery(this, formatedProperties);
  87.     try {
  88.       if (!(await this.vertexExists(entity))) {
  89.         const response = await gremlinQuery(this, query);
  90.         if (response.body.status.code === 200) {
  91.           log.info('Vertex inserted.');
  92.           return response.body.result.data;
  93.         }
  94.       }
  95.       log.info('Vertex already exists, skipping insert...');
  96.     } catch {
  97.       log.error('Error occured while adding a Vertex');
  98.     }
  99.   }
  100.  
  101.   async addRelation(relation: RelationInterface): Promise<EdgeInterface> {
  102.     const v1 = `def v1 = g.V().has('entity_id', '${relation.in_entity_id}').next();`;
  103.     const v2 = `def v2 = g.V().has('entity_id', '${relation.out_entity_id}').next();`;
  104.     const formatedProperties = formatAddRelationProperties(relation);
  105.     const query = buildAddRelationQuery(this, v1, v2, formatedProperties);
  106.     try {
  107.       if (!(await this.relationExists(relation))) {
  108.         const response = await gremlinQuery(this, query);
  109.         if (response.body.status.code === 200) {
  110.           log.info('Relation inserted.');
  111.           return response.body.result.data;
  112.         }
  113.       }
  114.       log.info('Relation already exists, skipping insert...');
  115.     } catch {
  116.       log.error('Error occured while adding a Relation. Non existant entites ID?');
  117.     }
  118.  
  119.   }
  120.  
  121.   async insertKpbDocument(kpbDocument): Promise<any> {
  122.     // const entityTypes: EntityType[] = typeSystem.entity_types;
  123.     // const relationTypes: RelationType[] = typeSystem.relation_types;
  124.     await kpbDocument.doc.annotations.map(async (annotation) => {
  125.       await Promise.all(annotation.entities.map(async (entity) => {
  126.         // const formattedEntity = tagProcesser.processEntityTags(entity, entityTypes);
  127.         await this.addVertex(entity);
  128.       }));
  129.       await Promise.all(annotation.relations.map(async (relation) => {
  130.         // const formattedRelation = tagProcesser.processRelationTags(relation, relationTypes);
  131.         await this.addRelation(relation);
  132.       }));
  133.     });
  134.     return kpbDocument;
  135.   }
  136.  
  137.   async relationExists(relation: RelationInterface): Promise<boolean> {
  138.     const nbRelations = await this.countRelations(relation);
  139.     if (nbRelations !== 0) {
  140.       return true;
  141.     }
  142.     return false;
  143.   }
  144.  
  145.   async countRelations(properties): Promise<number> {
  146.     const formatedProperties = formatBasicProperties(properties);
  147.     const query = buildCountVerticesQuery(this, formatedProperties);
  148.     try {
  149.       const response = await gremlinQuery(this, query);
  150.       return response.body.result.data[0];
  151.     } catch {
  152.       return 0;
  153.     }
  154.   }
  155.  
  156.   async vertexExists(entity: EntityInterface): Promise<boolean> {
  157.     const nbVertices = await this.countVertices(entity);
  158.     if (nbVertices !== 0) {
  159.       return true;
  160.     }
  161.     return false;
  162.   }
  163.  
  164.   async countVertices(properties): Promise<number> {
  165.     const formatedProperties = formatBasicProperties(properties);
  166.     const query = buildCountVerticesQuery(this, formatedProperties);
  167.     try {
  168.       const response = await gremlinQuery(this, query);
  169.       return response.body.result.data[0];
  170.     } catch {
  171.       return 0;
  172.     }
  173.   }
  174.  
  175.   async getVertices(properties): Promise<VertexInterface[]> {
  176.     const formatedProperties = formatBasicProperties(properties);
  177.     const query = buildGetVerticesQuery(this, formatedProperties);
  178.     const response = await gremlinQuery(this, query);
  179.     return response.body.result.data;
  180.   }
  181.  
  182.   async getRelations(properties): Promise<RelationInterface[]> {
  183.     delete properties.start;
  184.     delete properties.end;
  185.     const formatedProperties = formatBasicProperties(properties);
  186.     const query = buildGetRelationsQuery(this, formatedProperties);
  187.     const response = await gremlinQuery(this, query);
  188.     return response.body.result.data;
  189.   }
  190.  
  191.   async findPath(entities, labels: string[], nbHops: number): Promise<ResponsedPath> {
  192.     const formattedProps = formatFindPathProperties(entities, labels);
  193.     const query = buildFindPathQuery(this, formattedProps, nbHops);
  194.     const response = await gremlinQuery(this, query);
  195.     return response.body.result.data;
  196.   }
  197. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement