Browse Source

Merge branch 'feat/7015-cache-CRUD' into fix/7183-enable-view-submission-in-check-command-permission-middleware

Taichi Masuyama 4 years ago
parent
commit
22cb248ab5

+ 15 - 15
packages/slackbot-proxy/src/controllers/growi-to-slack.ts

@@ -113,12 +113,12 @@ export class GrowiToSlackCtrl {
     const tokenGtoP = tokenGtoPs[0];
 
     // MOCK DATA MODIFY THIS GW 6972 -----------
-    const relationMock = await this.relationMockRepository.update(
+    const relation = await this.relationMockRepository.update(
       { tokenGtoP }, { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands },
     );
     // MOCK DATA MODIFY THIS GW 6972 -----------
 
-    return res.send({ relationMock });
+    return res.send({ relation });
   }
 
   @Post('/relation-test')
@@ -133,22 +133,22 @@ export class GrowiToSlackCtrl {
     const tokenGtoP = tokenGtoPs[0];
 
     // retrieve relation with Installation
-    const relationMock = await this.relationMockRepository.createQueryBuilder('relation_mock')
+    const relation = await this.relationMockRepository.createQueryBuilder('relation')
       .where('tokenGtoP = :token', { token: tokenGtoP })
-      .leftJoinAndSelect('relation_mock.installation', 'installation')
+      .leftJoinAndSelect('relation.installation', 'installation')
       .getOne();
 
     // Returns the result of the test if it already exists
-    if (relationMock != null) {
-      logger.debug('relation found', relationMock);
+    if (relation != null) {
+      logger.debug('relation found', relation);
 
-      const token = relationMock.installation.data.bot?.token;
+      const token = relation.installation.data.bot?.token;
       if (token == null) {
         throw createError(400, 'installation is invalid');
       }
 
       try {
-        await this.requestToGrowi(relationMock.growiUri, relationMock.tokenPtoG);
+        await this.requestToGrowi(relation.growiUri, relation.tokenPtoG);
       }
       catch (err) {
         logger.error(err);
@@ -160,7 +160,7 @@ export class GrowiToSlackCtrl {
         throw createError(400, `failed to get connection. err: ${status.error}`);
       }
 
-      return res.send({ relationMock, slackBotToken: token });
+      return res.send({ relation, slackBotToken: token });
     }
 
     // retrieve latest Order with Installation
@@ -205,7 +205,7 @@ export class GrowiToSlackCtrl {
      * this code represents the creation of cache (Relation schema) using request from GROWI
      */
     // Transaction is not considered because it is used infrequently
-    const response = await this.relationMockRepository.createQueryBuilder('relation_mock')
+    const response = await this.relationMockRepository.createQueryBuilder('relation')
       .insert()
       .values({
         installation: order.installation,
@@ -227,7 +227,7 @@ export class GrowiToSlackCtrl {
     // Find the generated relation
     const generatedRelationMock = await this.relationMockRepository.findOne({ id: response.identifiers[0].id });
 
-    return res.send({ relationMock: generatedRelationMock, slackBotToken: token });
+    return res.send({ relation: generatedRelationMock, slackBotToken: token });
   }
 
   injectGrowiUri(req: GrowiReq, growiUri: string): void {
@@ -274,16 +274,16 @@ export class GrowiToSlackCtrl {
     const tokenGtoP = tokenGtoPs[0];
 
     // retrieve relation with Installation
-    const relationMock = await this.relationMockRepository.createQueryBuilder('relation')
+    const relation = await this.relationMockRepository.createQueryBuilder('relation')
       .where('tokenGtoP = :token', { token: tokenGtoP })
       .leftJoinAndSelect('relation.installation', 'installation')
       .getOne();
 
-    if (relationMock == null) {
+    if (relation == null) {
       return res.webClientErr('relation is invalid', 'invalid_relation');
     }
 
-    const token = relationMock.installation.data.bot?.token;
+    const token = relation.installation.data.bot?.token;
     if (token == null) {
       return res.webClientErr('installation is invalid', 'invalid_installation');
     }
@@ -291,7 +291,7 @@ export class GrowiToSlackCtrl {
     const client = generateWebClient(token);
 
     try {
-      this.injectGrowiUri(req, relationMock.growiUri);
+      this.injectGrowiUri(req, relation.growiUri);
 
       const opt = req.body;
       opt.headers = req.headers;

+ 25 - 25
packages/slackbot-proxy/src/controllers/slack.ts

@@ -65,21 +65,21 @@ export class SlackCtrl {
    * @param body
    * @returns
    */
-  private async sendCommand(growiCommand: GrowiCommand, relationMocks: RelationMock[], body: any) {
-    if (relationMocks.length === 0) {
+  private async sendCommand(growiCommand: GrowiCommand, relations: RelationMock[], body: any) {
+    if (relations.length === 0) {
       throw new Error('relations must be set');
     }
-    const botToken = relationMocks[0].installation?.data.bot?.token; // relations[0] should be exist
+    const botToken = relations[0].installation?.data.bot?.token; // relations[0] should be exist
 
-    const promises = relationMocks.map((relationMock: RelationMock) => {
+    const promises = relations.map((relation: RelationMock) => {
       // generate API URL
-      const url = new URL('/_api/v3/slack-integration/proxied/commands', relationMock.growiUri);
+      const url = new URL('/_api/v3/slack-integration/proxied/commands', relation.growiUri);
       return axios.post(url.toString(), {
         ...body,
         growiCommand,
       }, {
         headers: {
-          'x-growi-ptog-tokens': relationMock.tokenPtoG,
+          'x-growi-ptog-tokens': relation.tokenPtoG,
         },
       });
     });
@@ -136,12 +136,12 @@ export class SlackCtrl {
     const installationId = authorizeResult.enterpriseId || authorizeResult.teamId;
     // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
     const installation = await this.installationRepository.findByTeamIdOrEnterpriseId(installationId!);
-    const relationMocks = await this.relationMockRepository.createQueryBuilder('relation_mock')
-      .where('relation_mock.installationId = :id', { id: installation?.id })
-      .leftJoinAndSelect('relation_mock.installation', 'installation')
+    const relations = await this.relationMockRepository.createQueryBuilder('relation')
+      .where('relation.installationId = :id', { id: installation?.id })
+      .leftJoinAndSelect('relation.installation', 'installation')
       .getMany();
 
-    if (relationMocks.length === 0) {
+    if (relations.length === 0) {
       return res.json({
         blocks: [
           markdownSectionBlock('*No relation found.*'),
@@ -155,7 +155,7 @@ export class SlackCtrl {
       return res.json({
         blocks: [
           markdownSectionBlock('*Found Relations to GROWI.*'),
-          ...relationMocks.map(relationMock => markdownSectionBlock(`GROWI url: ${relationMock.growiUri}`)),
+          ...relations.map(relation => markdownSectionBlock(`GROWI url: ${relation.growiUri}`)),
         ],
       });
     }
@@ -166,40 +166,40 @@ export class SlackCtrl {
 
     const baseDate = new Date();
 
-    const relationMocksForSingleUse:RelationMock[] = [];
-    await Promise.all(relationMocks.map(async(relationMock) => {
-      const isSupported = await this.relationsService.isSupportedGrowiCommandForSingleUse(relationMock, growiCommand.growiCommandType, baseDate);
+    const relationsForSingleUse:RelationMock[] = [];
+    await Promise.all(relations.map(async(relation) => {
+      const isSupported = await this.relationsService.isSupportedGrowiCommandForSingleUse(relation, growiCommand.growiCommandType, baseDate);
       if (isSupported) {
-        relationMocksForSingleUse.push(relationMock);
+        relationsForSingleUse.push(relation);
       }
     }));
 
     let isCommandPermitted = false;
 
-    if (relationMocksForSingleUse.length > 0) {
+    if (relationsForSingleUse.length > 0) {
       isCommandPermitted = true;
-      body.growiUrisForSingleUse = relationMocksForSingleUse.map(v => v.growiUri);
+      body.growiUrisForSingleUse = relationsForSingleUse.map(v => v.growiUri);
       return this.selectGrowiService.process(growiCommand, authorizeResult, body);
     }
 
-    const relationMocksForBroadcastUse:RelationMock[] = [];
-    await Promise.all(relationMocks.map(async(relationMock) => {
-      const isSupported = await this.relationsService.isSupportedGrowiCommandForBroadcastUse(relationMock, growiCommand.growiCommandType, baseDate);
+    const relationsForBroadcastUse:RelationMock[] = [];
+    await Promise.all(relations.map(async(relation) => {
+      const isSupported = await this.relationsService.isSupportedGrowiCommandForBroadcastUse(relation, growiCommand.growiCommandType, baseDate);
       if (isSupported) {
-        relationMocksForBroadcastUse.push(relationMock);
+        relationsForBroadcastUse.push(relation);
       }
     }));
 
     /*
      * forward to GROWI server
      */
-    if (relationMocksForBroadcastUse.length > 0) {
+    if (relationsForBroadcastUse.length > 0) {
       isCommandPermitted = true;
-      this.sendCommand(growiCommand, relationMocksForBroadcastUse, body);
+      this.sendCommand(growiCommand, relationsForBroadcastUse, body);
     }
 
     if (!isCommandPermitted) {
-      const botToken = relationMocks[0].installation?.data.bot?.token;
+      const botToken = relations[0].installation?.data.bot?.token;
 
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
       const client = generateWebClient(botToken!);
@@ -265,7 +265,7 @@ export class SlackCtrl {
     // forward to GROWI server
     if (callBackId === 'select_growi') {
       const selectedGrowiInformation = await this.selectGrowiService.handleSelectInteraction(installation, payload);
-      return this.sendCommand(selectedGrowiInformation.growiCommand, [selectedGrowiInformation.relationMock], selectedGrowiInformation.sendCommandBody);
+      return this.sendCommand(selectedGrowiInformation.growiCommand, [selectedGrowiInformation.relation], selectedGrowiInformation.sendCommandBody);
     }
 
     /*

+ 21 - 21
packages/slackbot-proxy/src/services/RelationsService.ts

@@ -15,43 +15,43 @@ export class RelationsService {
   @Inject()
   relationMockRepository: RelationMockRepository;
 
-  async getSupportedGrowiCommands(relationMock:RelationMock):Promise<any> {
+  async getSupportedGrowiCommands(relation:RelationMock):Promise<any> {
     // generate API URL
-    const url = new URL('/_api/v3/slack-integration/supported-commands', relationMock.growiUri);
+    const url = new URL('/_api/v3/slack-integration/supported-commands', relation.growiUri);
     return axios.get(url.toString(), {
       headers: {
-        'x-growi-ptog-tokens': relationMock.tokenPtoG,
+        'x-growi-ptog-tokens': relation.tokenPtoG,
       },
     });
   }
 
-  async syncSupportedGrowiCommands(relationMock:RelationMock): Promise<RelationMock> {
-    const res = await this.getSupportedGrowiCommands(relationMock);
+  async syncSupportedGrowiCommands(relation:RelationMock): Promise<RelationMock> {
+    const res = await this.getSupportedGrowiCommands(relation);
 
     // MOCK DATA MODIFY THIS GW-6972 ---------------
     /**
      * this code represents the update of cache (Relation schema) using request from GROWI
      */
     const { permissionsForBroadcastUseCommands, permissionsForSingleUseCommands } = res.data.data;
-    if (relationMock !== null) {
-      relationMock.permissionsForBroadcastUseCommands = permissionsForBroadcastUseCommands;
-      relationMock.permissionsForSingleUseCommands = permissionsForSingleUseCommands;
-      relationMock.expiredAtCommands = addHours(new Date(), 48);
-      return this.relationMockRepository.save(relationMock);
+    if (relation !== null) {
+      relation.permissionsForBroadcastUseCommands = permissionsForBroadcastUseCommands;
+      relation.permissionsForSingleUseCommands = permissionsForSingleUseCommands;
+      relation.expiredAtCommands = addHours(new Date(), 48);
+      return this.relationMockRepository.save(relation);
     }
-    throw Error('No relation mock exists.');
+    throw Error('No relation exists.');
     // MOCK DATA MODIFY THIS GW-6972 ---------------
   }
 
   // MODIFY THIS METHOD USING ORIGINAL RELATION MODEL GW-6972
-  async syncRelation(relationMock:RelationMock, baseDate:Date):Promise<RelationMock|null> {
-    if (relationMock == null) return null;
+  async syncRelation(relation:RelationMock, baseDate:Date):Promise<RelationMock|null> {
+    if (relation == null) return null;
 
-    const distanceMillisecondsToExpiredAt = relationMock.getDistanceInMillisecondsToExpiredAt(baseDate);
+    const distanceMillisecondsToExpiredAt = relation.getDistanceInMillisecondsToExpiredAt(baseDate);
 
     if (distanceMillisecondsToExpiredAt < 0) {
       try {
-        return await this.syncSupportedGrowiCommands(relationMock);
+        return await this.syncSupportedGrowiCommands(relation);
       }
       catch (err) {
         logger.error(err);
@@ -62,18 +62,18 @@ export class RelationsService {
     // 24 hours
     if (distanceMillisecondsToExpiredAt < 24 * 60 * 60 * 1000) {
       try {
-        this.syncSupportedGrowiCommands(relationMock);
+        this.syncSupportedGrowiCommands(relation);
       }
       catch (err) {
         logger.error(err);
       }
     }
 
-    return relationMock;
+    return relation;
   }
 
-  async isSupportedGrowiCommandForSingleUse(relationMock:RelationMock, growiCommandType:string, baseDate:Date):Promise<boolean> {
-    const syncedRelation = await this.syncRelation(relationMock, baseDate);
+  async isSupportedGrowiCommandForSingleUse(relation:RelationMock, growiCommandType:string, baseDate:Date):Promise<boolean> {
+    const syncedRelation = await this.syncRelation(relation, baseDate);
     if (syncedRelation == null) {
       return false;
     }
@@ -83,8 +83,8 @@ export class RelationsService {
     // MOCK DATA THIS CODE SHOULD BE IMPLEMENTED IN GW-7017
   }
 
-  async isSupportedGrowiCommandForBroadcastUse(relationMock:RelationMock, growiCommandType:string, baseDate:Date):Promise<boolean> {
-    const syncedRelation = await this.syncRelation(relationMock, baseDate);
+  async isSupportedGrowiCommandForBroadcastUse(relation:RelationMock, growiCommandType:string, baseDate:Date):Promise<boolean> {
+    const syncedRelation = await this.syncRelation(relation, baseDate);
     if (syncedRelation == null) {
       return false;
     }

+ 7 - 7
packages/slackbot-proxy/src/services/SelectGrowiService.ts

@@ -10,7 +10,7 @@ import { RelationMockRepository } from '~/repositories/relation-mock';
 
 
 export type SelectedGrowiInformation = {
-  relationMock: RelationMock,
+  relation: RelationMock,
   growiCommand: GrowiCommand,
   sendCommandBody: any,
 }
@@ -93,19 +93,19 @@ export class SelectGrowiService implements GrowiCommandProcessor {
     // ovverride trigger_id
     sendCommandBody.trigger_id = triggerId;
 
-    const relationMock = await this.relationMockRepository.createQueryBuilder('relation_mock')
-      .where('relation_mock.growiUri =:growiUri', { growiUri })
-      .andWhere('relation_mock.installationId = :id', { id: installation?.id })
-      .leftJoinAndSelect('relation_mock.installation', 'installation')
+    const relation = await this.relationMockRepository.createQueryBuilder('relation')
+      .where('relation.growiUri =:growiUri', { growiUri })
+      .andWhere('relation.installationId = :id', { id: installation?.id })
+      .leftJoinAndSelect('relation.installation', 'installation')
       .getOne();
 
-    if (relationMock == null) {
+    if (relation == null) {
       // TODO: postEphemeralErrors
       throw new Error('No relation found.');
     }
 
     return {
-      relationMock,
+      relation,
       growiCommand,
       sendCommandBody,
     };