Feature: Get a project

As a vision user
I want to get a project
So that I can monitor the activity of selected repositories

Let's add a test to the existing set of tests ./test/project.js for our feature Get a project. This resource will GET a project from route /project/:id, and return a 200 OK status.

Let's install underscore.js; a utility-belt library that provides functional programming support:

npm install underscore --save
describe('when requesting an available resource /project/:id', function(){
  it('should respond with 200', function(done){
    request(app)
    .get('/project/' + id)
    .expect('Content-Type', /json/)
    .expect(200)
    .end(function (err, res) {
      var proj = JSON.parse(res.text);
      assert.equal(proj._id, id);
      assert(_.has(proj, '_id'));
      assert(_.has(proj, 'name'));
      assert(_.has(proj, 'user'));
      assert(_.has(proj, 'token'));
      assert(_.has(proj, 'created'));
      assert(_.has(proj, 'repositories'));
      done();
    });
  });
});

Let's implement the Get a project feature ./lib/project/index.js and add a get function. We attempt to retrieve a project by calling the static function Project.findOne. If we get an error, we return it, if we find the project then we return the project:

Project.prototype.get = function(id, callback){
  var query = {"_id" : id};

  ProjectSchema.findOne(query, function(error, project) {
    if (error) return callback(error, null);
    return callback(null, project);
  });
};

Let's add a new route ./lib/routes/project.js. We start by defining a route called get. We validate the request using a regular expression for a valid Mongoose ObjectId; and it returns a 400 Bad Request status if the request is invalid. We attempt to retrieve a project by calling Project.get passing the id. If we get an error, we return 500 Internal Server Error; if the project does not exist, we return a 404 Not Found. If we find the project, we return the project and a 200 OK response:

exports.get = function(req, res){
  logger.info('Request.' + req.url);

  Project.get(req.params.id, function(error, project) {
    if (error) return res.json(500, 'Internal Server Error'),
    if (project == null) return res.json(404, 'Not Found'),
    return res.json(200, project);
  });
};

Now add the following route to ./lib/express/index.js:

app.get('/project/:id', project.get);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.187.15