Last active
March 5, 2019 09:56
-
-
Save alanrsoares/ef36cbe54b1d7d493f5d03713e709acf to your computer and use it in GitHub Desktop.
Micro router for js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Router { | |
routes = {} | |
baseUrl = "" | |
constructor(baseUrl) { | |
this.baseUrl = baseUrl | |
} | |
register = (method) => { | |
return (pattern, handler) => { | |
const path = `${this.baseUrl}${pattern}` | |
const placeholders = [] | |
const body = path.replace(/:(\w+)/g, (_,x) => { | |
placeholders.push(x); | |
return `(\\w+)`; | |
}); | |
const route = { | |
path, | |
handler, | |
placeholders, | |
pattern: new RegExp(`^${body}$`, "i") | |
} | |
if (method in this.routes) { | |
this.routes[method].push(route) | |
} else { | |
this.routes[method] = [route] | |
} | |
return this | |
} | |
} | |
match(method, url) { | |
if (method in this.routes) { | |
const candidates = this.routes[method]; | |
const match = candidates.find(route => route.pattern.test(url)) | |
if (match) { | |
const parsed = match.pattern.exec(url) | |
const args = parsed.length > 1 | |
? parsed | |
.slice(1) | |
.reduce( | |
(acc, x, i) => ({ ...acc, [match.placeholders[i]]: x }), | |
{} | |
) | |
: undefined | |
return match.handler(args) | |
} | |
} | |
return null | |
} | |
get = this.register("GET") | |
post = this.register("POST") | |
put = this.register("PUT") | |
patch = this.register("PATCH") | |
delete = this.register("DELETE") | |
} | |
const baseUrl = "https://foo.com/api" | |
const router = new Router(baseUrl) | |
const matcher = router | |
.get("/foos", () => ({ | |
delay: 500, | |
status: 200, | |
data: [{ id: "id-1", bar: "2" }] | |
})) | |
.get("/foos/:id", ({ id }) => ({ | |
delay: 500, | |
status: 200, | |
data: { | |
id: id, | |
bar: "asdas" | |
} | |
})) | |
.post("/bars", () => ({ | |
delay: 100, | |
status: 200, | |
data: { | |
id: "id-1234" | |
} | |
})) | |
const match = matcher.match("GET", "https://foo.com/api/foos/ab") | |
console.log(match) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment