Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created July 20, 2019 04:54
Show Gist options
  • Select an option

  • Save nexpr/6034450ec2f4d00464ce9f59ef6a8c1f to your computer and use it in GitHub Desktop.

Select an option

Save nexpr/6034450ec2f4d00464ce9f59ef6a8c1f to your computer and use it in GitHub Desktop.
koa のルーティングミドルウェア

koa のルーティングミドルウェア

使い方

routes(route_config)

route_config : オブジェクトの配列

  • path : マッチするパス (配列可)
    • 正規表現 or 文字列
    • 文字列の場合は最初の / 省略可
    • 文字列の場合は <name> でパラメータ
    • パラメータの最後に / を入れると / はマッチしなくなる
  • method : マッチするメソッド (配列可)
  • handler : ミドルウェア関数 (配列可)

返り値: ミドルウェア関数

例

const Koa = require("koa")
const routes = require("./routes.js")

const app = new Koa()

app.use(
	routes([
		{
			path: "/",
			method: "GET",
			handler(ctx) {
				ctx.body = "A"
			},
		},
		{
			path: ["/a", "/b"],
			method: ["GET", "POST"],
			handler: [
				(ctx, next) => {
					ctx.body = "M"
					return next()
				},
				ctx => (ctx.body += "B"),
			],
		},
		{
			path: /^\/c\/xx-(?<id>[a-z]+)-yy\/zz$/,
			handler(ctx) {
				ctx.body = ctx.params
			}
		},
		{
			path: "/d/xx-<id>-yy/zz",
			handler(ctx) {
				ctx.body = ctx.params
			}
		},
		{
			path: "e/zz<param>",
			handler(ctx) {
				ctx.body = ctx.params
			}
		},
		{
			path: "f/zz<param/>",
			handler(ctx) {
				ctx.body = ctx.params
			}
		},
		{
			handler(ctx) {
				ctx.body = "NOTFOUND"
			}
		},
	])
)

app.listen(80)

リクエスト

const request = async (path, method) => {
	const res = await fetch(path, { method })
	const body = await res.text()
	return console.log(body)
}

await request("/")
// "A"

await request("/", "POST")
// "NOTFOUND"

await request("/a")
// "MB"

await request("/a", "POST")
// "MB"

await request("/b")
// "MB"

await request("/b", "POST")
// "MB"

await request("/c/xx-abcd-yy/zz")
// "{"id":"abcd","match1":"abcd"}"

await request("/d/xx-123-yy/zz")
// "{"id":"123","match1":"123"}"

await request("/e/zz1/2/3/4")
// "{"param":"1/2/3/4","match1":"1/2/3/4"}"

await request("/f/zz1/2/3/4")
// "NOTFOUND"

await request("/f/zz1234")
// "{"param":"1234","match1":"1234"}"
const compose = require("koa-compose")
const toarray = a => (Array.isArray(a) ? a : a == null ? [] : [a])
const path2regexp = path => {
if (!path[0] !== "/") path = "/" + path
const repath = path
.split(/<([_a-z0-9]*\/?)>/i)
.map((part, i) => {
if (i % 2) {
const any = part.slice(-1) === "/" ? "[^/]" : "."
const name = part.slice(-1) === "/" ? part.slice(0, -1) : part
return `(?<${name}>${any}*?)`
} else {
return [...part].map(e => "\\u" + e.charCodeAt().toString(16).padStart(4, "0")).join("")
}
})
.join("")
return new RegExp(`^${repath}$`, "i")
}
module.exports = (routes = []) => {
const middlewares = routes.map(route => (ctx, next) => {
if (
route.path &&
!toarray(route.path).some(p => {
const regexp = p instanceof RegExp ? p : path2regexp(String(p))
const matched = regexp.exec(ctx.path)
if (!matched) return false
const params = (ctx.params = {})
if (matched.length > 1) {
Object.assign(params, matched.groups)
for (const [index, value] of matched.slice(1).entries()) {
params["match" + (index + 1)] = value
}
}
return true
})
)
return next()
if (
route.method &&
!toarray(route.method).some(m => {
return m.toUpperCase() === ctx.method || m.toUpperCase() === "ALL"
})
)
return next()
return Promise.resolve(compose(toarray(route.handler))(ctx, next))
})
return compose(middlewares)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment