기본 콘텐츠로 건너뛰기

Meteor REST API 미립자 팁 - 404 처리하기

Meteor 를 쓰다보면 너무 편해서 그냥 단순 REST API 서버도 Meteor 로 만들고 싶을 때가 있다. WebApp package는 connect 객체를 갖고 있기 때문에 필요한 라우팅을 해준 뒤   WebApp.connectHandlers   .use('/hey', (req,res)=> res.end('hey handler'))   .use('/may', (req,res)=> res.end('may handler'))   .use( ( req,res ) => res.statusCode = 404 && res.end('404 not found')); 이와 같이 마지막에 모든 request에 대해 처리해주면 된다. 만일 Picker( https://github.com/meteorhacks/picker ) 같은 패키지를 사용할 경우 내부적으로 path-to-regexp npm package를 사용하므로 맞게 수정해줄 필요가 있다. Picker.route('/hey', (params,req,res)=> res.end('hey picker')); Picker.route('/(.*)', (params,req,res,next)=> res.statusCode = 404 && res.end('404 not found')); 역시 Meteor는 REST API 서버로만 써도 완전 꿀이다.

generator 연습

co 를 손으로 직접 만들어서 재귀를 통해 next() 를 돌려봤다. 결국 fiber 랑 같은 패턴인게 아닌가 싶은데 그래도 순정이니까 좋은 것.. node-fetch는 http request를 하고 promise를 반환형으로 갖는 독특한 라이브러리인데 yield랑 함께 쓸 수 있다. fetch=require 'node-fetch' r = (generator)->   iterator = generator()   # recurse   iterate = (iteration)->     if iteration.done       iteration.value     else       iteration.value.then (x)-> iterate iterator.next x   iterate iterator.next() r ->   uri = "http://jsonplaceholder.typicode.com/posts/1"   response = yield fetch uri   json = yield response.json()   json?.title .catch (error)-> console.error "ERROR", error.stack .then (x)-> console.log x 

RxJS 연습.

http://jsbin.com/roweju  에 해보고 있음. Rx.Observable 에 fromEvent 를 붙여서 click 눌렀을 때 카운트가 올라가는 건 솔직히 잘 모르겠고 map으로 가공하고 최종결과를 subscribe 하는 패턴은 재미있다. 비동기 실행을 하는 부분은  Rx.Observable.create (observer)-> 로 시작해서 observer.next( 리턴값 ) 형식으로 끝나는 건 promise 랑 되게 비슷한 패턴이다. .flatMap은    .map (url)-> sendRequest url, 'GET', null    .mergeAll() 이 두개를 합친 것이라고 보면 됨. * HTML <!DOCTYPE html> <html> <head> <script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>   <meta charset="utf-8">   <meta name="viewport" content="width=device-width">   <title>JS Bin</title> </head> <body>   <button id="btn">click</button>   <p><span id="counter">1</span>th click</p>   <button id="btn-get">get posts</button>   <pre id="result">   </pre> </b...

haxe / kha / kode studio - workflow

haxe 설치 후 haxelib setup haxelib install kha kode studio 설치 후 cmd+shift+p 해서 command 치고 Shell Command: Install "kodestudio" command in PATH 선택. 프로젝트를 생성할 디렉토리를 만들고 kodestudio . 해서 시작. 해당 경로에서 시작하면 cmd+shift+p 하고 Init Kha Project F5로 run

오늘의 코드 - Excel 에서 Collection 까지 (feat. dot2obj)

Meteor.startup ->   if Tours.find().count() is 0     addDefault = (v)->       v.createdAt = Date.now()       v     dot2obj = (obj)->       for k,v of obj         idxes = k.split '.'         if idxes.length>0           delete obj[k]           idxes.reduce (a,b,ci,ar)->             a[b] = ar.length-1 is ci and v or a[b] or {}           , obj       obj     excel = new Excel 'xlsx'     workbook = excel.read new Buffer Assets.getBinary "fixtures.xlsx"     fixtures = excel.utils.sheet_to_json workbook.Sheets['Sheet1']     Tours.insert addDefault dot2obj obj for obj in fixtures     console.log "Tours collection initiated." 이런 코드를 만들었다. Tours 라는 collection이 비어있으면 excel 파일을 읽어서 (...

Meteor DDP 요점 정리

준비 ddp 라이브러리 추가 $ meteor add ddp 외부 DDP 연결 extDDP = DDP.connect("http://externalhost.com:4100"); Collection 연결 Posts = new Mongo.Collection('posts', extDDP); 2,3 과정은 client 에서 가장 먼저 실행되도록 client/lib 디렉토리 안에 넣는 것을 추천 기존 연결을 외부 DDP로 대치 Meteor.connection = extDDP; ex) 활용예 Meteor.connection = extDDP; Meteor.loginWithPassword(login.valiu, password.value); Meteor.startup 같은 곳에서 사용하면 좋음. 만일 login을 그냥 사용하려면 expDDP.call('login', .... ); 형태로 사용하여야함. Subscribe 사용 onCreated 시점에 this.subscribe 대신 DDP 객체의 subscribe를 사용 Template.postView.onCreated(function() {   extDDP.subscribe("getPosts", { searchWord: 'blahblah' }); }); Helper 사용 3번처럼 했다면 그냥 똑같이 사용 Tempalte.postView.helpers({   "posts": function() {     return Posts.find({});   } }); Method 사용 Template.postInput.events({   "submit": function(e) {     expDDP.call('addPost', inputText.value', function(error, result) {      /* do something */     });     e.preventDefa...

microservice 기반 meteor application 설계 /w DDP

특정 업무가 장애가 일어나도 전체가 다운되지 않는 서비스를 Meteor 로 만들 수 있지 않을까 라는 생각을 하고 있었는데 실제로 한번 해보았다. 로긴 서버와 N개의 업무서버가 하나의 DB를 바라보고 클라이언트에서 로긴 서버에 계정생성/접속 후 토큰을 꺼내와서 나머지 서버에 접속하는 그림을 그려보았다. 업무 서버의 경우 웹앱에서 접근 문제가 있기 때문에 CORS를 열어준다. Meteor.startup ->   WebApp.rawConnectHandlers.use (req, res, next)->     res.setHeader "Access-Control-Allow-Origin", "*"     next() iOS/Android 앱의 경우는 사실 상관이 없지만 webApp인 경우엔 꼭 필요. 반대로 webApp 인 경우는 client 폴더에만 작업하면 되는데 가장 먼저 실행하는 파일(ex. client/lib) 에 DDP와 Collection 연결하는 부분을 만들어 준다. # global namespace @ddps =   loginDDP : DDP.connect "http://localhost:4100"   chatDDP : DDP.connect "http://localhost:4200" # models @Chats = new Mongo.Collection 'chats', ddps.chatDDP 그리고 Meteor App 이 시작하는 시점에 아래와 같이 구성한다. Meteor.startup ->   Meteor.connetion = ddps.loginDDP   Tracker.autorun ->     if Meteor.user()?       unless Meteor.loggingIn()         con...