Promise 순차적 실행

코드깎는 노인·2021년 6월 3일
0
post-custom-banner
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { IContext, MutationReturn } from 'src/_shared/common/dtos/common.dto';
import { MeetingFile } from 'src/file-manager/entities/meetingFile.entity';
import { Connection, Repository } from 'typeorm';
import { UpdateMeetingInputDto } from '../dtos/meeting.dto';
import { Meeting } from '../entites/meeting.entity';
import e from 'express';
import { CopyFileService } from 'src/file-manager/services/copyFile.service';
import { FILETYPE } from 'src/_shared/common/types/customTypes';

@Injectable()
export class UpdateMeetingService {
  constructor(
    @InjectRepository(Meeting)
    private readonly meetingRepository: Repository<Meeting>,
    @InjectRepository(MeetingFile)
    private readonly meetingFileRepository: Repository<MeetingFile>,
    private readonly connection: Connection,
    private readonly copyFileService: CopyFileService,
  ) {}

  private async updateMyMeeting(
    args: UpdateMeetingInputDto & IContext,
  ): Promise<MutationReturn> {
    const { id } = await args;
    let queryRunner = this.connection.createQueryRunner();
    try {
      console.log('startUpdateMeeting');
      queryRunner = this.connection.createQueryRunner();
      await queryRunner.connect();
      await queryRunner.startTransaction();
      let entryIds: any[] = [];
      if (args.entry) {
        entryIds = args.entry.map((id) => {
          return { id };
        });
      }
      const meeting = await this.meetingRepository.findOneOrFail({
        where: { id: args.id },
        relations: ['meetingLogFolder', 'meetingFiles'],
      });
      meeting.meetingFiles = [];
      if (args.title) meeting.title = args.title;
      if (args.content) meeting.content = args.content;
      if (args.entry && args.entry.length) meeting.users = entryIds;
      if (args.startedAt) meeting.startedAt = args.startedAt;
      if (args.finishedAt) meeting.endedAt = args.finishedAt;
      await queryRunner.manager.save(meeting);
      if (args.localFiles && args.localFiles.length > 0) {
        // args.localFiles.forEach(async (data) => {
        //   const meetingFile = this.meetingFileRepository.create({
        //     meeting: { id: meeting.id },
        //     fileManager: { id: data.id },
        //   });
        //   await queryRunner.manager.save(meetingFile);
        // });
        for (const data of args.localFiles) {
          const meetingFile = this.meetingFileRepository.create({
            meeting: { id: meeting.id },
            fileManager: { id: data.id },
          });
          await queryRunner.manager.save(meetingFile);
        }
      }

      if (args.existedFileIds && args.existedFileIds.length > 0) {
        // args.existedFileIds.forEach(async (existedFileId) => {
        //   const existed = await this.meetingFileRepository.findOne({
        //     where: {
        //       fileManager: { id: existedFileId },
        //     },
        //   });
        //   if (!existed) {
        //     const meetingFile = this.meetingFileRepository.create({
        //       meeting: { id: meeting.id },
        //       fileManager: { id: existedFileId },
        //     });
        //     await queryRunner.manager.save(meetingFile);
        //   } else {
        //     existed.meeting = meeting;
        //     await queryRunner.manager.save(existed);
        //   }
        // });

        for (const existedFileId of args.existedFileIds) {
          const existed = await this.meetingFileRepository.findOne({
            where: {
              fileManager: { id: existedFileId },
            },
          });
          if (!existed) {
            const meetingFile = this.meetingFileRepository.create({
              meeting: { id: meeting.id },
              fileManager: { id: existedFileId },
            });
            await queryRunner.manager.save(meetingFile);
          } else {
            existed.meeting = meeting;
            await queryRunner.manager.save(existed);
          }
        }
      }

      if (args.userFileIds && args.userFileIds.length > 0) {
        // args.userFileIds.forEach(async (userFileId) => {
        //   await this.copyFileService.copyFile({
        //     id: userFileId,
        //     type: FILETYPE.MEETING_FILE,
        //     meetingId: args.id,
        //   });
        // });
        for (const userFileId of args.userFileIds) {
          await this.copyFileService.copyFile({
            id: userFileId,
            type: FILETYPE.MEETING_FILE,
            meetingId: args.id,
          });
        }
      }
      await queryRunner.commitTransaction();
      console.log('finishUpdateMeeting');
      return {
        success: true,
        error: null,
      };
    } catch (error) {
      await queryRunner.rollbackTransaction();
      console.log(error);
      return {
        success: false,
        error: error,
      };
    } finally {
      console.log('UpdateMeetingRelease');
      await queryRunner.release();
    }
  }

  private async finish(
    mutationReturn: MutationReturn,
  ): Promise<MutationReturn> {
    return mutationReturn;
  }

  public async updateMeeting({
    ...args
  }: UpdateMeetingInputDto & IContext): Promise<MutationReturn> {
    return Promise.resolve(this.updateMyMeeting(args)).then(
      this.finish.bind(this),
    );
  }
}

forEach로 promise를 실행하니 promise를 기다리지 순차적으로 실행(기다리지 않음)되지 않고 finally의
release가 실행되어 forEach반복문의 다음 쿼리가 실행되지 않았다.순차적으로 실행시키고자 한다면 for..of loop나
Promise.all로 처리한다.
참고
https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop

profile
내가 볼려고 만든 블로그
post-custom-banner

0개의 댓글