r2/game-server/app/dao/userDao.js
lightings 6cf6974464 ...
2023-04-26 14:20:17 +08:00

70 lines
2.0 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}` });
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);
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 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;
}
}
module.exports = new UserDao();