首页 > 数据库 >node.js: mysql sequelize es6 ORM (updated)

node.js: mysql sequelize es6 ORM (updated)

时间:2024-08-24 13:27:42浏览次数:7  
标签:node es6 updated const res req send message id

 

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File:dbconfig.js
 * ds:$
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 8:40
 */

/**
 *
 * @type {{dialect: string, PASSWORD: string, pool: {min: number, max: number, idle: number, acquire: number}, HOST: string, USER: string, DB: string}}
 */
const dbConfig = {
    HOST: "localhost",
    USER: "root",
    PASSWORD: "888888",
    DB: "geovindu",
    dialect: "mysql",
    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 10000
    }
};

export default dbConfig;

  

import Tutorial from "./tutorial.js";

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File: server/models/userinfo.js
 * ds:$
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 8:58
 */
/**
 *
 * @param sequelize
 * @param Sequelize
 * @returns {*}
 * @constructor
 */
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;

  

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File: server/models/toutorial.js
 * ds:$ npm install express sequelize mysql2 cors
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 8:42
 */

/**
 * 实体类
 * @param sequelize
 * @param Sequelize
 * @returns {*}
 * @constructor
 */
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;

  

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File: server/models/index.js
 * ds:$
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 8:48
 */
import dbConfig from "../dbconfig/dbConfig.js";
import Sequelize from "sequelize";
import tutorials from "./tutorial.js"
import userinfos from "./userinfo.js"

/**
 *
 */
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
    host: dbConfig.HOST,
    dialect: dbConfig.dialect,
    operatorsAliases: false,

    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;

  

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File: server/controllers/userinfo.js
 * ds:$
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 9:03
 */
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,
        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."
            });
        });
};



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

  

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File: server/controllers/toutorial.js
 * ds:$
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 8:49
 */
import db  from "../models/index.js";

const Tutorial = db.tutorials;
const Op = db.Sequelize.Op;

/**
 *
 * @param req
 * @param res
 */
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 => {
            if (data) {
                res.send(data);
            } else {
                res.status(404).send({
                    message: `Cannot find Tutorial with id=${id}.`
                });
            }
        })
        .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."
            });
        });
};



// 这个命名问题 tutorials
// 使用 ES6 的默认导出语法,直接导出包含所有函数的对象
/**
 *
 */
export default
{
    findAllPublished,
    deleteAll,
    deleteid,
    update,
    findOne,
    findAll,
    create
};

  

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File: server/routes/userinfo.js
 * ds:$
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 11:15
 */
import express from "express"
import userinfos from "../controllers/userinfo.js"


/**
 *
 * @param app
 */
const uroutes= app => {

     var router = express.Router();

    router.post("/user",userinfos.usercreate)

    router.get("/user", userinfos.userfindAll);

    router.get("/user/userIsOk", userinfos.findAlluserIsOk);

    router.get("/user/:id", userinfos.userfindOne);

    router.put("/user/:id", userinfos.userupdate);

    router.put("/user/:id", userinfos.userdeleteid);

    router.put("/user", userinfos.userdeleteAll);

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

export default uroutes;

  

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File: server/routes/toutorial.js
 * ds:$
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 8:50
 */
import express from "express"
import tutorials from "../controllers/tutorial.js"


/**
 *
 * @param app
 */
const troutes= app => {



    var router = express.Router();

    // Create a new Tutorial
    router.post("/tutorials/",tutorials.create)

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

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

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

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

    // Delete a Tutorial with id
    router.put("/tutorials/:id", tutorials.deleteid);

    // Delete all Tutorials
    router.put("/tutorials/", tutorials.deleteAll);

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

export default troutes;

  

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File: server/routes/index.js
 * ds:$
 * package:
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 12:56
 */


import troutes from "./tutorial.js"
import uroutes from "./userinfo.js"

/**
 *
 * @param app
 */
const routes=app => {

troutes(app);
uroutes(app);

};

export default routes;

  

/**
 * description:
 * product: WebStorm
 * project vuetstest
 * File: server.js
 * ds:$
 * IDE: webstorm 2023.1
 * OS: windows 10
 * database: mysql 8+ sql server 2019 postgreSQL 16
 * dev: node 20+ vue.js 3.0+
 * @author hp
 * @project vuetstest
 * @date 2024/8/24 8:52
 */
import express from "express";
import cors from "cors";
import db from "./models/index.js"
import routes from "./routes/index.js"

const Tutorial = db.tutorials;
//require("./app/routes/turorial.routes")(app);

const app = express();

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

routes(app);
//app.routes();

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

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:8080/tutorials
//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) => {

    /*
      if (!req.body.title) {
        res.status(400).send({
          message: "Content can not be empty!"
        });
        return;
      }
    */
    /*
    // Create a Tutorial
    const tutorial = {
        title: '兴大兴',
        description: '涂没有什么',
        published: false,
        createdAt:'2024-08-05',
        updatedAt:'2024-08-05'
    };

    // 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."
            });
        });
     */
    res.json({ message: "数据添加成功!." });

});

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

  

 

 

 

 

标签:node,es6,updated,const,res,req,send,message,id
From: https://www.cnblogs.com/geovindu/p/18377665

相关文章

  • 基于Node.js+vue社交网站(程序+论文+开题报告)-计算机毕业设计
    本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景随着互联网技术的飞速发展和智能手机的普及,社交网站已成为人们日常生活中不可或缺的一部分。它们不仅为人们提供了交流思想、分享生活的平台,还深刻影响着人......
  • 基于Node.js+vue摄影作品网站(程序+论文+开题报告)-计算机毕业设计
    本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景在数字化时代,摄影艺术以其独特的视觉语言,成为了人们记录生活、表达情感、传递思想的重要方式。随着互联网的普及和摄影技术的不断进步,摄影作品的展示与分享......
  • 基于Node.js+vue蜗牛兼职网(程序+论文+开题报告)-计算机毕业设计
    本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景在当今社会,随着经济的快速发展和就业市场的多元化,兼职工作已成为许多学生、职场新人乃至寻求灵活工作方式的职场人士的重要选择。然而,传统兼职信息的获取渠......
  • 基于Node.js+vue企业知识产权管理系统(程序+论文+开题报告)-计算机毕业设计
     本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景随着全球经济一体化的深入发展,企业知识产权已成为企业核心竞争力的重要组成部分,其保护与管理直接关系到企业的创新能力、市场地位及长远发展。当前,企业面......
  • 基于Node.js+vue食堂管理系统(程序+论文+开题报告)-计算机毕业设计
    本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景随着高校规模的不断扩大及师生对校园生活品质要求的日益提升,食堂作为校园生活的重要组成部分,其管理效率与服务水平直接影响到师生的就餐体验与满意度。传统......
  • 基于nodejs+vueK13878玩具销售[程序+论文+开题]-计算机毕业设计
    本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景随着消费市场的日益多元化和消费者需求的不断升级,玩具行业作为儿童娱乐与教育的重要载体,正经历着前所未有的变革与发展。K13878作为一款新兴或具有代表性的......
  • 基于nodejs+vueJava在线教育系统[程序+论文+开题]-计算机毕业设计
    本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景随着互联网技术的迅猛发展和教育理念的革新,在线教育已成为现代教育体系中的重要组成部分。特别是在编程语言学习领域,如Java,其复杂性和实用性要求学习者能够......
  • 基于nodejs+vueIT企业绩效核算平台[程序+论文+开题]-计算机毕业设计
    本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景在当今竞争激烈的IT行业中,企业的持续发展离不开高效的管理体系与科学的绩效评估机制。随着企业规模的扩大和业务复杂度的提升,传统的手工或简单的电子表格绩......
  • 基于nodejs+vuejava学习平台[程序+论文+开题]-计算机毕业设计
    本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景随着互联网技术的飞速发展和在线教育市场的蓬勃兴起,传统的教育模式正经历着深刻的变革。在这个数字化时代,构建一个高效、便捷、互动性强的学习平台成为了提......
  • ES6解构赋值详解;全面掌握:JavaScript解构赋值的终极指南
    目录全面掌握:JavaScript解构赋值的终极指南一、数组解构赋值1、基本用法2、跳过元素3、剩余元素4、默认值二、对象解构赋值1、基本用法2、变量重命名3、默认值4、嵌套解构三、复杂的嵌套结构解构四、函数参数解构赋值1、对象解构作为函数参数2、带有默认值的函......