Thursday, August 3, 2017

27/07/2017

Building web app using react.js, express.js,         node.js and mongodb

Implementing REST endpoints


school.js



var mongoose = require("mongoose");
var schoolSchema = mongoose.Schema({
    name: String,
    tagline: String
});

module.exports = mongoose.model("school", schoolSchema);
 
 
 
schoolController.js
 
 
var mongoose = require("mongoose");
var School = require("../data/school");
var _ = require("underscore");

var router = require("express").Router();
router.route("/schools/:id?").get(getSchools).post(addSchool).delete(deleteSchool);

function getSchools(req, res) {
    School.find(function (err, schools) {
        if (err)
            res.send(err);
        else
            res.json(schools);
    });
}

function addSchool(req, res) {
    var school = new School(_.extend({}, req.body));
    school.save(function (err) {
        if (err)
            res.send(err);
        else
            res.json(school);
    });
}

function deleteSchool(req, res) {
    var id = req.params.id;
    School.remove({ _id: id }, function (err, removed) {
        if (err)
            res.send(err)
        else
            res.json(removed);
    });
}

module.exports = router;
 
 
 
server.js
 
 
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var path = require("path");

var schoolController = require("./controllers/schoolController");

//Express request pipeline
var app = express();
app.use(express.static(path.join(__dirname, "../app/dist")));
app.use(bodyParser.json())
app.use("/api", schoolController);

app.listen(7777, function () {
    console.log("Started listening on port", 7777);
});

// Connect to mongodb database
mongoose.connect("mongodb://localhost/schoolfinder");
 
 
 
 

Plugging REST to react

schoolService.js

var $ = require("jquery");
var promise = require("es6-promise");
var resourceUrl = "http://localhost:7777/api/schools";

module.exports = {
    addSchool: function (school) {
        var Promise = promise.Promise;
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: resourceUrl,
                data: JSON.stringify(school),
                method: "POST",
                dataType: "json",
                contentType: "application/json",
                success: resolve,
                error: reject
            });
        });
    },
    getSchools: function () {
        var Promise = promise.Promise;
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: resourceUrl,
                method: "GET",
                dataType: "json",
                success: resolve,
                error: reject
            });
        });
    },
    deleteSchool: function (school) {
        var Promise = promise.Promise;
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: resourceUrl + "/" + school._id,
                method: "DELETE",
                dataType: "json",
                success: resolve,
                error: reject
            });
        });
    }
}
 
 
 
 
schoolsStore.js
 
 
var dispatcher = require("../dispatcher");
var schoolService = require("../services/schoolService");

function SchoolStore() {
    var listeners = [];

    function onChange(listener) {
        getSchools(listener);
        listeners.push(listener);
    }
    
    function getSchools(cb){
        schoolService.getSchools().then(function (res) {
            cb(res);
        });
    }

    function addSchool(school) {
    schoolService.addSchool(school).then(function (res) {
            console.log(res);
            triggerListeners();
        });
    }

    function deleteSchool(school) {
   schoolService.deleteSchool(school).then(function (res) {
            console.log(res);
            triggerListeners();
        });
    }

    function triggerListeners() {
        getSchools(function (res) {
            listeners.forEach(function (listener) {
                listener(res);
            });
        });
    }

    dispatcher.register(function (payload) {
        var split = payload.type.split(":");
        if (split[0] === "school") {
            switch (split[1]) {
                case "addSchool":
                    addSchool(payload.school);
                    break;
                case "deleteSchool":
                    deleteSchool(payload.school);
                    break;
            }
        }
    });

    return {
        onChange: onChange
    }
}

module.exports = SchoolStore();
 
 
 
 
main.jsx

var React = require("react");
var ReactDOM = require("react-dom");
var SchoolsList = require("./components/SchoolsList.jsx");
var schoolsStore = require("./stores/schoolsStore");
var _schools = [];
var getSchoolsCallback = function(schools){
    _schools = schools;
    render();
};
schoolsStore.onChange(getSchoolsCallback);

function render(){
ReactDOM.render(<SchoolsList schools={_schools} />, document.getElementById("container"));    
}





 

 

 

 

 
 
 

 

No comments:

Post a Comment

HTML introduction

HTML stands for Hyper Text Markup Language. HTML describes the structure of web page using markup. HTML elements are the building blo...