r2/game-server/app/dao/userDao.js
lightings a6f260a6e6 ...
2023-07-24 17:53:28 +08:00

89 lines
2.6 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, last_idx, limit, uid) {
if (limit>20) {
throw new Error(`limit too large: ${limit}`);
}
const query = `SELECT idx, account_id, CAST(name as CHAR) as name FROM t_user WHERE idx>? AND (CAST(account_id as CHAR) = ? OR CAST(name as CHAR) LIKE ?) LIMIT ?`;
const results = await query_game(query, [
last_idx,
name,
"%" + name + "%",
limit,
]);
if (results.length === 0) {
return { users: [], last_idx: last_idx };
}
const users = results.map((user) => {
this.getUserInfo(user.account_id);
return {
uid: user.account_id,
name: user.name.toString(),
};
});
return { users: users, last_idx: results[results.length - 1].idx };
}
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();