Advertisement
Guest User

Janus.ts

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