Permalink
Browse files

Initial commit

  • Loading branch information...
0 parents commit 4ae3cb6c2b298caf458b1d0631485beb6174cc29 Ricard Aspeljung committed Mar 21, 2013
Showing with 545 additions and 0 deletions.
  1. +14 −0 .gitignore
  2. +8 −0 LICENSE
  3. +34 −0 README.md
  4. +14 −0 config.json
  5. +30 −0 lib/accesscontrol.js
  6. +163 −0 lib/rest.js
  7. +48 −0 lib/util.js
  8. +21 −0 package.json
  9. +55 −0 server.js
  10. +158 −0 test/test.js
@@ -0,0 +1,14 @@
+= OS generated files =
+======================
+.DS_Store
+.DS_Store?
+._*
+.Spotlight-V100
+.Trashes
+Icon?
+ehthumbs.db
+Thumbs.db
+
+= Node modules =
+================
+node_modules/
@@ -0,0 +1,8 @@
+The MIT License (MIT)
+Copyright (c) 2013 Ricard Aspeljung
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,34 @@
+# crest
+
+[crest](http://github.com/cordazar/crest) is a REST API Server for MongoDB.
+crest stands for [Cygnus](http://en.wiktionary.org/wiki/Cygnus) REST.
+
+
+## Usage
+Run server with `node server`
+
+### Quick try
+After starting the server you can quickly try it out by issuing the following from the command line:
+`curl -d '{ "example key" : " }' -H "Content-Type: application/json" http://localhost:3500/tests/example`
+
+This should add a document to the collection **example** in database **tests**, like so: `{ "A1": 201, "_id": ObjectId("4e90e196b0c7f4687000000e") }`
+
+
+## Installation
+Clone repository and you can just run it directly from the repository folder. NPM install will come at a later time.
+
+
+## Tests
+Basic tests are available and can be run via [mocha](http://visionmedia.github.com/mocha/).
+
+
+## License
+
+The MIT License (MIT)
+Copyright (c) 2013 Ricard Aspeljung
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,14 @@
+{
+ "db": {
+ "port": 27017,
+ "host": "localhost",
+ "username": "foo",
+ "password": "bar"
+ },
+ "server": {
+ "port": 3500,
+ "address": "0.0.0.0"
+ },
+ "flavor": "nounderscore",
+ "debug": true
+}
@@ -0,0 +1,30 @@
+/**
+ * Copyright 2013 Ricard Aspeljung. All Rights Reserved.
+ *
+ * accesscontrol.js
+ * crest
+ */
+
+var mongo = require("mongodb"),
+ config = module.parent.exports.config,
+ debug = module.parent.exports.debug;
+
+debug("accesscontrol.js is loaded");
+
+/*
+ * accesscontrol - handles http access control based on configuration
+ */
+module.exports.handle = function (req, res, next) {
+ if (req.header('Origin')) {
+ if (config.accessControl.allowOrigin) {
+ res.header('Access-Control-Allow-Origin', config.accessControl.allowOrigin);
+ }
+ if (config.accessControl.allowMethods) {
+ res.header('Access-Control-Allow-Methods', config.accessControl.allowMethods);
+ }
+ if (req.header('Access-Control-Request-Headers')) {
+ res.header('Access-Control-Allow-Headers', req.header('Access-Control-Request-Headers'));
+ }
+ }
+ return next();
+};
@@ -0,0 +1,163 @@
+/**
+ * Copyright 2013 Ricard Aspeljung. All Rights Reserved.
+ *
+ * rest.js
+ * crest
+ */
+
+var mongo = require("mongodb"),
+ server = module.parent.exports.server,
+ config = module.parent.exports.config,
+ debug = module.parent.exports.debug,
+ util = require("./util"),
+ BSON = mongo.BSONPure;
+
+debug("rest.js is loaded");
+
+/**
+ * Query
+ */
+function handleGet(req, res, next) {
+ debug("GET-request recieved");
+ var o;
+ var query = req.query.query ? JSON.parse(req.query.query) : {};
+ // Providing an id overwrites giving a query in the URL
+ if (req.params.id) {
+ query = {
+ '_id': new BSON.ObjectID(req.params.id)
+ };
+ }
+ var options = req.params.options || {};
+
+ var test = ['limit', 'sort', 'fields', 'skip', 'hint', 'explain', 'snapshot', 'timeout'];
+
+ for (o in req.query) {
+ if (test.indexOf(o) >= 0) {
+ options[o] = req.query[o];
+ }
+ }
+
+ var mongoclient = new mongo.MongoClient(new mongo.Server(config.db.host, config.db.port, {
+ native_parser: true,
+ auto_reconnect: true
+ }));
+
+ mongoclient.open(function (err, mongoclient) {
+ var db = mongoclient.db(req.params.db);
+ db.authenticate(config.db.username, config.db.password, function () {
+ db.collection(req.params.collection, function (err, collection) {
+ collection.find(query, options, function (err, cursor) {
+ cursor.toArray(function (err, docs) {
+ var result = [];
+ if (req.params.id) {
+ if (docs.length > 0) {
+ result = util.flavorize(docs[0], "out");
+ res.header('Content-Type', 'application/json');
+ res.send(result);
+ } else {
+ res.send(404);
+ }
+ } else {
+ docs.forEach(function (doc) {
+ result.push(util.flavorize(doc, "out"));
+ });
+ res.header('Content-Type', 'application/json');
+ res.send(result);
+ }
+ db.close();
+ });
+ });
+ });
+ });
+ });
+}
+
+server.get('/:db/:collection/:id?', handleGet);
+server.get('/:db/:collection', handleGet);
+
+
+/**
+ * Insert
+ */
+server.post('/:db/:collection', function (req, res) {
+ debug("POST-request recieved");
+ if (req.params) {
+ var mongoclient = new mongo.MongoClient(new mongo.Server(config.db.host, config.db.port, {
+ native_parser: true,
+ auto_reconnect: true
+ }));
+
+ mongoclient.open(function (err, mongoclient) {
+ var db = mongoclient.db(req.params.db);
+ db.authenticate(config.db.username, config.db.password, function () {
+ db.collection(req.params.collection, function (err, collection) {
+ // We only support inserting one document at a time
+ collection.insert(Array.isArray(req.params) ? util.cleanParams(req.params[0]) : util.cleanParams(req.params), function (err, docs) {
+ res.header('Location', '/' + req.params.db + '/' + req.params.collection + '/' + docs[0]._id.toHexString());
+ res.header('Content-Type', 'application/json');
+ res.send(201, '{"ok":1}');
+ db.close();
+ });
+ });
+ });
+ });
+ } else {
+ res.header('Content-Type', 'application/json');
+ res.send(200, '{"ok":0}');
+ }
+});
+
+/**
+ * Update
+ */
+server.put('/:db/:collection/:id', function (req, res) {
+ debug("PUT-request recieved");
+ var spec = {
+ '_id': new BSON.ObjectID(req.params.id)
+ };
+
+ var mongoclient = new mongo.MongoClient(new mongo.Server(config.db.host, config.db.port, {
+ native_parser: true,
+ auto_reconnect: true
+ }));
+
+ mongoclient.open(function (err, mongoclient) {
+ var db = mongoclient.db(req.params.db);
+ db.authenticate(config.db.username, config.db.password, function () {
+ db.collection(req.params.collection, function (err, collection) {
+ collection.update(spec, util.cleanParams(req.params), true, function (err, docs) {
+ res.header('Content-Type', 'application/json');
+ res.send('{"ok":1}');
+ });
+ });
+ });
+ });
+});
+
+/**
+ * Delete
+ */
+server.del('/:db/:collection/:id', function (req, res) {
+ debug("DELETE-request recieved");
+ var spec = {
+ '_id': new BSON.ObjectID(req.params.id)
+ };
+
+ var mongoclient = new mongo.MongoClient(new mongo.Server(config.db.host, config.db.port, {
+ native_parser: true,
+ auto_reconnect: true
+ }));
+
+ mongoclient.open(function (err, mongoclient) {
+ var db = mongoclient.db(req.params.db);
+ db.authenticate(config.db.username, config.db.password, function () {
+ db.collection(req.params.collection, function (err, collection) {
+ collection.remove(spec, function (err, docs) {
+ res.header('Content-Type', 'application/json');
+ res.send('{"ok":1}');
+ db.close();
+ });
+ });
+ });
+ });
+});
@@ -0,0 +1,48 @@
+/**
+ * Copyright 2013 Ricard Aspeljung. All Rights Reserved.
+ *
+ * util.js
+ * crest
+ */
+
+var mongo = require("mongodb"),
+ config = module.parent.parent.exports.config,
+ debug = module.parent.parent.exports.debug;
+
+debug("util.js is loaded");
+
+/*
+ * flavorize - Changes JSON based on flavor in configuration
+ */
+module.exports.flavorize = function (doc, direction) {
+ if (direction === "in") {
+ if (config.flavor === "nounderscore") {
+ console.log(doc);
+ delete doc.id; // only do this in case flavor is set to nounderscore
+ console.log(doc);
+ }
+ } else {
+ if (config.flavor === "nounderscore") {
+ var id = doc._id.toHexString();
+ delete doc._id;
+ doc.id = id;
+ } else {
+ doc._id = doc._id.toHexString();
+ }
+ }
+ return doc;
+};
+
+module.exports.cleanParams = function (params) {
+ var clean = JSON.parse(JSON.stringify(params));
+ if (clean.id) {
+ delete clean.id;
+ }
+ if (clean.db) {
+ delete clean.db;
+ }
+ if (clean.collection) {
+ delete clean.collection;
+ }
+ return clean;
+};
@@ -0,0 +1,21 @@
+{
+ "name": "crest",
+ "description": "REST Server for MongoDB",
+ "version": "0.0.1",
+ "author": "Ricard Aspeljung <ricard@opendia.se>",
+ "private": true,
+ "dependencies": {
+ "mongodb": ">=1.2.14",
+ "restify": ">=2.3.4",
+ "supertest": ">=0.5.1",
+ "mocha": ">=1.8.2"
+ },
+ "keywords": ["mongodb", "mongo", "db", "rest", "restful", "api"],
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/cordazar/crest.git"
+ },
+ "engines": {
+ "node": ">=0.8"
+ }
+}
Oops, something went wrong.

0 comments on commit 4ae3cb6

Please sign in to comment.