[Javascript] closure를 활용한 함수 역할 분리

예리에르·2022년 11월 23일
3

JavaScript

목록 보기
7/7
post-thumbnail

개발 동기

사용자 세션을 관리하는 함수중에 사용자 정보를 가져오는 함수가 있다.
이 함수는

  1. 로그인 성공
  2. 일정기간을 두고 세션확인 후 있을때 실행된다.

그런데 중간에 세션이 사라질 때의 재로그인 처리를 한 부분이 있는데, 일정기간 세션을 확인하는 시점에서 로그인시 잠시 세션이 없을 때에도 같이 적용되어 재로그인 문구가 뜨게 되었다.

변경 전 코드

  • 사용자 정보 가져오기
private responseSessionInfo = action((info?: SessionInfo) => {
        if (info) {
            this.userInfo = info;
            this.sessionState = SessionState.Auth;
            this.getRole();
            this.getUsers();
         
        } else {
            // 세션x
          
            this.clearSession();

        }
    })
  • 로그인 성공
private responseLogin = (complete: (result: boolean, message: string) => void) => (info: SessionInfo) => {
        this.responseSessionInfo(info);
        complete(true, '성공');
    }
  • 세션확인
setInterval(this.updateSession, 60 * 5 * 1000);

...

private updateSession = () => {
        if (this.sessionState === SessionState.Auth) {
            requestSession(this.responseSessionInfo, this.completeSessionInfo(true));
        }
    }

수정할 부분은 responseSessionInfo 함수를 트리거를 통해 역할을 분리이다.

변경 후 코드 (closure 적용 - 컬링함수)

  • 사용자 정보 가져오기
 private responseSessionInfo = (showSessionPopup:boolean = false) => action((info?: SessionInfo) => {
        if (info) {
            this.userInfo = info;
            this.sessionState = SessionState.Auth;
            this.getRole();
            this.getUsers();
            this.rootStore.socketStore.sendSocketEvent(SocketRequestType.ChangeNickname, this.socketUserName);
        } else {
            // 세션x
            if(showSessionPopup) {
                this.showSessionDisconnectedPopup = true;
            }
            this.clearSession();

        }
    })
  • 로그인 성공
private responseLogin = (complete: (result: boolean, message: string) => void) => (info: SessionInfo) => {
        this.responseSessionInfo()(info);
        complete(true, '성공');
    }
  • 세션확인
setInterval(this.updateSession, 60 * 5 * 1000);

...

private updateSession = () => {
        if (this.sessionState === SessionState.Auth) {
            requestSession(this.responseSessionInfo(true), this.completeSessionInfo(true));
        }
    }

responseSessionInfo 함수의 외부함수를 만들어 showSessionPopup 이라는 변수를 추가하였다.
기본으로 false값을 설정하였고 true일때 세션이없으면 재로그인 팝업이 뜨게 조건문을 추가하였다.

후기

javascript의 기본 이론이 중요하다는 것은 알고있었으나 실제 개발때 체감을 하지못하고 있었다. 당장 기능을 구현하기 바쁘다는 핑계로 🥲 ㅎ

만약에 closure라는 기능을 쓰지 않았더라면 추가로 복잡한 코드를 작성했을 것 같다. 팀장님의 조언을 통해 적용하였고 기존의 코드에 많은 변화없이 간단하게 코드를 수정할 수 있었다. (팀장님 쵝오...👍👍)

profile
비전공 프론트엔드 개발자의 개발일기😈 ✍️

0개의 댓글