기본 콘텐츠로 건너뛰기

Meteor에서 REST API를 사용하는 방법 #2

server쪽 API를 router package를 사용해 쓰다보면 header 같은 걸 다루거나 할땐 너무 단순하게 만들어서 곤란할 수 있다.
이전에도 다룬 적(http://spectrumdig.blogspot.kr/2012/08/meteor-rest.html)이 있지만 __meteor_bootstrap__ 객체를 통해 접근하면 node.js 식의 접근이 가능하다.

Meteor update와 함께 Npm 객체가 생겼으니 이를 이용해 connect 객체를 사용해보자
http://www.slideshare.net/cjoudrey/building-your-first-node-app-with-connect-express
위 슬라이드를 한번 보면 이해에 도움이 될 것이다.

WebApp.connectHandlers 가 connect.createServer()라는 걸 기억하면 된다.



connect = Npm.require 'connect'
server = WebApp.connectHandlers
server.use connect.router (app)->
app.get '/info', (req,res)->
res.end "info"
app.get '/user/:id', (req,res)->
res.end "user id: #{req.params.id}"

이와 같은 코드를 server 디렉토리에 안에 넣거나 Meteor.isServer일때 실행하도록 하자.
파일 업로드나 쿼리 문자열 처리(ex: ?a=1&b=c)하려면
각각 bodyParser(http://www.senchalabs.org/connect/bodyParser.html) 와 query(http://www.senchalabs.org/connect/query.html)를 추가하는 것이 좋다.
위의 해당 링크에 보면 소스까지 공개 해놓아서 이해하기 쉬우니 필요한게 있으면 추가해보자. (가령 logger라든지...)



connect = Npm.require 'connect'
server = WebApp.connectHandlers
server.use connect.bodyParser()
server.use connect.query()
server.use connect.router (app)->
app.get '/info', (req,res)->
res.end "info"
app.get '/user/:id', (req,res)->
res.end "user id: #{req.params.id}"
app.post '/user', (req, res)->
res.end "user name: #{req.body.user.name}"
app.get '/search', (req,res)->
res.end "search : #{req.query.q}"



$ curl -d '{"user":{"name":"tj"}}' -H "Content-Typeon" http://localhost:3000/user
user name: tj


$ curl http://localhost:3000/search?q=something
search : something

위 두개의 curl 명령은 각각 bodyParser와 query모듈이 없으면 오류를 발생한다. body와 query 객체가 request 객체 안에 없으니까.

Npm이 그랬던 것 처럼 __meteor_bootstrap__.app 도 세련되게 포장해야하지 않나 싶은데 그건 또 그때 일 :)


* Updatehttps://github.com/tmeasday/meteor-router/blob/master/lib/router_server.js 소스를 보니 기존의 __meteor_bootstrap__.app 이 WebApp.connectHandlers 로 바뀌었다.
만일 패키지를 만들었고 그것이 이전 버전과 하위 호환을 유지하고 싶다면 require와 connect.createServer에 대해

@require = if Npm? then Npm.require else __meteor_bootstrap__.require
@server = if WebApp?.connectHandlers? then WebApp.connectHandlers else __meteor_bootstrap__.app

과 같이 정의해서 쓰는 것도 좋겠다.

댓글

이 블로그의 인기 게시물

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

OS X 터미널에서 tmux 사용시 pane 크기 조절

http://superuser.com/a/660072  글 참조. OS X 에서 tmux 사용시 나눠놓은 pane 크기 조정할 때 원래는 ctrl+b, ctrl+↑←→↓ 로 사이즈를 조정하는데 기본 터미널 키 입력이 조금 문제가 있다. 키 매핑을 다시 하자 Preferences(cmd+,) > Profile >  변경하고자 하는 Theme 선택 > Keyboards 로 들어가서 \033[1;5A \033[1;5B \033[1;5C \033[1;5D 를 순서대로 ↑↓→←순으로 매핑이 되도록 하면 된다. +를 누르고 Key에 해당 화살표키와 Modifier에 ctrl 선택 한 후 <esc>, [, 1, ;, 5 까지 한키 한키 입력 후 A,B,C,D를 써준다. 잘못 입력했을 땐 당황하지 말고 Delete on character 버튼을 눌러 수정하도록 하자. 그리고 다시 tmux에서 ctrl+b, ctrl+↑←→↓로 사이즈를 조절해보자. 잘 된다.