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

myService.js

Blame
  • myService.js 5.92 KiB
    import { Redis } from '../redis.js';
    import { ReportableError } from '../errors.js';
    import myRepository from '../repositories/myRepository.js';
    import ShareRepository from '../repositories/shareRepository.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,