1. Moleculer 目前支持SQLite,MySQL,MariaDB,PostgreSQL,MSSQL等数据库,这里以mysql为例
2. package.json 增加mysql依赖
"mysql2": "^2.3.3", "sequelize": "^6.21.3", "moleculer-db-adapter-sequelize": "^0.2.15", "moleculer-db": "^0.8.24",
npm install moleculer-db-adapter-sequelize sequelize --save
npm install moleculer-db --save
3.然后执行对应数据库的命令
SQLitenpm install sqlite3 --save# For MySQL
npm install mysql2 --save# For MariaDB
npm install mariadb --save# For PostgreSQLnpm install pg pg-hstore --save# For MSSQL
$npm install tedious --save
4.服务增加如下操作:
const { ServiceBroker } = require("moleculer");
const DbService = require("moleculer-db");
const SqlAdapter = require("moleculer-db-adapter-sequelize");
const Sequelize = require("sequelize");
const broker = new ServiceBroker();
/*** @typedef {import('moleculer').ServiceSchema} ServiceSchema Moleculer's Service Schema* @typedef {import('moleculer').Context} Context Moleculer's Context*/broker.createService({name: "products",mixins: [DbService],adapter: new SqlAdapter('test', 'root', 'root', {host: 'localhost',dialect: 'mysql' ,pool: {max: 5,min: 0,idle: 10000}}),model: {name: "products",define: {title: Sequelize.STRING,content: Sequelize.TEXT,votes: Sequelize.INTEGER,author: Sequelize.INTEGER,status: Sequelize.BOOLEAN},options: {}},
});broker.start()// Create a new post.then(() => broker.call("products.create", {title: "My first post",content: "Lorem ipsum...",votes: 0})).then(() => broker.call("products.find").then(console.log));
5.启动项目: 数据库自动创表products,并插入了一条数据,可以查询出来
6.具体的crud 可以参考Sequelize | Feature-rich ORM for modern TypeScript & JavaScript 实现,这里就不详细介绍了