如何使用Sequelize Query构建.json端点?

时间:2016-03-01 20:05:06

标签: rest express sequelize.js

为了解决这个问题而奋斗了一个半星期,我想知道如何获得来自Sequelize ORM查询的.json端点。目前它记录了404错误" GET / api / users 404 3ms"。你可能听说过Sequelize的文档非常有限,我在教程之后一直在搜索github repo,到目前为止还没有工作,所以我想我会在这里问。

一小段摘录(https://github.com/NatuMyers/A.M.E.N.SQL-Stack上的代码):

// VARS -----------------------------
var express        = require('express')
  , bodyParser     = require('body-parser')
  , errorHandler   = require('errorhandler')
  , methodOverride = require('method-override')
  , morgan         = require('morgan')
  , http           = require('http')
  , path           = require('path')
  , db             = require('./models')

var router = require('express').Router();
var app = express()

// all environments
app.set('port', process.env.PORT || 3000)
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(morgan('dev'))
app.use(bodyParser())
app.use(methodOverride())
app.use(express.static(path.join(__dirname, 'public')))

// SEQUELIZE MODELS 
var userVar     = require('./models/user');

// dev only
 if ('development' === app.get('env')) {
      app.use(errorHandler())
}

// Make db, and make it listen 
db
.sequelize
.sync()
.complete(function(err) {
    if (err) {
    throw err
    } else {
              http.createServer(app).listen(app.get('port'), function() {
              console.log('Express server listening on port ' + app.get('port'))
            })
    }
    })

// HTTP GET endpoints
module.exports = function() {

  router.get('/', function(req, res, next){
      res.json({ message: 'This works at localhost:3000/api but getting a list of users is a pain :(' });
  });

  // question
  router.get('/users', function(req, res, next){
      res.json(/* I need to make sequelize send a part of the User db here. */);
  });

return router;
};

1 个答案:

答案 0 :(得分:0)

我通过使用Epilogue.js(以一种普通的方式)继续这样做。

我在Sequelize中添加了INLINE模型(我浪费了大量时间尝试导入模型),然后添加任何中间件并根据下面的语法创建restful api。

// 1. ADD SEQUELIZE MODELS ---- ---- ---- ----
var database = new Sequelize('raptroopdb', 'root', 'strongpassword');

var Employee = database.define('Employee', {
    name: Sequelize.STRING,
    hireDate: Sequelize.DATE
});

// Add Account model with foreign key constraint to Employee
var Account = database.define('Account', {
    name: Sequelize.STRING,
    managerId: {
        type: Sequelize.INTEGER,

        references: {
            // This is a reference to model Employee
            model: Employee,

            // This is the column name of the referenced model
            key: 'id',

        }
    }
});

// 2. ROOM FOR MIDDLEWARE to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('In server.js');

    // make sure we go to the next routes and don't stop here
    next();
});

// Initialize epilogue
epilogue.initialize({
    app: app,
    sequelize: database
});

app.use(express.static(__dirname + "/public"));
app.get('/', function(req, res) {
    res.redirect('/public/index.html');
});



// 3. Create REST resource
var employeeResource = epilogue.resource({
    model: Employee,
    endpoints: ['/api/employees', '/api/employees/:id']
});

var acctResource = epilogue.resource({
    model: Account,
    endpoints: ['/api/accounts', '/api/accounts/:id']
});

// Create database and listen
database
    .sync({
        force: false
    })
    .then(function() {
        app.listen(port, function() {
            console.log('listening at %s', port);
        });
    });