node.js: mssql2019 sequelize6 es6+ ORM in vscode and WebStorm 2023.1

news2024/9/28 21:25:07

mssql:

insert into [dbo].[tutorials]([title],[description],[published],[createdAt],[updatedAt])
values(N'涂聚文',N'涂聚文',0,'2025-05-04','2025-05-04');
go
insert into [dbo].[tutorials]([title],[description],[published],[createdAt],[updatedAt])
values(N'geovindu',N'geovindu',1,'2025-05-04','2025-05-04');
go
 
select * from [dbo].[tutorials]
go
 
insert into userinfos([userName],[userReal],[userPassword],[userIsOk],[userMail],[userMobile],[createdAt],[updatedAt]) values('geovindu','塗聚文','geovindu',1,'geovindu@163.com','13824350518','2025-07-09','2025-09-01')
go
 
select * from userinfos
go
/*
 *                   江城子 . 程序员之歌
 * 
 *               十年生死两茫茫,写程序,到天亮。
 *                   千行代码,Bug何处藏。
 *               纵使上线又怎样,朝令改,夕断肠。
 * 
 *               领导每天新想法,天天改,日日忙。
 *                   相顾无言,惟有泪千行。
 *               每晚灯火阑珊处,夜难寐,加班狂。
 * 
 * 
 * @Author: geovindu
 * @Date: 2024-08-14 22:25:22
 * @LastEditors: geovindu
 * @LastEditTime: 2024-08-14 12:21:48
 * @FilePath: \vue\vuejs\nodesql\dbConfig.js
 * @Description: geovindu
 * 
 * @IDE: vscode
 * @js lib: node 20 vue.js 3.0
 * @database: sql server 2019
 * Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved. 
 */

/*
const dbConfig = {
    server: "DESKTOP-OAS00A4",
    port: 1433,
    user: "geovindu",
    password: "geovindu",
    database: "geovindu",
    dialect: "mssql",
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    }
  };
   */

  const dbConfig = {
    HOST: "DESKTOP-OAS00A4",
    PORT: "1433",
    USER: "geovindu",
    PASSWORD: "geovindu",
    DB: "geovindu",
    dialect: "mssql",
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    }
  };


  export default dbConfig;


/**
 * https://nodejs.cn/api/http/http_request_url_options_callback.html
 * node --trace-deprecation server //检查具体问题
 * models/tutorial.model.js
 */
/**
 * 
 * @param {*} sequelize 
 * @param {*} Sequelize 
 * @returns 
 */
const Tutorial  = (sequelize, Sequelize) => {
    const Tutorial = sequelize.define("tutorial", {
      title: {
        type: Sequelize.STRING
      },
      description: {
        type: Sequelize.STRING
      },
      published: {
        type: Sequelize.BOOLEAN
      }
    });
   
    return Tutorial;
  };
 
  export default Tutorial;

/*
 * 
 *    ┏┓   ┏┓
 *  ┏┛┻━━━┛┻┓
 *  ┃       ┃
 *  ┃   ━   ┃
 *  ┃ >   < ┃
 *  ┃       ┃
 *  ┃... ⌒ ... ┃
 *  ┃       ┃
 *  ┗━┓   ┏━┛
 *      ┃   ┃ 
 *      ┃   ┃
 *      ┃   ┃
 *      ┃   ┃  神兽保佑
 *      ┃   ┃  代码无bug  
 *      ┃   ┃
 *      ┃   ┗━━━┓
 *      ┃       ┣┓
 *      ┃       ┏┛
 *      ┗┓┓┏━┳┓┏┛
 *        ┃┫┫ ┃┫┫
 *        ┗┻┛ ┗┻┛
 * 
 * @Author: geovindu
 * @Date: 2024-08-14 10:32:27
 * @LastEditors: geovindu
 * @LastEditTime: 2024-08-14 22:55:55
 * @FilePath: \vue\vuejs\nodesql\models\userinfo.model.js
 * @Description: geovindu
 * 
 * @IDE: vscode
 * @js lib: node 20 vue.js 3.0
 * @database: sql server 2019
 * Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved. 
 */

/**
 * 参考: https://sequelize.org/docs/v6/core-concepts/assocs/  ORM 关系 一对一,一对多,多对多,多对一
 */
/**
 * 
 * @param {*} sequelize 
 * @param {*} Sequelize 
 * @returns 
 */
const UserInfo = (sequelize, Sequelize) => {
    const UserInfo = sequelize.define("userInfo", {
      userName: {
        type: Sequelize.STRING
      },
      userReal:{
        type:Sequelize.STRING
      },
      userPassword: {
        type: Sequelize.STRING
      },
      userIsOk: {
        type: Sequelize.BOOLEAN
      },
      userMail:
      {
        type:Sequelize.STRING
      },
      userMobile:
      {
 
        type:Sequelize.STRING
         
      }
    });
    
    return UserInfo;
  };
  
  export default UserInfo;

/**
 * https://nodejs.cn/api/http/http_request_url_options_callback.html
 * node --trace-deprecation server //检查具体问题
 * models/tutorial.model.js
 */
/**
 * 
 * @param {*} sequelize 
 * @param {*} Sequelize 
 * @returns 
 */
const Tutorial  = (sequelize, Sequelize) => {
    const Tutorial = sequelize.define("tutorial", {
      title: {
        type: Sequelize.STRING
      },
      description: {
        type: Sequelize.STRING
      },
      published: {
        type: Sequelize.BOOLEAN
      }
    });
   
    return Tutorial;
  };
 
  export default Tutorial;



/*
 * _______________#########_______________________ 
 * ______________############_____________________ 
 * ______________#############____________________ 
 * _____________##__###########___________________ 
 * ____________###__######_#####__________________ 
 * ____________###_#######___####_________________ 
 * ___________###__##########_####________________ 
 * __________####__###########_####_______________ 
 * ________#####___###########__#####_____________ 
 * _______######___###_########___#####___________ 
 * _______#####___###___########___######_________ 
 * ______######___###__###########___######_______ 
 * _____######___####_##############__######______ 
 * ____#######__#####################_#######_____ 
 * ____#######__##############################____ 
 * ___#######__######_#################_#######___ 
 * ___#######__######_######_#########___######___ 
 * ___#######____##__######___######_____######___ 
 * ___#######________######____#####_____#####____ 
 * ____######________#####_____#####_____####_____ 
 * _____#####________####______#####_____###______ 
 * ______#####______;###________###______#________ 
 * ________##_______####________####______________ 
 * 
 * @Author: geovindu
 * @Date: 2024-08-14 09:44:36
 * @LastEditors: geovindu
 * @LastEditTime: 2024-08-14 22:50:54
 * @FilePath: \vue\vuejs\nodesql\models\index.js
 * @Description: geovindu
 * https://sequelize.org/docs/v7/databases/mssql/
 * https://github.com/tediousjs/node-mssql
 * https://github.com/tediousjs/tedious
 * @IDE: vscode npm i @sequelize/mssql
 * @js lib: node 20 vue.js 3.0
 * @database: sql server 2019
 * Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved. 
 */


//import { Sequelize } from '@sequelize/core';
//import { MsSqlDialect } from '@sequelize/mssql';

import Sequelize from "sequelize";
import tutorials from "./tutorial.model.js"
import dbConfig from "../dbConfig.js";
import userinfos from "./userinfo.model.js"

/*
const sequelize = new Sequelize({
  dialect: MsSqlDialect,
  server: dbConfig.server,
  port: dbConfig.port,
  database: dbConfig.database,
  authentication: {
    type: 'ntlm', //default
    options: {
      userName: dbConfig.user,
      password: dbConfig.password,
    },
  },
});
*/

/**
 * 
 * 
 */
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
    host: dbConfig.HOST,
    port: dbConfig.PORT,
    dialect: dbConfig.dialect,
    pool: {
      max: dbConfig.pool.max,
      min: dbConfig.pool.min,
      acquire: dbConfig.pool.acquire,
      idle: dbConfig.pool.idle,
    },
  });

const db = {};
 
db.Sequelize = Sequelize;
db.sequelize = sequelize;
 
db.tutorials = tutorials(sequelize, Sequelize); //
db.userinfos = userinfos(sequelize, Sequelize);  //
 
export default db;


/**
 * https://github.com/tediousjs/node-mssql
 * controllers/tutorial.controller.js
 * sql server 2019
 */
import db from  "../models/index.js";
 
const Tutorial = db.tutorials;
const Op = db.Sequelize.Op;
 

/**
 * 
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
const create = (req, res) => {
    // Validate request
    if (!req.body.title) {
      res.status(400).send({
        message: "Content can not be empty!"
      });
      return;
    }
   
    // Create a Tutorial
    const tutorial = {
      title: req.body.title,
      description: req.body.description,
      published: req.body.published ? req.body.published : false
    };
   
    // Save Tutorial in the database
    Tutorial.create(tutorial)
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while creating the Tutorial."
        });
      });
  };

  /**
   * 
   * @param {*} req 
   * @param {*} res 
   */
  const findAll = (req, res) => {
    const title = req.query.title;
    var condition = title ? { title: { [Op.like]: `%${title}%` } } : null;
   
    Tutorial.findAll({ where: condition })
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving tutorials."
        });
      });
  };
 
  /**
   * 
   * @param {*} req 
   * @param {*} res 
   */
  const findOne = (req, res) => {
    const id = req.params.id;
   
    Tutorial.findByPk(id)
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message: "Error retrieving Tutorial with id=" + id
        });
      });
  };
 
  /**
   * 
   * @param {*} req 
   * @param {*} res 
   */
  const update = (req, res) => {
    const id = req.params.id;
   
    Tutorial.update(req.body, {
      where: { id: id }
    })
      .then(num => {
        if (num == 1) {
          res.send({
            message: "Tutorial was updated successfully."
          });
        } else {
          res.send({
            message: `Cannot update Tutorial with id=${id}. Maybe Tutorial was not found or req.body is empty!`
          });
        }
      })
      .catch(err => {
        res.status(500).send({
          message: "Error updating Tutorial with id=" + id
        });
      });
  };
 
  /**
   * 
   * @param {*} req 
   * @param {*} res 
   */
  const deleteid = (req, res) => {
    const id = req.params.id;
   
    Tutorial.destroy({
      where: { id: id }
    })
      .then(num => {
        if (num == 1) {
          res.send({
            message: "Tutorial was deleted successfully!"
          });
        } else {
          res.send({
            message: `Cannot delete Tutorial with id=${id}. Maybe Tutorial was not found!`
          });
        }
      })
      .catch(err => {
        res.status(500).send({
          message: "Could not delete Tutorial with id=" + id
        });
      });
  };
 
  /**
   * 
   * @param {*} req 
   * @param {*} res 
   */
  const deleteAll = (req, res) => {
    Tutorial.destroy({
      where: {},
      truncate: false
    })
      .then(nums => {
        res.send({ message: `${nums} Tutorials were deleted successfully!` });
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while removing all tutorials."
        });
      });
  };
 
  /**
   * 
   * @param {*} req 
   * @param {*} res 
   */
  const findAllPublished = (req, res) => {
    Tutorial.findAll({ where: { published: true } })
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving tutorials."
        });
      });
  };
 
  export default
  {
    findAllPublished,
    deleteAll,
    deleteid,
    update,
    findOne,
    findAll,
    create
  };


/**
 * https://github.com/sequelize/sequelize
 * sql server 2019
 * controllers/userinfo.controller.js
 */

import db  from "../models/index.js";
  
const UserInfo = db.userinfos;
const Op = db.Sequelize.Op;
  
/**
 * 添加记录
 * @param {*} req
 * @param {*} res
 * @returns
 */
 const usercreate = (req, res) => {
    // Validate request
    if (!req.body.title) {
      res.status(400).send({
        message: "Content can not be empty!"
      });
      return;
    }
    
    // Create a Tutorial
    const userInfo = {
      userName: req.body.userName,
      userReal:req.body.userReal,
      userPassword: req.body.userPassword,
      userIsOk: req.body.userIsOk ? req.body.userIsOk : false,
      userMail:req.body.userMail,
      userMobile:req.body.userMobile
    };
    
    // Save Tutorial in the database
    UserInfo.create(userInfo)
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while creating the userinfos."
        });
      });
  };
  
/**
 * 查看所有记录
 * @param {*} req
 * @param {*} res
 */
  
const  userfindAll = (req, res) => {
    const userName = req.query.userName;
    var condition = userName ? { userName: { [Op.like]: `%${userName}%` } } : null;
    
    UserInfo.findAll({ where: condition })
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving userinfos."
        });
      });
  };
  
/**
 * 查找一条记录
 * @param {*} req
 * @param {*} res
 */
const userfindOne = (req, res) => {
    const id = req.params.id;
    
    UserInfo.findByPk(id)
      .then(data => {
        if (data) {
          res.send(data);
        } else {
          res.status(404).send({
            message: `Cannot find userinfos with id=${id}.`
          });
        }
      })
      .catch(err => {
        res.status(500).send({
          message: "Error retrieving userinfos with id=" + id
        });
      });
  };
  
  
/**
 * 更新记录
 * @param {*} req
 * @param {*} res
 */
const userupdate = (req, res) => {
    const id = req.params.id;
    
    UserInfo.update(req.body, {
      where: { id: id }
    })
      .then(num => {
        if (num == 1) {
          res.send({
            message: "usrinfos was updated successfully."
          });
        } else {
          res.send({
            message: `Cannot update userinfos with id=${id}. Maybe userinfos was not found or req.body is empty!`
          });
        }
      })
      .catch(err => {
        res.status(500).send({
          message: "Error updating userinfos with id=" + id
        });
      });
  };
  
/**
 * 删除了一条记录
 * @param {*} req
 * @param {*} res
 */
const userdeleteid = (req, res) => {
    const id = req.params.id;
    
    UserInfo.destroy({
      where: { id: id }
    })
      .then(num => {
        if (num == 1) {
          res.send({
            message: "userinfos was deleted successfully!"
          });
        } else {
          res.send({
            message: `Cannot delete userinfos with id=${id}. Maybe userinfos was not found!`
          });
        }
      })
      .catch(err => {
        res.status(500).send({
          message: "Could not delete userinfos  with id=" + id
        });
      });
  };
  
/**
 * 删除所有记录
 * @param {*} req
 * @param {*} res
 */
const userdeleteAll = (req, res) => {
    UserInfo.destroy({
      where: {},
      truncate: false
    })
      .then(nums => {
        res.send({ message: `${nums} userinfos were deleted successfully!` });
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while removing all userinfos."
        });
      });
  };
  
  
    
  
/**
 * 查找有效的会员记录
 * @param {*} req 变量
 * @param {*} res 变量
 */
const findAlluserIsOk = (req, res) => {
     
    UserInfo.findAll({ where: { userIsOk: true } })
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving userinfos."
        });
      });
  };
  
  

// 使用 ES6 的默认导出语法,直接导出包含所有函数的对象
 export default
  {
    findAlluserIsOk,
    userdeleteAll,
    userdeleteid,
    userupdate,
    userfindOne,
    userfindAll,
    usercreate
  };


/*
 * 
 *   ┏┓   ┏┓+ +
 *  ┏┛┻━━━┛┻┓ + +
 *  ┃       ┃  
 *  ┃   ━   ┃ ++ + + +
 *  ████━████ ┃+
 *  ┃       ┃ +
 *  ┃   ┻   ┃
 *  ┃       ┃ + +
 *  ┗━┓   ┏━┛
 *    ┃   ┃           
 *    ┃   ┃ + + + +
 *    ┃   ┃
 *    ┃   ┃ +  神兽保佑
 *    ┃   ┃    代码无bug  
 *    ┃   ┃  +         
 *    ┃    ┗━━━┓ + +
 *    ┃        ┣┓
 *    ┃        ┏┛
 *    ┗┓┓┏━┳┓┏┛ + + + +
 *     ┃┫┫ ┃┫┫
 *     ┗┻┛ ┗┻┛+ + + +
 * 
 * 
 * @Author: geovindu
 * @Date: 2024-08-14 22:51:57
 * @LastEditors: geovindu
 * @LastEditTime: 2024-08-14 22:57:11
 * @FilePath: \vue\vuejs\nodesql\routes\turorial.routes.js
 * @Description: geovindu
 * 
 * @IDE: vscode
 * @js lib: node 20 vue.js 3.0
 * @database: sql server 2019
 * Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved. 
 */



import express from "express"
import tutorials from "../controllers/tutorial.controller.js"
import userinfos from "../controllers/userinfo.controller.js"


const routes = app => {
     
   
    var router = express.Router();
   
  // Create a new Tutorial
    //app.post("/", Tutorial.findAll);
    router.post("/tutorials",tutorials.create)
 
    router.post("/user",userinfos.usercreate)
 
  
    // Retrieve all Tutorials
    router.get("/tutorials", tutorials.findAll);
 
    router.get("/user", userinfos.userfindAll);
 
  /**/
    // Retrieve all published Tutorials
    router.get("/tutorials/published", tutorials.findAll);
 
    router.get("/user/userIsOk", userinfos.findAlluserIsOk);
    
    // Retrieve a single Tutorial with id
    router.get("/user/:id", userinfos.userfindOne);
 
    router.get("tutorials/:id", tutorials.findOne);
    
    // Update a Tutorial with id
    router.put("tutorials/:id", tutorials.update);
 
    router.put("/user/:id", userinfos.userupdate);
    
    // Delete a Tutorial with id
    router.put("tutorials/:id", tutorials.deleteid);
 
    router.put("/user/:id", userinfos.userdeleteid);
 
    // Delete all Tutorials
    router.put("/tutorials", tutorials.deleteAll);
    router.put("/user", userinfos.userdeleteAll);

  
    //app.use('/api/tutorials', router);
    app.use('/api',router);

  };
 
  export default routes;

/*
 *  ┌───┐   ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┐
 *  │Esc│   │ F1│ F2│ F3│ F4│ │ F5│ F6│ F7│ F8│ │ F9│F10│F11│F12│ │P/S│S L│P/B│  ┌┐    ┌┐    ┌┐
 *  └───┘   └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┘  └┘    └┘    └┘
 *  ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───────┐ ┌───┬───┬───┐ ┌───┬───┬───┬───┐
 *  │~ `│! 1│@ 2│# 3│$ 4│% 5│^ 6│& 7│* 8│( 9│) 0│_ -│+ =│ BacSp │ │Ins│Hom│PUp│ │N L│ / │ * │ - │
 *  ├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─────┤ ├───┼───┼───┤ ├───┼───┼───┼───┤
 *  │ Tab │ Q │ W │ E │ R │ T │ Y │ U │ I │ O │ P │{ [│} ]│ | \ │ │Del│End│PDn│ │ 7 │ 8 │ 9 │   │
 *  ├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴─────┤ └───┴───┴───┘ ├───┼───┼───┤ + │
 *  │ Caps │ A │ S │ D │ F │ G │ H │ J │ K │ L │: ;│" '│ Enter  │               │ 4 │ 5 │ 6 │   │
 *  ├──────┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴────────┤     ┌───┐     ├───┼───┼───┼───┤
 *  │ Shift  │ Z │ X │ C │ V │ B │ N │ M │< ,│> .│? /│  Shift   │     │ ↑ │     │ 1 │ 2 │ 3 │   │
 *  ├─────┬──┴─┬─┴──┬┴───┴───┴───┴───┴───┴──┬┴───┼───┴┬────┬────┤ ┌───┼───┼───┐ ├───┴───┼───┤ E││
 *  │ Ctrl│    │Alt │         Space         │ Alt│    │    │Ctrl│ │ ← │ ↓ │ → │ │   0   │ . │←─┘│
 *  └─────┴────┴────┴───────────────────────┴────┴────┴────┴────┘ └───┴───┴───┘ └───────┴───┴───┘
 * 
 * @Author: geovindu
 * @Date: 2024-08-14 22:53:38
 * @LastEditors: geovindu
 * @LastEditTime: 2024-08-14 22:34:37
 * @FilePath: \vue\vuejs\nodesql\server.js
 * @Description: geovindu
 * backend  frontend
 * @IDE: vscode
 * @js lib: node 20 vue.js 3.0
 * @database: sql server 2019
 * Copyright (c) geovindu 2024 by geovindu@163.com, All Rights Reserved. 
 */



import express from "express";
import  cors from "cors";
import routes from "./routes/turorial.routes.js"
import db from "./models/index.js"
 
const app = express();
 
 
 
var corsOptions = {
  origin: "http://localhost:8083"
};
 
app.use(cors(corsOptions));
 
// parse requests of content-type - application/json
app.use(express.json());
 
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
 
 
 
//http://localhost:8080/models
///http://localhost:8082/api/tutorials
//http://localhost:8082/api/tutorials/2
//http://localhost:8082/api/user
//const db = require("./app/models");
db.sequelize.sync()
  .then(() => {
    console.log("Synced db.");
  })
  .catch((err) => {
    console.log("Failed to sync db: " + err.message);
  });
   
 routes(app); //
 
// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});
 
// set port, listen for requests
const PORT = process.env.PORT || 8082;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});



运行:

node server

也可以运行,查看BUG

node --trace-deprecation server

WebStorm 2023.1:

/**
 *  config/db.config.js
 *  node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mssql 2019
 * npm install express sequelize tedious cors
 * */


/**
 *
 * @type {{dialect: string, PORT: string, PASSWORD: string, pool: {min: number, max: number, idle: number, acquire: number}, HOST: string, USER: string, DB: string}}
 */
module.exports = {
  HOST: "DESKTOP-OAS00A4",
  PORT: "1433",
  USER: "geovindu",
  PASSWORD: "geovindu",
  DB: "geovindu",
  dialect: "mssql",
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
};



/**
 @description WebStorm
 @author geovindu  geovindu
 @project vuedemo
 @package
 @file userinfo.model.js
 @ide webstorm 2023.1
 @database sql server 2019
 @dev node 20 vue.js 3.0
 @date Created in 20:50 2024/08/15
 @edate eddit in
 */


/**
 * userInfo 实体类
 * @param sequelize
 * @param Sequelize
 * @returns {*}
 */
module.exports = (sequelize, Sequelize) => {
    const UserInfo = sequelize.define("userInfo", {
        userName: {
            type: Sequelize.STRING
        },
        userReal:{
            type:Sequelize.STRING
        },
        userPassword: {
            type: Sequelize.STRING
        },
        userIsOk: {
            type: Sequelize.BOOLEAN
        },
        userMail:
            {
                type:Sequelize.STRING
            },
        userMobile:
            {

                type:Sequelize.STRING

            }
    });

    return UserInfo;
};



/**
 * models/tutorial.model.js
 *  node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mssql 2019
 * npm install express sequelize tedious cors
 * */


/**
 *
 * @param sequelize
 * @param Sequelize
 * @returns {*}
 */
module.exports = (sequelize, Sequelize) => {
  const Tutorial = sequelize.define("tutorial", {
    title: {
      type: Sequelize.STRING
    },
    description: {
      type: Sequelize.STRING
    },
    published: {
      type: Sequelize.BOOLEAN
    }
  });

  return Tutorial;
};


/**
 @description WebStorm
 @author geovindu  geovindu
 @project vuedemo
 @package
 @file userinfo.model.js
 @ide webstorm 2023.1
 @database sql server 2019
 @dev node 20 vue.js 3.0
 @date Created in 20:50 2024/08/15
 @edate eddit in
 */


/**
 * userInfo 实体类
 * @param sequelize
 * @param Sequelize
 * @returns {*}
 */
module.exports = (sequelize, Sequelize) => {
    const UserInfo = sequelize.define("userInfo", {
        userName: {
            type: Sequelize.STRING
        },
        userReal:{
            type:Sequelize.STRING
        },
        userPassword: {
            type: Sequelize.STRING
        },
        userIsOk: {
            type: Sequelize.BOOLEAN
        },
        userMail:
            {
                type:Sequelize.STRING
            },
        userMobile:
            {

                type:Sequelize.STRING

            }
    });

    return UserInfo;
};


/**
 * models/index.js
 *  node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mssql 2019
 * npm install express sequelize tedious cors
 * */



const dbConfig = require("../config/db.config.js");

const Sequelize = require("sequelize");

/**
 *
 */
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  port: dbConfig.PORT,
  dialect: dbConfig.dialect,
  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle,
  },
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

//关联对象 tutorials 表
db.tutorials = require("./tutorial.model.js")(sequelize, Sequelize);
//关联对象 userinfos 表
db.userinfos = require("./userinfo.model.js")(sequelize, Sequelize);

module.exports = db;


/**
 @description WebStorm
 @author geovindu  geovindu
 @project vuedemo
 @package
 @file userinfo.controller.js
 @ide webstorm 2023.1
 @database mysql 8.0 sql server 2019
 @dev node 20 vue.js 3.0
 @date Created in 20:56 2024/08/15
 @edate eddit in
 */

const db = require("../models");


const UserInfo = db.userinfos;
const Op = db.Sequelize.Op;

/**
 * 添加记录
 * @param {*} req
 * @param {*} res
 * @returns
 */
exports.usercreate = (req, res) => {
    // Validate request
    if (!req.body.title) {
        res.status(400).send({
            message: "Content can not be empty!"
        });
        return;
    }

    // Create a Tutorial
    const userInfo = {
        userName: req.body.userName,
        userReal:req.body.userReal,
        userPassword: req.body.userPassword,
        userIsOk: req.body.userIsOk ? req.body.userIsOk : false,
        userMail:req.body.userMail,
        userMobile:req.body.userMobile
    };

    // Save Tutorial in the database
    UserInfo.create(userInfo)
        .then(data => {
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message:
                    err.message || "Some error occurred while creating the userinfos."
            });
        });
};

/**
 * 查看所有记录
 * @param {*} req
 * @param {*} res
 */

exports.userfindAll = (req, res) => {
    const userName = req.query.userName;
    var condition = userName ? { userName: { [Op.like]: `%${userName}%` } } : null;

    UserInfo.findAll({ where: condition })
        .then(data => {
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message:
                    err.message || "Some error occurred while retrieving userinfos."
            });
        });
};

/**
 * 查找一条记录
 * @param {*} req
 * @param {*} res
 */
exports.userfindOne = (req, res) => {
    const id = req.params.id;

    UserInfo.findByPk(id)
        .then(data => {
            if (data) {
                res.send(data);
            } else {
                res.status(404).send({
                    message: `Cannot find userinfos with id=${id}.`
                });
            }
        })
        .catch(err => {
            res.status(500).send({
                message: "Error retrieving userinfos with id=" + id
            });
        });
};


/**
 * 更新记录
 * @param {*} req
 * @param {*} res
 */
exports.userupdate = (req, res) => {
    const id = req.params.id;

    UserInfo.update(req.body, {
        where: { id: id }
    })
        .then(num => {
            if (num == 1) {
                res.send({
                    message: "usrinfos was updated successfully."
                });
            } else {
                res.send({
                    message: `Cannot update userinfos with id=${id}. Maybe userinfos was not found or req.body is empty!`
                });
            }
        })
        .catch(err => {
            res.status(500).send({
                message: "Error updating userinfos with id=" + id
            });
        });
};

/**
 * 删除了一条记录
 * @param {*} req
 * @param {*} res
 */
exports.userdeleteid = (req, res) => {
    const id = req.params.id;

    UserInfo.destroy({
        where: { id: id }
    })
        .then(num => {
            if (num == 1) {
                res.send({
                    message: "userinfos was deleted successfully!"
                });
            } else {
                res.send({
                    message: `Cannot delete userinfos with id=${id}. Maybe userinfos was not found!`
                });
            }
        })
        .catch(err => {
            res.status(500).send({
                message: "Could not delete userinfos  with id=" + id
            });
        });
};

/**
 * 删除所有记录
 * @param {*} req
 * @param {*} res
 */
exports.userdeleteAll = (req, res) => {
    UserInfo.destroy({
        where: {},
        truncate: false
    })
        .then(nums => {
            res.send({ message: `${nums} userinfos were deleted successfully!` });
        })
        .catch(err => {
            res.status(500).send({
                message:
                    err.message || "Some error occurred while removing all userinfos."
            });
        });
};




/**
 * 查找有效的会员记录
 * @param {*} req 变量
 * @param {*} res 变量
 */
exports.findAlluserIsOk = (req, res) => {

    UserInfo.findAll({ where: { userIsOk: true } })
        .then(data => {
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message:
                    err.message || "Some error occurred while retrieving userinfos."
            });
        });
};



/**
 * controllers/tutorial.controller.js
 *  node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mssql 2019
 * npm install express sequelize tedious cors
 * */


const db = require("../models");
const Tutorial = db.tutorials;
const Op = db.Sequelize.Op;

// Create and Save a new Tutorial
exports.create = (req, res) => {
  // Validate request
  if (!req.body.title) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
    return;
  }

  // Create a Tutorial
  const tutorial = {
    title: req.body.title,
    description: req.body.description,
    published: req.body.published ? req.body.published : false
  };

  // Save Tutorial in the database
  Tutorial.create(tutorial)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Tutorial."
      });
    });
};

// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
  const title = req.query.title;
  var condition = title ? { title: { [Op.like]: `%${title}%` } } : null;

  Tutorial.findAll({ where: condition })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });
};

// Find a single Tutorial with an id
exports.findOne = (req, res) => {
  const id = req.params.id;

  Tutorial.findByPk(id)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message: "Error retrieving Tutorial with id=" + id
      });
    });
};

// Update a Tutorial by the id in the request
exports.update = (req, res) => {
  const id = req.params.id;

  Tutorial.update(req.body, {
    where: { id: id }
  })
    .then(num => {
      if (num == 1) {
        res.send({
          message: "Tutorial was updated successfully."
        });
      } else {
        res.send({
          message: `Cannot update Tutorial with id=${id}. Maybe Tutorial was not found or req.body is empty!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Error updating Tutorial with id=" + id
      });
    });
};

// Delete a Tutorial with the specified id in the request
exports.delete = (req, res) => {
  const id = req.params.id;

  Tutorial.destroy({
    where: { id: id }
  })
    .then(num => {
      if (num == 1) {
        res.send({
          message: "Tutorial was deleted successfully!"
        });
      } else {
        res.send({
          message: `Cannot delete Tutorial with id=${id}. Maybe Tutorial was not found!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Could not delete Tutorial with id=" + id
      });
    });
};

// Delete all Tutorials from the database.
exports.deleteAll = (req, res) => {
  Tutorial.destroy({
    where: {},
    truncate: false
  })
    .then(nums => {
      res.send({ message: `${nums} Tutorials were deleted successfully!` });
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while removing all tutorials."
      });
    });
};

// find all published Tutorial
exports.findAllPublished = (req, res) => {
  Tutorial.findAll({ where: { published: true } })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });
};


/**
 * routes/turorial.routers.js
 *  node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mssql 2019
 * npm install express sequelize tedious cors
 * ///http://localhost:8082/api/tutorials
 * //http://localhost:8082/api/tutorials/2
 * //http://localhost:8082/api/userinfos
 * */

/**
 *
 * @param app
 */
module.exports = app => {
  const tutorials = require("../controllers/tutorial.controller.js");
  const userinfos=require("../controllers/userinfo.controller")
  var router = require("express").Router();

// Create a new Tutorial
  router.post("/tutorials/", tutorials.create);
  //Create a new userinfo
  router.post("/userinfos/", userinfos.usercreate);


  // Retrieve all Tutorials
  router.get("/tutorials/", tutorials.findAll);
  //Retrieve all userinfos
  router.get("/userinfos/", userinfos.userfindAll);


  // Retrieve all published Tutorials
  router.get("/tutorials/published", tutorials.findAllPublished);
  //Retrieve all published userinfos
  router.get("/userinfos/", userinfos.findAlluserIsOk);

  // Retrieve a single Tutorial with id
  router.get("/tutorials/:id", tutorials.findOne);
  //Retrieve a single userinfos with id
  router.get("/userinfos/:id", userinfos.userfindOne);


  // Update a Tutorial with id
  router.put("/tutorials/:id", tutorials.update);
  //Update a userinfos with id
  router.put("/userinfos/:id", userinfos.userupdate);



  // Delete a Tutorial with id
  router.delete("/tutorials/:id", tutorials.delete);
  //Delete a userinfos with id
  router.delete("/userinfos/:id", userinfos.userdeleteid);

  // Delete all Tutorials
  router.delete("/tutorials/", tutorials.deleteAll);
  //Delete all userinfos
  router.delete("/userinfos/", userinfos.userdeleteAll);


  app.use('/api', router);
};


/**
 * server.js
 *  node 20 vue.js 3.0
 * ide: WebStorm 2023.1
 * mssql 2019
 * npm install express sequelize tedious cors
 * */


const express = require("express");
// const bodyParser = require("body-parser"); /* deprecated */
const cors = require("cors");

const app = express();

var corsOptions = {
  origin: "http://localhost:8083"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());  /* bodyParser.json() is deprecated */

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));   /* bodyParser.urlencoded() is deprecated */

const db = require("./models");

db.sequelize.sync();
// // drop the table if it already exists
// db.sequelize.sync({ force: true }).then(() => {
//   console.log("Drop and re-sync db.");
// });

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

require("./routes/turorial.routes")(app);

// set port, listen for requests
const PORT = process.env.PORT || 8082;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});


运行:

node server

自动创建表

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2052387.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

实战OpenCV之图像的属性

基础入门 图像的属性指的是描述图像基本信息的数据&#xff0c;包括但不限于&#xff1a;图像的尺寸、颜色通道数、像素数据类型等。这些属性对于图像处理非常重要&#xff0c;因为它们直接关系到如何正确地读取、处理和存储图像。常见的图像属性包括&#xff1a; 尺寸&#xf…

WandB 简明教程【Weights Bias】

在机器学习实验领域&#xff0c;调整超参数类似于微调复杂机器的旋钮和刻度盘。这些参数通常很微妙但至关重要&#xff0c;能够显著影响我们模型的性能和行为。WandB&#xff08;权重和偏差 ) 是一个强大的在线工具集&#xff0c;旨在简化模型训练、评估和分析的过程。 随着我…

TCP shutdown 之后~

目录 摘要 1 API 2 shutdown(sockfd, SHUT_WR) 3 shutdown(sockfd, SHUT_WR) 4 kernel 是怎么做的&#xff1f; 附 摘要 通过 shutdown() 关闭读写操作&#xff0c;会发生什么&#xff1f;具体点呢&#xff0c;考虑两个场景&#xff1a; 场景一&#xff1a;C 发送数据完毕…

VBA技术资料MF184:图片导入Word添加说明文字设置格式

我给VBA的定义&#xff1a;VBA是个人小型自动化处理的有效工具。利用好了&#xff0c;可以大大提高自己的工作效率&#xff0c;而且可以提高数据的准确度。“VBA语言専攻”提供的教程一共九套&#xff0c;分为初级、中级、高级三大部分&#xff0c;教程是对VBA的系统讲解&#…

C ++初阶:C++入门级知识点

&#x1f37a;0.前言 言C之言&#xff0c;聊C之识&#xff0c;以C会友&#xff0c;共向远方。各位博友的各位你们好啊&#xff0c;这里是持续分享C知识的小赵同学&#xff0c;今天要分享的C知识是C入门知识点&#xff0c;在这一章&#xff0c;小赵将会向大家展开聊聊C入门知识…

基于Mediapipe的手势识别系统 | OpenCV | Mediapipe | C++ | QT | Python | C# | Unity

基于Mediapipe的手势识别系统 OpenCV、Mediapipe C (QT)、Python (PyCharm)、C# (Visual Studio) Unity 3D 登录界面 图片手势识别 视频文件手势识别 摄像头实时手势识别 演示视频 基于Mediapipe的手势识别系统

UDP和TCP协议段格式分析

目录 UDP协议 特点 UDP协议的缓冲区 UDP协议段格式 TCP协议 特点 如何理解TCP是传输控制协议&#xff1f; TCP协议段格式 四位首部长度 16位窗口大小 32位序号 32位确认序号 TCP/IP四层模型&#xff1a; UDP协议 UDP&#xff08;User Datagram Protocol &#xff…

十大护眼落地灯品牌哪款好?十大护眼落地灯品牌

十大护眼落地灯品牌哪款好&#xff1f;根据国际市场的研究数据表明&#xff0c;我国在日常生活中对电子产品的依赖度极高&#xff0c;每天看电子产品的时间超过8小时&#xff0c;出现眼睛酸痛、干涩、视觉疲劳的人群也不再少数&#xff0c;而给眼睛带来伤害的除了电子产品中所含…

界面控件DevExpress ASP.NET Web Forms v24.1最新版本系统环境配置要求

本文档包含有关安装和使用 DevExpress ASP.NET Web Forms控件的系统要求的信息。 点击获取DevExpress v24.1正式版 .NET Framework DevExpress ASP.NET Web Forms控件支持以下.NET框架版本。 如果您需要 DevExpress 产品的早期版本&#xff0c;请直接戳这里联系我>> …

MySQL中的EXPLAIN的详解

一、介绍 官网介绍&#xff1a; https://dev.mysql.com/doc/refman/5.7/en/explain-output.htmlhttps://dev.mysql.com/doc/refman/8.0/en/explain-output.htmlexplain&#xff08;执行计划&#xff09;&#xff0c;使用explain关键字可以模拟优化器执行sql查询语句&#xff…

爆火的本地知识库项目是什么?什么是RAG?本地知识库与大模型的关系

“ 本地知识库就相当于大模型的外部资料库。” 很多人应该都听过本地知识库项目&#xff0c;它是当今人工智能领域爆火的项目之一&#xff0c;那么到底什么是本地知识库&#xff1f;它和大模型有什么关系&#xff1f;怎么构建本地知识库&#xff1f; 01 — 为什么需要本地知…

Docker的介绍、保姆级安装和使用

一、Docker简介 1.1、Docker是什么 Docker是一个用于开发、发布和运行应用程序的开放平台;使您能够将应用程序与基础设施分离,以便您可以快速交付软件。不像虚拟机那样笨重(比如:我需要将一个安装好nginx环境的内容分享给其他人: 方式一【使用虚拟】(应用程序Nginx与基…

系统架构设计师 - 软件工程(2)

软件工程 软件工程&#xff08;13-22分&#xff09;非常重要软件系统建模系统设计界面设计 ★★软件设计结构化设计 ★★面向对象设计 ★★★★★基本过程设计原则设计模式创建型模式&#xff1a;创建对象结构型模式&#xff1a;更大的结构行为型模式&#xff1a;交互及职责分配…

四川财谷通信息技术有限公司抖音小店优势解析

在数字经济蓬勃发展的今天&#xff0c;电商平台如雨后春笋般涌现&#xff0c;其中&#xff0c;四川财谷通信息技术有限公司旗下的抖音小店凭借其独特的优势和强大的实力&#xff0c;在众多竞争者中脱颖而出&#xff0c;成为消费者和商家信赖的优选平台。本文将详细解析四川财谷…

Windows键快捷键大全

Windows键快捷键大全 Windows键结合其他键可以执行多种快捷操作&#xff0c;以下是一些常用的Windows键快捷键&#xff1a; Windows键 D: 显示或隐藏桌面。Windows键 E: 打开文件资源管理器。Windows键 L: 锁定电脑。Windows键 R: 打开运行对话框。Windows键 I: 打开Win…

Java中JDK动态代理

参考&#xff1a;疯狂Java讲义 第18章 文章目录 前言复杂度与耦合的矛盾 使用JDK动态代理总结 前言 复杂度与耦合的矛盾 开发实际应用的软件系统时&#xff0c;通常会存在相同代码段重复出现的情况&#xff0c;在这种情况下&#xff0c;一般都提取为一个方法&#xff0c;在不…

SOP企业内部推行:效率飙升100%,质量保障零瑕疵!

在企业的日常运营中&#xff0c;你是否经常遇到这样的问题&#xff1a;同样一项工作&#xff0c;不同的人做出来效果却大相径庭&#xff1f;或者&#xff0c;明明已经制定了工作流程&#xff0c;但执行起来却总是出现偏差&#xff0c;导致效率低下、质量不稳&#xff1f;这些问…

【STM32单片机_(HAL库)】3-2-2【中断EXTI】【电动车报警器项目】继电器定时开闭

1.硬件 STM32单片机最小系统继电器模块 2.软件 继电器模块alarm驱动文件添加GPIO常用函数main.c程序 #include "sys.h" #include "delay.h" #include "led.h" #include "alarm.h"int main(void) {HAL_Init(); …

海外服务器和内地服务器有什么区别?

海外服务器和内地服务器在许多方面存在区别&#xff0c;主要包括以下几个方面&#xff1a; 1. 地理位置 海外服务器&#xff1a;位于中国大陆以外的地区&#xff0c;比如美国、欧洲、东南亚等地。常见的海外服务器提供商有Amazon Web Services&#xff08;AWS&#xff09;、Goo…

稚晖君发布5款全能人形机器人,开源创新,全能应用

8月18日&#xff0c;智元机器人举行“智元远征 商用启航” 2024年度新品发布会&#xff0c;智元联合创始人彭志辉主持并发布了“远征”与“灵犀”两大系列共五款商用人形机器人新品——远征A2、远征A2-W、远征A2-Max、灵犀X1及灵犀X1-W&#xff0c;并展示了在机器人动力、感知、…