Node.js向け主要データベースの汎用メソッドのラップ
Node.jsで利用されることの多いデータベースには、MySQL、MongoDB、Redisなどがあります。以下は、各種データベースの一般的なメソッドのラッパーの例です。
- MySQLデータベースの一般的なメソッドカプセル化の例:
const mysql = require('mysql');
// 创建连接池
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb',
connectionLimit: 10
});
// 查询数据
function query(sql, values) {
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) {
reject(err);
} else {
connection.query(sql, values, (err, results) => {
connection.release();
if (err) {
reject(err);
} else {
resolve(results);
}
});
}
});
});
}
module.exports = {
query
};
- MongoDBデータベースの最も使用されているメソッドのラッパーの例:
const mongoose = require('mongoose');
// 连接数据库
mongoose.connect('mongodb://localhost/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
// 定义数据模型
const userSchema = new mongoose.Schema({
name: String,
age: Number
});
const User = mongoose.model('User', userSchema);
// 查询数据
function findUser(query) {
return User.find(query).exec();
}
module.exports = {
findUser
};
- Redisデータベースの一般的に使用されるメソッドのラッピングの例:
const redis = require('redis');
const client = redis.createClient();
// 设置数据
function set(key, value) {
return new Promise((resolve, reject) => {
client.set(key, value, (err, reply) => {
if (err) {
reject(err);
} else {
resolve(reply);
}
});
});
}
// 获取数据
function get(key) {
return new Promise((resolve, reject) => {
client.get(key, (err, reply) => {
if (err) {
reject(err);
} else {
resolve(reply);
}
});
});
}
module.exports = {
set,
get
};
これらのカプセル化例は単なる簡単なデモで、実際的なアプリケーションでは具体的なビジネスの需要に基づいて適切なカプセル化とエラー処理を行う必要があります。