77 lines
2.2 KiB
JavaScript
77 lines
2.2 KiB
JavaScript
const { configure, query_game, query_guild } = require("../lib/db");
|
|
const { hConfig, hGet, hSet } = require("../lib/redis");
|
|
|
|
class UserDao {
|
|
async getUserInfo(userid) {
|
|
const cacheResult = await 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 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;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
let dao;
|
|
module.exports = {
|
|
setup: (config) => {
|
|
configure(config.db);
|
|
hConfig(config.redis);
|
|
},
|
|
dao: () => {
|
|
if (!dao) {
|
|
dao = new UserDao();
|
|
}
|
|
return dao;
|
|
}
|
|
}
|