문제(출처: 프로그래머스)

머쓱이는 친구들과 동그랗게 서서 공 던지기 게임을 하고 있습니다. 공은 1번부터 던지며 오른쪽으로 한 명을 건너뛰고 그다음 사람에게만 던질 수 있습니다. 친구들의 번호가 들어있는 정수 배열 numbers와 정수 K가 주어질 때, k번째로 공을 던지는 사람의 번호는 무엇인지 return 하도록 solution 함수를 완성해보세요.

 

▶ 내가 푼 방식

function solution(numbers, k) {
    return numbers[(k - 1) * 2 % numbers.length]
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(numbers, k) {
    return numbers[(--k*2)%numbers.length];
}

// 유저 2
function solution(numbers, k) {
    const [idx, len] = [k * 2 - 1, numbers.length];
    const findIdx = idx >= len ? idx % len : idx;
    return findIdx;
}

 

 배운 것들

     -  k 번째로 던진 사람이므로  k-1 , 한 사람씩 건너뛰므로 2를 곱해 준다.

     -  배열이므로 배열의 크기로 나누어서 나오는 나머지를 이용하여 위치 확인

     - 

문제(출처: 프로그래머스)

정수 배열 num_list와 정수 n이 매개변수로 주어집니다. num_list를 다음 설명과 같이 2차원 배열로 바꿔 return하도록 solution 함수를 완성해주세요.

num_list가 [1, 2, 3, 4, 5, 6, 7, 8] 로 길이가 8이고 n이 2이므로 num_list를 2 * 4 배열로 다음과 같이 변경합니다. 2차원으로 바꿀 때에는 num_list의 원소들을 앞에서부터 n개씩 나눠 2차원 배열로 변경합니다.

 

▶ 내가 푼 방식

function solution(num_list, n) {
    var answer = [];
    let temp = [];
    let cnt = 0
    for ( i of num_list){
        temp.push(i)
        cnt += 1
        if (cnt == n){
            answer.push(temp)
            cnt = 0
            temp = []
        }      
    }
    return answer;
}

 

 다른 유저가 푼 방식

// 유저 1 splice 를 이용한 방법
function solution(num_list, n) {
    var answer = [];

    while(num_list.length) {
        answer.push(num_list.splice(0,n));
    }

    return answer;
}

 

 배운 것들

     -  array.splice(시작점, 개수) 시작점 부터 갯수 만큼 잘라내기

     - 

문제 발생 상황

user 와 게시물의 1:N 관계를 맺은 후 

게시물을 올리는 유저의 이 메일을 이용하여 유저정보를 검색하려는 상황에서 발생

 

코드

board.service.ts

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { WriteBoardRequestDto } from './dto/writeBoard.request.dto';
import { WriteBoardResponseDto } from './dto/writeBoard.response.dto';
import { DataSource, Repository } from 'typeorm';
import { Board } from './board.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { UpdateBoardRequestDto } from './dto/updateBoard.request.dto';
import { UpdateBoardResponseDto } from './dto/updateBoard.response.dto';
import { SearchKeywordBoardResponseDto } from './dto/searchKeywordBoard.response.dto';
import { User } from '../User.entity';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
import { AppModule } from '../app.module';

@Injectable()
export class BoardService {
  constructor(
    @InjectRepository(Board)
    private readonly boardRepository: Repository<Board>,
  ) {}

  async write(
    writeBoardRequestDto: WriteBoardRequestDto,
  ): Promise<WriteBoardResponseDto> {
    const { title, content, email } = writeBoardRequestDto;

    const dataSource = new DataSource({
      type: 'mysql',
      host: 'localhost', //'127.0.0.1',
      port: 3306,
      username: 'root',
      password: '',
      database: 'test_typeORM',
      entities: [User],
      synchronize: false, // true : 동기화가 되지만 데이터가 다 날라간다.
      logging: true,
      namingStrategy: new SnakeNamingStrategy(),
    });

    const userRepository = dataSource.getRepository(User);
    const user = await userRepository.findOne({ where: { email: email } }); // 에러 발생

    const newMessage = new Board();
    newMessage.title = title;
    newMessage.content = content;
    newMessage.user = postingUser;

    const savedBoard = await this.boardRepository.save(newMessage);

    return new WriteBoardResponseDto(
      savedBoard.id,
      savedBoard.title,
      savedBoard.content,
      savedBoard.user,
    );
  }

 

에러메세지

ERROR [ExceptionsHandler] No metadata for "User" was found.
EntityMetadataNotFoundError: No metadata for "User" was found.

 

에러발생 위치 및 원인 파악

 

User 의 위치를 확인해보니 위치는 맞았다.

User 엔티티가 잘못되었나 해서 유저를 생성하는 서비스에서 확인을 해보니 잘 생성되었다.

그러면 문제는 userRepository를 생성하는 과정에서 문제가 있다는 걸로 확인하고

 

해결 시도 1

constructor 에 추가를 해보았다.

constructor(
    @InjectRepository(Board)
    private readonly boardRepository: Repository<Board>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

 

이렇게 선언을 하고 나니 서버자체가 실행되지 않았다.

 

에러메세지

Nest can't resolve dependencies of the BoardService (BoardRepository, ?). Please make sure that the argument "UserRepository" at index [1] is available in the BoardModule context.

 

.... 두개의 레포지터리를 사용하는 것이 안되나 보다

 

해결 시도 2

TypeORM 공식문서에서 레포지토리를 사용하는 다른 방법을 찾아보았다.

https://www.npmjs.com/package/typeorm

 

ActiveRecord implementation 를 하는 방법이 있다는 것을 발견

// user.entity.ts

@Entity('users') //생성할 데이터 테이블의 이름을 적는다.
export class User {
	// 코드...
}

// 아래로 변경 extends BaseEntity 추가
export class User extends BaseEntity {
	// 코드...
}

 

이제 아래와 같이 사용이 가능하다.

const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.age = 25
await user.save()

const allUsers = await User.find()
const firstUser = await User.findOneBy({
    id: 1,
})
const timber = await User.findOneBy({
    firstName: "Timber",
    lastName: "Saw"
})

await timber.remove()

 

일단은 해결이 되었다. 

'프로그래밍 > Nest.js' 카테고리의 다른 글

[ NestJS ] [TypeORM ] N : M 관계 형성  (0) 2024.04.27
[ NestJS ] [ TypeORM ] 1: N 관계 형성, 수정, 삭제  (0) 2024.04.27
[ NestJS ] Modules  (0) 2024.04.18
[ NestJS ] Providers  (0) 2024.04.18
[NestJS] TypeORM 설정방법  (0) 2024.04.17

문제(출처: 프로그래머스)

머쓱이는 구슬을 친구들에게 나누어주려고 합니다. 구슬은 모두 다르게 생겼습니다. 머쓱이가 갖고 있는 구슬의 개수 balls와 친구들에게 나누어 줄 구슬 개수 share이 매개변수로 주어질 때, balls개의 구슬 중 share개의 구슬을 고르는 가능한 모든 경우의 수를 return 하는 solution 함수를 완성해주세요.

 

▶ 내가 푼 방식

function factorial(n) {
  return n ? n * factorial(n - 1) : 1;
}

function solution(balls, share) {
    return Math.round(factorial(balls) / (factorial(balls-share) * factorial(share)))
}

 

 다른 유저가 푼 방식

// 유저 1

function solution(balls, share) {
    var result = 1;
    while(share > 0){
        result = result * balls / share;
        balls = balls - 1;
        share = share - 1;
    }
    return Math.round(result);
}

 

 배운 것들

     -  오류가 나서 혹시나 해서 Math.round() 를 했는데 정답이였다 어떤 예가 있을까??

             부동소수점이 나올수도 있어서 일듯하다.

     -  n!/ (n-m)! m! -> n 개에서 서로 다른 m 개를 고르는 경우의 수 구하는 공식

문제(출처: 프로그래머스)

머쓱이는 친구에게 모스부호를 이용한 편지를 받았습니다. 그냥은 읽을 수 없어 이를 해독하는 프로그램을 만들려고 합니다. 문자열 letter가 매개변수로 주어질 때, letter를 영어 소문자로 바꾼 문자열을 return 하도록 solution 함수를 완성해보세요.

 

▶ 내가 푼 방식

morse = { 
    '.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f',
    '--.':'g','....':'h','..':'i','.---':'j','-.-':'k','.-..':'l',
    '--':'m','-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r',
    '...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x',
    '-.--':'y','--..':'z'}

function solution(letter) {
    var answer = '';
    let letters = letter.split(' ');
    for (let i of letters){
        answer += morse[i]
    }
    return answer;
}

 

 다른 유저가 푼 방식

// 유저 1

function solution(letter) {
    return letter.split(' ').reduce((prev, curr) => prev + morse[curr], '')
}

// 유저 2
function solution(letter) {
    return letter.split(' ').map(v=>morse[v]).join('');
}

// 유저 3

 

 배운 것들

     -  reduce 가 숫자 연산뿐만아니라 문자도 가능

     - 

+ Recent posts