Last active
February 10, 2018 13:53
-
-
Save k1r0s/71c2543d7b700bba52d5ee9f62c2ae77 to your computer and use it in GitHub Desktop.
nodeProvider provides a single node http server instance to every AbstractResource instance to allow each request to be handled by one resource subclass
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
const { createClass, inject } = require("kaop"); | |
const { nodeProvider } = require("./node-server"); | |
const url = require("url"); | |
module.exports = AbstractResource = createClass({ | |
constructor: [inject.args(nodeProvider), function(resourceIdentifier, node) { | |
this.uri = resourceIdentifier; | |
node.server.on("request", (req, res) => | |
req.url.includes(resourceIdentifier) && this.processRequest(req, res)); | |
}], | |
processRequest(req, res) { | |
const query = url.parse(req.url, true).query; | |
let body = ""; | |
req.on("data", d => body += d); | |
req.on("end", () => this.dispatch(req, res, query, body)); | |
}, | |
dispatch(req, res, query, body) { | |
req.body = body ? JSON.parse(body): null; | |
req.query = query; | |
const methodName = req.method.toLowerCase(); | |
this[methodName](req, res); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment