nodejs-mysql-mapper
Description
A nodeJS similar to Mybatis is used to map data to mysql. This makes the code more readable!
Installation
npm i nodejs-mysql-mapper -S
# OR
yarn add nodejs-mysql-mapper -S
Instructions
1. Initialize the mapper plug-in configuration
import { init } from "nodejs-mysql-mapper";
import { join } from "path";
init({
mysql:{
host: "localhost",
user: "root",
password: "**********",
database: "databaseName",
},
basePath: join(__dirname, './mapper')
});
2. Create the XML mapping file './mapper/xxx.xml'
<?xml version="1.0" encoding="UTF-8"?>
<mapper>
<item key="product_name" as="productName"></item>
<item key="product_intro" as="productIntro"></item>
<item key="id" as="productId"></item>
<sql type="select" name="getProductInfo">
select product_name,product_intro from product where id = #{id}
</sql>
<sql type="insert" name="setProductInfo">
insert into product(product_name,product_intro) values (#{product_name},#{product_intro})
</sql>
<sql type="insert" mode="multiple" name="setMultipleProductInfo">
insert into product(product_name,product_intro) values (#{product_name},#{product_intro})
</sql>
<sql type="update" name="updateProductInfo">
update product set product_name=#{product_name} where id=#{id}
</sql>
</mapper>
3. Call the defined method. The 'name' attribute in '.xml '
import mysqlMapper from "nodejs-mysql-mapper";
// Query
async () => {
try {
const result = await mysqlMapper("xxx", "getProductInfo", {
productId: 1,
});
// output result
console.log(result);
} catch (err) {
return Promise.reject(err);
}
};
// insert
async () => {
try {
const result = await mysqlMapper("xxx", "setProductInfo", {
productName: "test name",
productIntro: "test intro",
});
// output result
console.log(result);
} catch (err) {
return Promise.reject(err);
}
};
// Insert multiple data
async () => {
try {
const result = await mysqlMapper("xxx", "setMultipleProductInfo", [
{
productName: "test name1",
productIntro: "test intro1",
},
{
productName: "test name2",
productIntro: "test intro2",
},
{
productName: "test name3",
productIntro: "test intro3",
}
]);
// output result
console.log(result);
} catch (err) {
return Promise.reject(err);
}
};
// update
async () => {
try {
const result = await mysqlMapper("xxx", "updateProductInfo", {
productId: 1,
productName: "update test name",
});
// output result
console.log(result);
} catch (err) {
return Promise.reject(err);
}
};