diff --git a/api.js b/api.js index 60ad133a2..c89d25fe2 100644 --- a/api.js +++ b/api.js @@ -10,22 +10,77 @@ var util = require('util'), // API Server inherits EventEmitter function Server () { - if (!(this instanceof Server)) return new Server(); + if (!(this instanceof Server)) + return new Server(); + http.Server.call(this); + // An array that contains the listeners for the different methods + this.methods = []; + // Listen for any request and map the request to it's own event. // 'regularRequest' is emitted, when there are no listeners for the event. - this.addListener('request', function(req, res) { - var path = url.parse(req.url).pathname; + this.addListener('request', function(req, resp) { + var method, + parsed = url.parse(req.url), + path = parsed.pathname; + + req.urlParsed = parsed; if (this.listeners(path).length > 0) - this.emit(path, req, res); - else - this.emit('regularRequest', req, res); + this.emit(path, req, resp); + else { + // check if method is defined + if (method = this.methods[req.method]) + // for each listener of method + for (var listener in method) { + var match, + p = method[listener].pattern; + + // match it + if ((match = p.exec(path)) != null) { + // add to resp + resp.match = match; + // callback + method[listener].callback(req, resp); + return; + } + console.log(match); + } + this.emit('regularRequest', req, resp); + } }); + + this.extend('GET'); + this.extend('POST'); + this.extend('PUT'); + this.extend('DELETE'); + this.extend('HEAD'); }; + +// Inherit from native http.Server util.inherits(Server, http.Server); +// extend server with a new request method +Server.prototype.extend = function (method, override) { + var fn = method.toLowerCase(); // the methods will be lowercase + + if (this[fn] && !override) + return new Error('The property '+fn + +' already exists. Please use another name or set override to true.'); + + this.methods[method] = []; + + this[fn] = function (p, cb) { + this.methods[method].push({ pattern: p, callback: cb }); + }; +}; + +Server.util = {}; +Server.util.escPath = function(path) { + return path.replace(/\//g, '\\/'); +}; + api.Server = Server; return api; diff --git a/package.json b/package.json index 083631937..a4e5ca731 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,15 @@ { "author": "Paul Vorbach (https://vorb.de/)", "name": "api", - "description": "A server for RESTful APIs", - "tags": [ "REST", "API", "server" ], - "version": "0.0.0", + "description": "A server framework for easy routing", + "tags": [ "server", "middleware", "router" ], + "version": "0.1.0", "repository": { "type": "git", "url": "git://github.com/pvorb/node-api.git" }, "bugs": { - "web": "https://github.com/pvorb/node-api/issues" + "url": "https://github.com/pvorb/node-api/issues" }, "main": "api.js", "engines": {