erikpalla
4/9/2017 - 10:10 PM

Creating a microservice in NodeJs

Creating a microservice in NodeJs

// server.js
let express = require('express')
let app = express();

let mongoose = require('mongoose');
mongoose.connect('[connection string]');

let CommentService = require('./comment-service');

let commentService = new CommentService();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/comment/:articleId', (req, res) => {
  commentService.getComments(req.params.articleId)
                .then((comments) => {
                  res.json(comments);
                })
                .catch((error) => {
                  res.json(error);
                });
});
 
app.listen(process.env.PORT);

// comment-service.js
let Comment = require('./comment');

let LoggerService = require('./logger-service');
let loggerService = new LoggerService();

let commentModel = require('./comment-model');

class CommentService {
  constructor() {
    this.commentCache = {};
  }

  getComments(articleId){
    if(this.commentCache[articleId]) {
      return Promise.resolve(this.commentCache[articleId]);
    }

    return new Promise((resolve, reject) => {
      commentModel.find({approved: true, articleId: articleId}).sort({created: 'asc'}).exec((err, comments) => {
        
        if(err) {
          loggerService.logError(err);
          reject('There was an error fetching comments');
        }

        if(comments.length === 0) {
          resolve([]);
        }
   
        this.commentCache[articleId] = this.buildCommentBranchRecursive(null, comments);  
        resolve(this.commentCache[articleId]);
      });
    });
  }

  buildCommentBranchRecursive(parentId, allComments) {
    let siblings = allComments.filter(c => c.parentId === parentId);
    let comments = [];    
 
    siblings.forEach((node) => {
      var comment = new Comment(node.author, node.text, node._id.toString(), parentId, node.created);
      comment.children = this.buildCommentBranchRecursive(comment.id, allComments);
      comments.push(comment);
    });

    return comments;
  }
}
module.exports = CommentService;

// comment-model.js
let mongoose = require('mongoose');

mongoose.Promise = global.Promise;

var commentSchema = new mongoose.Schema(
    {
      author: {type: String},
      text: {type: String},
      approved: {type: Boolean, default: false},
      articleId: {type: String},
      parentId: {type: String},
      created: {type: Date, default: Date.now }
    },
    { versionKey: false }
);

module.exports = mongoose.model('Comments', commentSchema);

// comment.js
class Comment {

  constructor (author,text,id,parentId,created) {
    this.id = id;
    this.author = author;
    this.text = text;
    this.parentId = parentId;
    this.created = created;
    this.children = [];
  }
}

module.exports = Comment;