WebApp.connectHandlers

Fish
Fish
Aug 24, 2017 · 4 min read

Meteorには webapp というモジュールがあります。

import { WebApp } from 'meteor/webapp'

これを使うことで簡単なAPIが実装できます。

WebAppの実装は省略するとおおよそこのようになっています。内部にはconnectが使われています。残念なことに webapp モジュールの開発はあまり進んではないです。

var app = connect();var packageAndAppHandlers = connect()
app.use(packageAndAppHandlers)
_.extend(WebApp, {
connectHandlers: packageAndAppHandlers,
rawConnectHandlers: rawConnectHandlers,
httpServer: httpServer,
connectApp: app
// ...more
})

どうやら WebApp.connectHandlers を使うといいようです。

まずは、body-parser を用いて req.body を参照できるようにします。

import { WebApp } from 'meteor/webapp'
import bodyParser from 'body-parser'
const AccessControlAllowOrigin = (req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*')
next()
}

// Access-Control-Allow-Origin
WebApp.connectHandlers.use(AccessControlAllowOrigin)

// parse application/x-www-form-urlencoded
WebApp.connectHandlers.use(bodyParser.urlencoded({extended: false}))

// parse application/json
WebApp.connectHandlers.use(bodyParser.json())

簡単な例としては /api/v1/endpoint のアクセスに対してjsonデータを返却したりできます。

const endpoint = (req, res) => {
const json = req.method === 'POST' ? req.body || {} : {}
const message = JSON.stringify(json)
res.writeHead(200, {'Content-Type': 'application/json'})
res.end(message)
}
WebApp.connectHandlers.use('/api/v1/endpoint', endpoint)

connect は動的なparamsを処理することができません。この問題は connect-route によってどうにかなるのですが、loggerなどのミドルウェアは正常に機能しません。

import route from 'connect-route'const endpoint = router => {
router.post('/endpoint/:unique', (req, res) => {
const json = req.params
const message = JSON.stringify(json)
res.writeHead(200, {'Content-Type': 'application/json'})
res.end(message)
})
}
WebApp.connectHandlers.use('/api/v1', route(endpoint))

router を使用した場合は、このようになります。

import endpoint from 'router'const endpoint = router()endpoint.post('/api/v1/endpoint/:unique', (req, res) => {
const json = req.params
const message = JSON.stringify(json)
res.writeHead(200, {'Content-Type': 'application/json'})
res.end(message)
})
WebApp.connectHandlers.use(endpoint)
)
Fish

Written by

Fish

https://github.com/uufish

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade