기본 콘텐츠로 건너뛰기

Meteor - Session을 이용한 살아있는 Reactive 게시 시간(moment 사용)

facebook 같은 SNS를 보면 게시글과 댓글의 시간이 실시간으로 갱신되는데
Meteor를 사용하면 불필요한 DOM을 갱신하지 않고 필요한 부분만 적은 코드로 구현할 수 있습니다.

현재 시간 기준으로 얼마나 시간이 흘렀는지 (ex. 5 minute ago) 보여주려면

moment(기준시간).fromNow()
를 사용하면 됩니다.

helper를 만들어보면
<span>{{timeAgo createdAt}}</span>
....
Template.main.helpers({
  ...
  "timeAgo": function(time) {
    return moment(time).fromNow();
  }
});

이와 같이 구현할 수 있죠.

여기에서 우리는 Template의 helper가 Reactive Computation 대상이며Session이 Reactive Data Source라는 점을 사용합니다. (http://docs.meteor.com/#/full/reactivity)

Reactive Computation 대상인 helper 안에서 Session의 값이 갱신되면 helper를 다시 호출하지 않아도 다시 갱신이 되는 것입니다.

1초마다 특정 Session의 값을 갱신하도록 해봅시다.
onCreated에서 interval을 생성하고 onDestroy에서 제거하도록 하여 불필요한 부담을 줄여줍니다.

Template.main.onCreated(function() {
  Session.set("localtime",1);
  this.interval = Meteor.setInterval(function() {
    Session.set("localtime", Random.id());
  }, 1000);
});

....

Template.main.onDestroyed(function() {
  Meteor.clearInterval(this.interval);
});

단지 localtime 이라는 Session에 1초마다 다른 값이 들어오도록 set하는 것으로 모든 준비가 끝났습니다.
Session은 현재 가지고 있는 것과 같은 값이 들어올 경우 불필요한 갱신을 하지 않으므로 항상 다른 값이 들어오도록 Random.id() (https://github.com/meteor/meteor/tree/devel/packages/random) 를 사용해 중복 값을 피합니다. 이는 uuid 값을 생성하여 매번 다른 값을 받습니다. 예전 버전의 Meteor.uuid() 와 동일합니다.

이제 helper를 수정할 차례입니다.

Template.main.helpers({
  ...
  "timeAgo": function(time) {
    return Session.get("localtime") && moment(time).fromNow();
  }
});

이렇게 Session.get 을 추가해줍니다. 그 결과값은 항상 참이므로 &&(and)연산을 통해 항상 이후의 값을 반환합니다.

실제로 Chrome 브라우저에서 변경되는 순간을 보면
이와 같이 두 번째 li 부분이 점멸하면서 해당 DOM이 갱신되는 것처럼 최소한의 변경만 이루어지는 것을 확인할 수 있습니다.

실제로 구현한 소스는 이곳에서 확인하실 수 있습니다.

댓글

이 블로그의 인기 게시물

세상 간단한 https(+secured websocket): Caddy

nginx, apache2 같은 걸로 매번 certbot 연동을 통해 https 하는게 지겨워서 알아보니 Caddy라는게 있더라. 설치법은 강하게 크기 위해 알아서 해본다. # cat /etc/caddy/Caddyfile your.shitty.site:8123 {   proxy / localhost:9123 {     websocket     transparent   } } 이건 외부에서 8123으로 들어오는 걸 내부적으로 9123로 맞춰서 https 맞춰주는 reverse proxy. 만일 port를 생략하면 # cat /etc/caddy/Caddyfile your.shitty.site {   proxy / localhost:9123 {     websocket     transparent   } } 기본포트인 443으로 되어 https://your.shitty.site 로 접속이 된다. 요새 말썽이던 cloudflare 버리고 netlify domain이랑 caddy를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.

저지연 오디오 생성 LLVC 사용기

https://github.com/KoeAI/LLVC 써봄 CUDA 11.8 버전 쓰고 있어 pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 VC 없어서 설치 https://wikidocs.net/168848 참조 FAIRSEQ 관련 오류 https://github.com/facebookresearch/fairseq/issues/2908 pip install editdistance  설치 No CUDA runtime is found, using CUDA_HOME='C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8' 오류 멀쩡하게 있는데 안됨. pip install torch==2.1.0+cu118 torchvision==0.16.0+cu118 torchaudio==2.1.0+cu118 --extra-index-url https://download.pytorch.org/whl/cu118 다시 설치 set DISTUTILS_USE_SDK=1 이게 문젠가 설정하고 재도전 Using cached ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl (118 kB) Building wheels for collected packages: fairseq   Building wheel for fairseq (pyproject.toml) ... error   error: subprocess-exited-with-error   × Building wheel for fairseq (pyproject.toml) did not run successfully.   │ exit code: 1   ╰─> [1829 lines of output]       No CUDA runtime is found, usi...