代码之家  ›  专栏  ›  技术社区  ›  SirRupertIII

如何传入“app”,以便在model.js文件中创建端点?

  •  1
  • SirRupertIII  · 技术社区  · 6 年前

    app 我可以直接从那里添加端点。我在用Sequelize。我的一个模型看起来像这样:

    const user = function (sequelize, DataTypes) {
    const User = sequelize.define('user', {
           id: {
               type: DataTypes.STRING,
               primaryKey: true,
               unique: true
           },
           name: {
               type: DataTypes.STRING,
           },
           email: {
               type: DataTypes.STRING,
           },
       });
    
    
       return User;
    };
    
    module.exports = user;
    

    我创造 具有 var app = express(); server.js

      const Sequelize = require('sequelize');
    
      const sequelize = new Sequelize('carswaddle', 'kylekendall', 'password', {
        dialect: 'postgres',
      });
    
      const models = {
        User: sequelize.import('./user'),
        Service: sequelize.import('./service'),
      };
    
      Object.keys(models).forEach(key => {
        if ('associate' in models[key]) {
          models[key].associate(models);
        }
      });
    
      models.sequelize = sequelize;
      models.Sequelize = Sequelize;
    
      module.exports = models;
    

    1 回复  |  直到 6 年前
        1
  •  3
  •   Rahul Sharma    6 年前

    您可以通过此博客开始了解最佳实践和文件结构

    应用程序的入口点应该这样定义

    // This will be our application entry. We'll setup our server here.
    const http = require('http');
    const app = require('../app'); // The express app we just created
    
    const port = parseInt(process.env.PORT, 10) || 8000;
    app.set('port', port);
    
    const server = http.createServer(app);
    server.listen(port);
    

    在这种情况下,您只能启动express服务器。

    https://scotch.io/tutorials/getting-started-with-node-express-and-postgres-using-sequelize

    你的应用程序的文件夹结构应该是这样的,你可以根据自己的方便进行自定义,但应该类似于此

    ├── app.js
    ├── bin
    │   └── www
    ├── package.json
    └── server
        ├── config
        │   └── config.json
        ├── migrations
        ├── models
        │   └── index.js
        └── seeders
    

    现在您的模型文件夹将包含所有数据库模型。

    const express = require('express');
    const logger = require('morgan');
    const bodyParser = require('body-parser');
    
    const app = express();
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    
    // Require our routes into the application.
    require('./server/routes')(app);
    app.get('*', (req, res) => res.status(200).send({
      message: 'Welcome to the beginning of nothingness.',
    }));
    
    module.exports = app;
    

    要编写控制器,应该在控制器中导入模型。

    const Todo = require('../models').Todo;
    
    module.exports = {
      create(req, res) {
        return Todo
          .create({
            title: req.body.title,
          })
          .then(todo => res.status(201).send(todo))
          .catch(error => res.status(400).send(error));
      },
    };