Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Node.js 6.x Blueprints.
  • Table Of Contents Toc
Node.js 6.x Blueprints.

Node.js 6.x Blueprints.

By : Fernando Monteiro
1 (1)
close
close
Node.js 6.x Blueprints.

Node.js 6.x Blueprints.

1 (1)
By: Fernando Monteiro

Overview of this book

Node.js is the most popular framework to create server-side applications today. Be it web, desktop, or mobile, Node.js comes to your rescue to create stunning real-time applications. Node.js 6.x Blueprints will teach you to build these types of projects in an easy-to-understand manner. The key to any Node.js project is a strong foundation on the concepts that will be a part of every project. The book will first teach you the MVC design pattern while developing a Twitter-like application using Express.js. In the next chapters, you will learn to create a website and applications such as streaming, photography, and a store locator using MongoDB, MySQL, and Firebase. Once you’re warmed up, we’ll move on to more complex projects such as a consumer feedback app, a real-time chat app, and a blog using Node.js with frameworks such as loopback.io and socket.io. Finally, we’ll explore front-end build processes, Docker, and continuous delivery. By the end of book, you will be comfortable working with Node.js applications and will know the best tools and frameworks to build highly scalable desktop and cloud applications.
Table of Contents (16 chapters)
close
close
Node.js 6.x Blueprints
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface

Creating the controllers folder


Instead of using the routes folder to create the route and functions of the comments file, we will use another format and create the controllers folder, where we can separate the route and the controller function, thus having a better modularization:

  1. Create a folder called controllers.

  2. Create a file called comments.js and add the following code:

          // get gravatar icon from email 
          var gravatar = require('gravatar'); 
          // get Comments model 
          var Comments = require('../models/comments'); 
           
          // List Comments 
          exports.list = function(req, res) { 
             // List all comments and sort by Date 
              Comments.find().sort('-created').populate('user',
                'local.email').exec(function(error, comments) { 
                  if (error) { 
                      return res.send(400, { 
                          message: error       
                      }); 
                  } 
                  // Render result 
                  res.render('comments', { 
                      title: 'Comments Page', 
                      comments: comments, 
                      gravatar: gravatar.url(comments.email,
                         {s: '80', r: 'x', d: 'retro'}, true) 
                  }); 
              }); 
          }; 
          // Create Comments 
          exports.create = function(req, res) { 
             // create a new instance of the Comments model with request body 
              var comments = new Comments(req.body); 
              // Set current user (id) 
              comments.user = req.user; 
              // save the data received 
              comments.save(function(error) { 
                  if (error) { 
                      return res.send(400, { 
                          message: error 
                      }); 
                  } 
                  // Redirect to comments 
                  res.redirect('/comments'); 
              }); 
          }; 
          // Comments authorization middleware 
          exports.hasAuthorization = function(req, res, next) { 
              if (req.isAuthenticated()) 
                  return next(); 
              res.redirect('/login'); 
          }; 
    
  3. Let's import the controllers on the app.js file; add the following lines after var users = require('./server/routes/users'):

          // Import comments controller
          var comments = require('./server/controllers/comments'); 
  4. Now add the comments route after app.use('/users', users):

          // Setup routes for comments 
          app.get('/comments', comments.hasAuthorization, comments.list); 
          app.post('/comments', comments.hasAuthorization, comments.create); 
    
  5. Create a file called comments.ejs at server/pages and add the following lines:

          <!DOCTYPE html> 
          <html> 
          <head> 
              <title><%= title %></title> 
              <% include ../partials/stylesheet %> 
          </head> 
          <body> 
            <% include ../partials/header %> 
            <div class="container"> 
              <div class="row"> 
                <div class="col-lg-6"> 
                  <h4 class="text-muted">Comments</h4> 
                </div> 
                <div class="col-lg-6"> 
                  <button type="button" class="btn btn-secondary pull-right"
                   data-toggle="modal" data-target="#createPost">
                        Create Comment 
                    </button> 
                </div> 
                </div> 
                <!-- Modal --> 
                <div class="modal fade" id="createPost" tabindex="-1"
                 role="dialog" aria-labelledby="myModalLabel"
                  aria-hidden="true"> 
                  <div class="modal-dialog" role="document"> 
                    <div class="modal-content"> 
                      <form action="/comments" method="post"> 
                        <div class="modal-header"> 
                          <button type="button" class="close" 
                           data-dismiss="modal" aria-label="Close"> 
                             <span aria-hidden="true">&times;</span> 
                           </button> 
                           <h4 class="modal-title" id="myModalLabel">
                            Create Comment</h4> 
                        </div> 
     
                        <div class="modal-body"> 
                          <fieldset class="form-group"> 
                             <label  for="inputitle">Title</label> 
                             <input type="text" id="inputitle" name="title"
                               class="form-control" placeholder=
                                "Comment Title" required=""> 
                           </fieldset> 
                           <fieldset class="form-group"> 
                             <label  for="inputContent">Content</label> 
                             <textarea id="inputContent" name="content"
                              rows="8" cols="40" class="form-control"
                              placeholder="Comment Description" required="">
                             </textarea> 
                           </fieldset> 
     
                           </div> 
                            <div class="modal-footer"> 
                              <button type="button" class="btn btn-secondary"
                               data-dismiss="modal">Close</button> 
                              <button type="submit" class="btn btn-primary">
                               Save changes</button> 
                            </div> 
                      </form> 
                    </div> 
                  </div> 
                </div> 
                  <hr> 
                <div class="lead"> 
                  <div class="list-group"> 
                    <% comments.forEach(function(comments){ %> 
                      <a href="#" class="list-group-item"> 
                        <img src="<%= gravatar %>" alt="" style="float: left;
                          margin-right: 10px"> 
                   <div class="comments"> 
                    <h4 class="list-group-item-heading">
                      <%= comments.title %></h4> 
                     <p class="list-group-item-text">
                       <%= comments.content %></p> 
                     <small class="text-muted">By: 
                        <%= comments.user.local.email %>
                     </small> 
                    </div> 
                    </a> 
     
                <% }); %> 
                </div> 
              </div> 
             </div> 
              <% include ../partials/footer %> 
              <% include ../partials/javascript %> 
          </body> 
          </html> 
    
  6. Note that we are using a simple Modal component from Twitter-bootstrap for the addition of comments, as shown in the following screenshot:

    Model for the create comments screen

  7. The last step is to create a model for the comments; let's create a file named comments.js at server/models/ and add the following code:

          // load the things we need 
          var mongoose = require('mongoose'); 
          var Schema = mongoose.Schema; 
     
          var commentSchema = mongoose.Schema({ 
              created: { 
                  type: Date, 
                  default: Date.now 
              }, 
              title: { 
                  type: String,       
                  default: '', 
                  trim: true, 
                  required: 'Title cannot be blank' 
              }, 
              content: { 
                  type: String, 
                  default: '', 
                  trim: true 
              }, 
              user: { 
                  type: Schema.ObjectId, 
                  ref: 'User' 
              } 
          }); 
     
          module.exports = mongoose.model('Comments', commentSchema); 
    
Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Node.js 6.x Blueprints.
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon