Chapter 2. Building a Web API

With the foundations in place, we begin the process of building a Web API for our Vision project. We will start by setting up a persistence layer using MongoDB. We will then implement, feature-by-feature, the various aspects of our Web API.

Persisting data with MongoDB and Mongoose

MongoDB is an open source document-oriented database system. MongoDB stores structured data such as JSON-like documents, simplifying integration.

Let's start by creating a MongoDB schema for our project. The schema contains some basic information related to the project such as the project's name, a GitHub access token, a user, and a list of repositories.

Let's install Mongoose, a MongoDB Object Document Mapper for Node.js; it provides a schema-based solution to modeling your data.

npm install mongoose --save

Let's configure our application to use MongoDB and Mongoose; we add a URL for MongoDB to our configuration files ./lib/config/*.js:

{
  "express": {
    "port": 3000
  },
  "logger" : {
    "filename": "logs/run.log",
    "level": "silly"
  },
  "mongo": {
    "url":  "mongodb://localhost/vision"
  }
}

Let's create a MongoDB connection module, ./lib/db/index.js, which simply pulls in the MongoDB URL from our Winston configuration and opens a connection:

var mongoose = require('mongoose')
, config = require('../configuration')
, connectionString = config.get("mongo:url")
, options = { server: { auto_reconnect: true, poolSize: 10 } };

mongoose.connection.open(connectionString, options);

We now create a model class ./lib/models/index.js that defines our ProjectSchema:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var ProjectSchema = new Schema({
    name         : { type: String, required: true, index: true }
  , token        : { type: String }
  , user         : { type: String, required: true, index: true }
  , created      : { type: Date, default: Date.now }
  , repositories : [ { type: String } ]
});

mongoose.model('Project', ProjectSchema);
module.exports = mongoose;

In order to run the following examples, we need a running instance of MongoDB. You can download MongoDB from http://www.mongodb.org. Run the following command to start MongoDB:

mongod
..................Content has been hidden....................

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