Skip to content

Commit

Permalink
Adding support for OPTIONS routes
Browse files Browse the repository at this point in the history
  • Loading branch information
avoidwork committed Mar 8, 2017
1 parent 93268f6 commit 8dba514
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 12 deletions.
14 changes: 12 additions & 2 deletions lib/woodland.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ const coerce = require("tiny-coerce"),
endSlash = /\/$/,
isParam = /^:/,
hasParam = /\/:(\w*)/,
head = /^(HEAD)$/,
head = /^HEAD$/,
options = /^OPTIONS$/,
methods = http.METHODS;

class Woodland {
Expand Down Expand Up @@ -139,7 +140,7 @@ class Woodland {

route (req, res) {
let deferred = defer(),
method = [head.test(req.method) ? "GET" : req.method], // @todo support implicit GET & explicit OPTIONS
method = head.test(req.method) ? "GET" : req.method,
middleware, result;

let last = err => {
Expand Down Expand Up @@ -216,6 +217,11 @@ class Woodland {
});

this.decorate(req, res);

if (options.test(method) && !this.allowed(method, req.parsed.pathname, req.host)) {
method = "GET";
}

result = this.routes(req.parsed.pathname, req.host, method);

if (result.params) {
Expand Down Expand Up @@ -321,6 +327,10 @@ class Woodland {
throw new Error("Invalid HTTP method");
}

if (head.test(method)) {
throw new Error("Cannot set HEAD route, use GET");
}

if (!this.middleware.has(lhost)) {
this.middleware.set(lhost, new Map());
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "woodland",
"version": "1.1.22",
"version": "1.2.0",
"description": "Lightweight HTTP/HTTPS router with virtual hosts & automatic Allow header",
"main": "index.js",
"scripts": {
Expand Down
10 changes: 1 addition & 9 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,6 @@ const http = require("http"),
tinyhttptest = require("tiny-httptest"),
router = require(path.join(__dirname, "..", "index.js"))({defaultHeaders: {"Cache-Control": "no-cache"}, defaultHost: "localhost", hosts: ["localhost", "noresponse"]});

function bound (req, res, next) {
next();
}

let boundd = bound.bind(bound);

router.use(boundd).blacklist(boundd);

router.use("/", (req, res) => {
res.writeHead(200, {"Content-Type": "text/plain"});
res.end(req.method !== "OPTIONS" ? "Hello World!" : "");
Expand Down Expand Up @@ -66,7 +58,7 @@ describe("Valid Requests", function () {
.end();
});

it("GET /echo/hello (200 / 'Success')", function () {
it("OPTIONS /echo/hello (200 / 'Success')", function () {
return tinyhttptest({url: "http://localhost:8001/echo/hello", method: "OPTIONS"})
.expectStatus(200)
.expectHeader("allow", "GET, HEAD, OPTIONS")
Expand Down

0 comments on commit 8dba514

Please sign in to comment.