r2/game-server/app/dao/userDao.js
lightings 35ec876e81 ...
2023-07-16 20:54:19 +08:00

81 lines
2.3 KiB
JavaScript

const redis = require("redis");
const pomelo = require("pomelo");
const { query_game, query_guild } = require("../lib/db");
const config = pomelo.app.get("redis");
const client = redis.createClient({
url: `redis://${config.host}:${config.port}/${config.db}`,
});
client.on("error", (err) => {
console.error(err);
});
async function init() {
await client.connect();
}
init();
class UserDao {
async getUserInfo(userid) {
const cacheResult = await client.hGet(`t_user:${userid}`, "value");
if (cacheResult != null) {
const userInfo = JSON.parse(cacheResult);
userInfo.last_login_time = await this.getLastLoginTime(userid);
return userInfo;
} else {
return await this.fetchAndCacheUserInfoFromGameDB(userid);
}
}
async fetchAndCacheUserInfoFromGameDB(uid) {
const query = `SELECT idx,account_id,name,sex,head_id,head_frame,level,bceg,gold,diamond,\`rank\`,ring_id,last_login_time FROM t_user WHERE account_id=?`;
const results = await query_game(query, [uid]);
if (results.length === 0) {
throw new Error(`User not found: ${uid}`);
} else {
const userInfo = results[0];
userInfo.name = userInfo.name.toString();
const query_insert = `INSERT INTO t_users (account, username, password) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE account=VALUES(account), username=VALUES(username), password=VALUES(password)`;
const r = await query_guild(query_insert, [uid, userInfo.name, ""]);
await client.hSet(`t_user:${uid}`, "value", JSON.stringify(userInfo));
return userInfo;
}
}
async findUser(name, uid) {
const query = `SELECT account_id, name FROM t_user WHERE CAST(name as CHAR) LIKE ?`;
const results = await query_game(query, ["%" + name + "%"]);
if (results.length === 0) {
throw new Error(`User not found: ${name}`);
}
const users = results.map((user) => {
this.getUserInfo(user.account_id);
return {
uid: user.account_id,
name: user.name.toString(),
};
});
return users;
}
async getLastLoginTime(uid) {
const query = `SELECT last_login_time FROM t_user WHERE account_id=?`;
const results = await query_game(query, [uid]);
if (results.length === 0) {
throw new Error(`User not found: ${uid}`);
} else {
return results[0].last_login_time;
}
}
}
module.exports = new UserDao();