Permalink
Browse files

add missing files

  • Loading branch information...
fjakobs committed Nov 28, 2012
1 parent 38508f0 commit e7858d3e74aba461a79be4e73733ae67dae3e757
Showing with 117 additions and 0 deletions.
  1. +84 −0 example/api.js
  2. +33 −0 lib/middleware.js
View
@@ -0,0 +1,84 @@
+var frontdoor = require("../../frontdoor");
+var errors = require("http-error");
+
+module.exports = function() {
+ var api = frontdoor("TODO app");
+
+ var todo = new Todo();
+ todo.add({description: "get a hair cut"}, function() {});
+ todo.add({description: "buy milk"}, function() {});
+ todo.update({id: 1, done: true}, function() {});
+
+ api.section("todo").get("/", todo.list.bind(todo))
+ .put("/", {
+ params: {
+ description: {
+ type: "string",
+ source: "body"
+ }
+ }
+ }, todo.add.bind(todo))
+ .post("/:id", {
+ params: {
+ id: "int",
+ done: {
+ type: "boolean",
+ source: "body",
+ optional: true
+ },
+ description: {
+ type: "string",
+ source: "body",
+ optional: true
+ }
+ }
+ }, todo.update.bind(todo))
+ .delete("/:id", {
+ params: { id: "int" }
+ }, todo.remove.bind(todo));
+
+ api.get("/inspect.json", frontdoor.middleware.describeApi(api));
+
+ return api;
+};
+
+function Todo() {
+ this.items = {};
+ this._id = 1;
+}
+Todo.prototype.list = function(params, callback) {
+ var res = { items: [] };
+ for (var id in this.items)
+ res.items.push(this.items[id]);
+ callback(null, res);
+};
+Todo.prototype.add = function(params, callback) {
+ var id = this._id++;
+ this.items[id] = {
+ id: id,
+ done: false,
+ description: params.description
+ };
+ callback(null, { id: params.id });
+};
+Todo.prototype.update = function(params, callback) {
+ var item = this.items[params.id];
+ if (!item)
+ return callback(new errors.NotFound("No such entry " + params.id));
+
+ if ("done" in params)
+ item.done = params.done;
+
+ if ("description" in params)
+ item.description = params.description;
+
+ callback(null, { id: params.id });
+};
+Todo.prototype.remove = function(params, callback) {
+ var item = this.items[params.id];
+ if (!item)
+ return callback(new errors.NotFound("No such entry " + params.id));
+
+ delete this.items[params.id];
+ callback(null, { id: params.id });
+};
View
@@ -0,0 +1,33 @@
+"use strict";
+
+var error = require("http-error");
+
+exports.jsonWriter = function() {
+ return function(req, res, next) {
+ res.json = function(json, headers) {
+ var data;
+ try {
+ data = JSON.stringify(json);
+ } catch(e) {
+ console.error(e);
+ return next(new error.InternalServerError("Could not stringify JSON"));
+ }
+
+ if (req.parsedUrl && req.parsedUrl.query.jsonp)
+ data = req.parsedUrl.query.jsonp + "(" + data + ")";
+
+ headers = headers || {};
+ headers["Content-Type"] = "application/json";
+ res.writeHead(200, headers);
+ res.end(data);
+ };
+
+ next();
+ };
+};
+
+exports.describeApi = function(root) {
+ return function(req, res, next) {
+ res.json(root.describe());
+ };
+};

0 comments on commit e7858d3

Please sign in to comment.