码迷,mamicode.com
首页 > 数据库 > 详细

MEAN,从MONGO DB里弄出点东东来啦,以REST风格显示JSON

时间:2016-07-06 23:24:35      阅读:402      评论:0      收藏:0      [点我收藏+]

标签:

最近一直在弄弄的。。。

javascript的风格弄熟了,我觉得肯定很快,,但心中有种感觉,DJANGO和MEAN这种结构,搞大的不行。

因为MVC这种结构感觉不如SPRING这些严谨,是不是我有偏见呢?水平不够呢?不强制就不弄呢?

db层写法:

/**
 * Created by sahara on 2016/7/5.
 */

var mongoose = require(‘mongoose‘);
var dbURI = ‘mongodb://localhost/Loc8r‘;
var gracefulShutdown
mongoose.connect(dbURI);

mongoose.connection.on(‘connected‘, function () {
    console.log(‘Mongoose connected to ‘ + dbURI);
});
mongoose.connection.on(‘error‘,function (err) {
    console.log(‘Mongoose connection error: ‘ + err);
});
mongoose.connection.on(‘disconnected‘, function () {
    console.log(‘Mongoose disconnected‘);
});

var readLine = require ("readline");
if (process.platform === "win32"){
    var rl = readLine.createInterface ({
        input: process.stdin,
        output: process.stdout
    });
    rl.on ("SIGINT", function (){
        process.emit ("SIGINT");
    });
}

gracefulShutdown = function (msg, callback) {
    mongoose.connection.close(function () {
        console.log(‘Mongoose disconnected through ‘ + msg);
        callback();
    });
};

process.once(‘SIGUSR2‘, function () {
    gracefulShutdown(‘nodemon restart‘, function () {
        process.kill(process.pid, ‘SIGUSR2‘);
    });
});
process.on(‘SIGINT‘, function () {
    gracefulShutdown(‘app termination‘, function () {
        process.exit(0);
    });
});
process.on(‘SIGTERM‘, function() {
    gracefulShutdown(‘Heroku app shutdown‘, function () {
        process.exit(0);
    });
});

require(‘./locations‘);

数据库定义:

/**
 * Created by sahara on 2016/7/5.
 */

var mongoose = require(‘mongoose‘);

var openingTimeSchema = new mongoose.Schema({
    days: {type: String, required: true},
    opening: String,
    closing: String,
    closed: {type: Boolean, required: true}
});

var reviewSchema = new mongoose.Schema({
    author:String,
    rating: {type: Number, required: true, min: 0, max: 5},
    reviewText: String,
    createdOn: {type: Date, "default": Date.now}
});

var locationSchema = new mongoose.Schema({
    name: {type: String, required: true},
    address: String,
    rating: {type: Number, "default": 0, min: 0, max: 5},
    facilities: [String],
    coords: {type: [Number], index: ‘2dsphere‘},
    openingTimes: [openingTimeSchema],
    reviews: [reviewSchema]
});

mongoose.model(‘Location‘, locationSchema);

路由层写法:

var express = require(‘express‘);
var router = express.Router();
var ctrlLocations = require(‘../controllers/locations‘);
var ctrlReviews = require(‘../controllers/reviews‘);

//locations
router.get(‘/locations‘, ctrlLocations.locationsListByDistance);
router.post(‘/locations‘, ctrlLocations.locationsCreate);
router.get(‘/locations/:locationid‘, ctrlLocations.locationsReadOne);
router.put(‘/locations/:locationid‘, ctrlLocations.locationsUpdateOne);
router.delete(‘/locations/:locationid‘, ctrlLocations.locationsDeleteOne);

//reviews
router.post(‘/locations/:locationid/reviews‘, ctrlReviews.reviewCreate);
router.get(‘/locations/:locationid/reviews/:reviewid‘, ctrlReviews.reviewReadOne);
router.put(‘/locations/:locationid/reviews/:reviewid‘, ctrlReviews.reviewUpdateOne);
router.delete(‘/locations/:locationid/reviews/:reviewid‘, ctrlReviews.reviewDeleteOne);

module.exports = router

控制器写法:

/**
 * Created by sahara on 2016/7/6.
 */

var mongoose = require(‘mongoose‘);
var Loc = mongoose.model(‘Location‘);

var sendJsonResponse = function(res, status, content) {
    res.status(status);
    res.json(content);
};

module.exports.locationsListByDistance = function (req, res) {
    sendJsonResponse(res, 200, {"status" : "success"});
};

module.exports.locationsCreate = function (req, res) {
    sendJsonResponse(res, 201, {"status" : "success"});
};

module.exports.locationsReadOne = function (req, res) {
    if (req.params && req.params.locationid){
        Loc
            .findById(req.params.locationid)
            .exec(function(err, location){
                if (!location) {
                    sendJsonResponse(res, 404, {
                        "message": "locationid not found"
                    });
                    return;
                } else if (err) {
                    sendJsonResponse(res, 404, err);
                    return;
                }
                sendJsonResponse(res, 200, location);
            });
    } else {
        sendJsonResponse(res, 404, {
            "message": "no locationid in request"
        });
    }
};

module.exports.locationsUpdateOne = function (req, res) {
    sendJsonResponse(res, 200, {"status" : "success"});
};

module.exports.locationsDeleteOne = function (req, res) {
    sendJsonResponse(res, 204, {"status" : "success"});
};

app.js的改装:

var express = require(‘express‘);
var path = require(‘path‘);
var favicon = require(‘serve-favicon‘);
var logger = require(‘morgan‘);
var cookieParser = require(‘cookie-parser‘);
var bodyParser = require(‘body-parser‘);
require(‘./app_api/models/db‘);

var routes = require(‘./app_server/routes/index‘);
var routesApi = require(‘./app_api/routes/index‘);
var users = require(‘./app_server/routes/users‘);

var app = express();

// view engine setup
app.set(‘views‘, path.join(__dirname, ‘app_server‘, ‘views‘));
app.set(‘view engine‘, ‘jade‘);

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, ‘public‘, ‘favicon.ico‘)));
app.use(logger(‘dev‘));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, ‘public‘)));

app.use(‘/‘, routes);
app.use(‘/api‘, routesApi);
app.use(‘/users‘, users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error(‘Not Found‘);
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get(‘env‘) === ‘development‘) {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render(‘error‘, {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render(‘error‘, {
    message: err.message,
    error: {}
  });
});


module.exports = app;

技术分享

MEAN,从MONGO DB里弄出点东东来啦,以REST风格显示JSON

标签:

原文地址:http://www.cnblogs.com/aguncn/p/5648289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!