Skip to content
Snippets Groups Projects
Select Git revision
  • ddcc7df9e17bef22d1fcb219be07128af87368ee
  • main default protected
2 results

myService.js

Blame
  • myService.js 3.29 KiB
    import { Redis } from '../redis.js';
    import { ReportableError } from '../errors.js';
    import myRepository from '../repositories/myRepository.js';
    import crypto from 'crypto';
    
    const myService = {
      generateCode() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        let code = '';
        for (let i = 0; i < 12; i++) {
          code += chars[Math.floor(Math.random() * chars.length)];
        }
        return code;
      },
    
      async getUserIdFromCode(code) {
        const redisKey = `mypc:code:${code}:user_id`;
        const userId = await Redis.get(redisKey);
    
        if (!userId) {
          throw new ReportableError(401, '유효하지 않은 코드입니다.');
        }
    
        return userId;
      },
    
      async saveDocument(code, xml) {
        const redisKey = `mypc:code:${code}:document`;
        const userIdKey = `mypc:code:${code}:user_id`;
        const queueKey = 'mypc:queue';
        const transactionIdKey = `mypc:code:${code}:transaction_id`;
    
        const transactionId = crypto.randomBytes(6).toString('hex');
    
        try {
          const userId = await Redis.get(userIdKey);
          if (!userId) {
            throw new ReportableError(
              404,
              '해당 코드와 연결된 사용자 ID를 찾을 수 없습니다.'
            );
          }
    
          await Redis.set(redisKey, xml, 'EX', 600);
    
          await Redis.set(transactionIdKey, transactionId, 'EX', 600);
    
          await Redis.lPush(queueKey, code);
    
          await myRepository.saveTransaction(userId, transactionId);
        } catch (err) {
          throw new ReportableError(500, err.toString());
        }
      },
    
      async createRegistrationCode(userId) {
        if (!userId) {
          throw new ReportableError(400, '사용자 ID가 필요합니다.');
        }
    
        const code = this.generateCode();
        const redisKey = `mypc:code:${code}:user_id`;
        const redisValue = userId;
    
        try {
          await Redis.set(redisKey, redisValue, 'EX', 600);
        } catch {
          throw new ReportableError(
            500,
            '등록 코드를 생성하는 중 문제가 발생했습니다.'
          );
        }
    
        return { code };
      },
    
      async getCombinationId(req, res) {
        const { code } = req.params;
        const transactionIdKey = `mypc:code:${code}:transectionId`;
    
        try {
          const transactionId = await Redis.get(transactionIdKey);
          if (!transactionId) {
            throw new ReportableError(
              404,
              '해당 코드와 연결된 트랜잭션 ID를 찾을 수 없습니다.'
            );
          }
    
          const combinationId =
            await myRepository.getCombinationIdByTransactionId(transactionId);
    
          res.sendResponse('', 200, {
            combinationId: combinationId || null,
          });
        } catch {
          throw new ReportableError(
            500,
            '등록 코드 상태를 확인하는 중 문제가 발생했습니다.'
          );
        }
      },
    
      async getUserPCs(userId) {
        if (!userId) {
          throw new ReportableError(400, '유효한 사용자 ID가 필요합니다.');
        }
    
        const combinations = await myRepository.getCombinationsByUserId(userId);
    
        const pcs = await Promise.all(
          combinations.map(async (combination) => {
            const partIds = await myRepository.getPartIdsByCombinationId(
              combination?.id
            );
    
            return {
              id: combination.id,
              name: combination.name,
              parts: partIds,
            };
          })
        );
    
        return pcs;
      },
    };
    
    export default myService;