기본 콘텐츠로 건너뛰기

7월, 2016의 게시물 표시

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 파일을 읽어서 ( netanelgilad:excel 패키지 사용) 넣는데 헤더 이름이 a.b.c 처럼 dot notation 을 포함하고 있으면 알아서 { a: {b: {c: "value"}}} 로 집어넣도록 변환하는 것까지. reduce로 초기 object를 넣어서 마지막 depth에 닿으면 값을 할당하고 아닐 경우 해당 인덱스가 없으면 만들면서 계속 진행하는 방식으로 만들었다.           i