Commit 0bd78a73 authored by nanahira's avatar nanahira Committed by GitHub

Patch api (completed one) (#5)

* patch api.js

* fixup /report time query

* some formats by vscode

* revert sqlite3 part

* revert sqlite3 part

* more format
parent dd75d750
......@@ -11,4 +11,5 @@ db.sql
upload/
plan.md
query.sql
test*
\ No newline at end of file
test*
/tools/api.js
......@@ -108,8 +108,8 @@ var j = schedule.scheduleJob('0 0 0 1 * *', function () {
let sql = `update user_info set pt = (pt - (pt - 1000) * 0.5 )
where pt > 1000`;
// Monthly pt reduce will be done in function monthly_user_historical_record()
// Monthly pt reduce will be done in function monthly_user_historical_record()
//client.query(sql, function (err, result) {
// done();
// if (err) {
......@@ -122,14 +122,15 @@ var j = schedule.scheduleJob('0 0 0 1 * *', function () {
let time = moment().subtract(1, 'month');
let season = time.format('YYYY-MM');
let higher_limit = time.format('YYYY-MM-01 00:00:01');
let lower_limit = moment().subtract(1, 'day').format('YYYY-MM-DD 23:59:59'); let base = 1000;
let lower_limit = moment().subtract(1, 'day').format('YYYY-MM-DD 23:59:59');
let base = 1000;
pool.query('select monthly_user_historical_record($1::text, $2, $3::boolean, true)', [season, base, false], (err, result) => {
if (err)
return console.error('error running monthly scheduleJob', err);
else
pool.query('select collect_win_lose_rate($1, $2)', [lower_limit, higher_limit], (err, result) => {
if (err) console.error('error running monthly scheduleJob', err);
});
if (err)
return console.error('error running monthly scheduleJob', err);
else
pool.query('select collect_win_lose_rate($1, $2)', [lower_limit, higher_limit], (err, result) => {
if (err) console.error('error running monthly scheduleJob', err);
});
});
});
......@@ -171,7 +172,9 @@ schedule.scheduleJob('1 1 0 1 1 *', function () {
var Filter = require('bad-words-chinese');
var dirtyWords = require('../dirtyWordsChinese.json');
var filter = new Filter({ chineseList: dirtyWords.words });
var filter = new Filter({
chineseList: dirtyWords.words
});
// 数据迁移 rating_index => user_info
// router.get('/mr',function(req,res){
......@@ -186,7 +189,7 @@ var filter = new Filter({ chineseList: dirtyWords.words });
// }
// let count = result.rows.length
// result.rows.map(function(i) {
// var s = `insert into user_info (username, exp, pt, entertain_win, entertain_lose, entertain_all) values ('${i.username}', '${i.exp}', '${i.pt}', '${i.win}', '${i.lose}', '${i.game}')`
// var s = {text: `insert into user_info (username, exp, pt, entertain_win, entertain_lose, entertain_all) values ($1, $2, $3, $4, $5, $6)`, values: [i.username, i.exp, i.pt, i.win, i.lose, i.game]}
// return client.query(s)
// }).pop().on('end', function(){
// console.log(`Inserted ${count} people`)
......@@ -268,27 +271,29 @@ router.post('/score', function (req, res) {
var today = moment(start).format('YYYY-MM-DD')
// 真实得分 S(胜=1分,和=0.5分,负=0分)
let sa = 0, sb = 0
let sa = 0,
sb = 0
if (userscoreA > userscoreB || userscoreB === -9) {
sa = 1
paramA['athletic_win'] = 1
paramB['athletic_lose'] = 1
winner = usernameA
}
else if (userscoreA < userscoreB || userscoreA === -9) {
} else if (userscoreA < userscoreB || userscoreA === -9) {
sb = 1
paramA['athletic_lose'] = 1
paramB['athletic_win'] = 1
winner = usernameB
}
else {
} else {
sa = 0.5
sb = 0.5
paramA['athletic_draw'] = 1
paramB['athletic_draw'] = 1
}
var queryFirsrWinSql = `select count(*) from battle_history where type ='athletic' and userscorea != -5 and userscoreb != -5 and ( (usernameA= '${winner}' AND userscorea > userscoreb ) OR (usernameB= '${winner}' AND userscoreb > userscorea) ) and start_time > '${today}' `
var queryFirsrWinSql = {
text: `select count(*) from battle_history where type ='athletic' and userscorea != -5 and userscoreb != -5 and ( (usernameA= $1 AND userscorea > userscoreb ) OR (usernameB= $1 AND userscoreb > userscorea) ) and start_time > $2 `,
values: [winner, today]
}
console.log(queryFirsrWinSql)
client.query(queryFirsrWinSql, function (err, result) {
......@@ -381,41 +386,50 @@ router.post('/score', function (req, res) {
}
}
queries.push(`update user_info set exp = ${expResult.expA}, pt = ${ptResult.ptA},
athletic_win = athletic_win + ${paramA.athletic_win},
athletic_lose = athletic_lose + ${paramA.athletic_lose},
athletic_draw = athletic_draw + ${paramA.athletic_draw},
athletic_all = athletic_all + ${paramA.athletic_all}
where username = '${userA.username}'`)
queries.push(`update user_info set exp = ${expResult.expB}, pt = ${ptResult.ptB},
athletic_win = athletic_win + ${paramB.athletic_win},
athletic_lose = athletic_lose + ${paramB.athletic_lose},
athletic_draw = athletic_draw + ${paramB.athletic_draw},
athletic_all = athletic_all + ${paramB.athletic_all}
where username = '${userB.username}'`)
queries.push(`insert into battle_history values (
'${userA.username}',
'${userB.username}',
'${userscoreA}',
'${userscoreB}',
'${expResult.expA}',
'${expResult.expB}',
'${userA.exp}',
'${userB.exp}',
'${ptResult.ptA}',
'${ptResult.ptB}',
'${userA.pt}',
'${userB.pt}',
'${arena}',
'${start}',
'${end}',
'${winner}',
'${firstWin}',
'${deckA}',
'${deckB}'
)`)
queries.push({
text: `update user_info set exp = $2, pt = $3,
athletic_win = athletic_win + $4,
athletic_lose = athletic_lose + $5,
athletic_draw = athletic_draw + $6,
athletic_all = athletic_all + $7
where username = $1`,
values: [userA.username, parseFloat(expResult.expA), parseFloat(ptResult.ptA), parseFloat(paramA.athletic_win), parseFloat(paramA.athletic_lose), parseFloat(paramA.athletic_draw), parseFloat(paramA.athletic_all)]
})
queries.push({
text: `update user_info set exp = $2, pt = $3,
athletic_win = athletic_win + $4,
athletic_lose = athletic_lose + $5,
athletic_draw = athletic_draw + $6,
athletic_all = athletic_all + $7
where username = $1`,
values: [userB.username, parseFloat(expResult.expB), parseFloat(ptResult.ptB), parseFloat(paramB.athletic_win), parseFloat(paramB.athletic_lose), parseFloat(paramB.athletic_draw), parseFloat(paramB.athletic_all)]
})
queries.push({
text: `insert into battle_history values (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14,
$15,
$16,
$17,
$18,
$19
)`,
values: [userA.username, userB.username, userscoreA, userscoreB, expResult.expA, expResult.expB, userA.exp, userB.exp, ptResult.ptA, ptResult.ptB, userA.pt, userB.pt, arena, start, end, winner, firstWin, deckA, deckB]
})
queries.map(function (q) {
// console.log(q)
......@@ -446,41 +460,50 @@ router.post('/score', function (req, res) {
paramB['entertain_draw'] = 1
}
queries.push(`update user_info set exp = ${expResult.expA},
entertain_win = entertain_win + ${paramA.entertain_win},
entertain_lose = entertain_lose + ${paramA.entertain_lose},
entertain_draw = entertain_draw + ${paramA.entertain_draw},
entertain_all = entertain_all + ${paramA.entertain_all}
where username = '${userA.username}'`)
queries.push(`update user_info set exp = ${expResult.expB},
entertain_win = entertain_win + ${paramB.entertain_win},
entertain_lose = entertain_lose + ${paramB.entertain_lose},
entertain_draw = entertain_draw + ${paramB.entertain_draw},
entertain_all = entertain_all + ${paramB.entertain_all}
where username = '${userB.username}'`)
queries.push(`insert into battle_history values (
'${userA.username}',
'${userB.username}',
'${userscoreA}',
'${userscoreB}',
'${expResult.expA}',
'${expResult.expB}',
'${userA.exp}',
'${userB.exp}',
'${userA.pt}',
'${userB.pt}',
'${userA.pt}',
'${userB.pt}',
'${arena}',
'${start}',
'${end}',
'${winner}',
'${firstWin}'
)`)
queries.push({
text: `update user_info set exp = $2,
entertain_win = entertain_win + $3,
entertain_lose = entertain_lose + $4,
entertain_draw = entertain_draw + $5,
entertain_all = entertain_all + $6
where username = $1`,
values: [userA.username, parseFloat(expResult.expA), parseFloat(paramA.entertain_win), parseFloat(paramA.entertain_lose), parseFloat(paramA.entertain_draw), parseFloat(paramA.entertain_all)]
})
queries.push({
text: `update user_info set exp = $2,
entertain_win = entertain_win + $3,
entertain_lose = entertain_lose + $4,
entertain_draw = entertain_draw + $5,
entertain_all = entertain_all + $6
where username = $1`,
values: [userB.username, parseFloat(expResult.expB), parseFloat(paramB.entertain_win), parseFloat(paramB.entertain_lose), parseFloat(paramB.entertain_draw), parseFloat(paramB.entertain_all)]
})
queries.push({
text: `insert into battle_history values (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$9,
$10,
$11,
$12,
$13,
$14,
$15
)`,
values: [userA.username, userB.username, userscoreA, userscoreB, expResult.expA, expResult.expB, userA.exp, userB.exp, userA.pt, userB.pt, arena, start, end, winner, firstWin]
})
queries.map(function (q) {
// console.log(q)
......@@ -494,7 +517,10 @@ router.post('/score', function (req, res) {
})
client.query(`select * from user_info where username = '${usernameA}'`).on('end', function (result) {
client.query({
text: `select * from user_info where username = $1`,
values: [usernameA]
}).on('end', function (result) {
done()
if (result.rows.length > 0) {
ep.emit('query_userA', result.rows[0])
......@@ -504,7 +530,10 @@ router.post('/score', function (req, res) {
}
})
client.query(`select * from user_info where username = '${usernameB}'`).on('end', function (result) {
client.query({
text: `select * from user_info where username = $1`,
values: [usernameB]
}).on('end', function (result) {
done()
if (result.rows.length > 0) {
ep.emit('query_userB', result.rows[0])
......@@ -537,7 +566,9 @@ router.post('/score', function (req, res) {
} else
ep.emit('query_deckB', "no deck")
res.json({ msg: 'success' })
res.json({
msg: 'success'
})
})
})
......@@ -704,9 +735,11 @@ router.get('/report', function (req, res) {
to_date = moment(req.query.to_date).format('YYYY-MM-DD')
}
const time_args = [`${from_date} 00:00:00`, `${to_date} 00:00:00`];
async.parallel({
entertainTotal: function (callback) {
var sql = `SELECT count(*) from battle_history where type = 'entertain' and start_time>= '${from_date} 00:00:00' and start_time < '${to_date} 00:00:00';`
var sql = `SELECT count(*) from battle_history where type = 'entertain' and start_time >= $1 and start_time < $2;`
console.log(sql)
client.query(sql, function (err, result) {
done()
......@@ -719,9 +752,9 @@ router.get('/report', function (req, res) {
},
entertainDisconnect: function (callback) {
var sql = `SELECT count(*) from battle_history where type = 'entertain' and start_time>= '${from_date} 00:00:00' and start_time < '${to_date} 00:00:00' and (userscorea<0 or userscoreb<0);`
var sql = `SELECT count(*) from battle_history where type = 'entertain' and start_time >= $1 and start_time < $2 and (userscorea<0 or userscoreb<0);`
console.log(sql)
client.query(sql, function (err, result) {
client.query(sql, time_args, function (err, result) {
done()
if (err) {
return console.error('error running query', err)
......@@ -732,9 +765,9 @@ router.get('/report', function (req, res) {
},
entertainUsers: function (callback) {
var sql = `SELECT count(DISTINCT usernamea) from battle_history where type = 'entertain' and start_time>= '${from_date} 00:00:00' and start_time < '${to_date} 00:00:00';`
var sql = `SELECT count(DISTINCT usernamea) from battle_history where type = 'entertain' and start_time >= $1 and start_time < $2;`
console.log(sql)
client.query(sql, function (err, result) {
client.query(sql, time_args, function (err, result) {
done()
if (err) {
return console.error('error running query', err)
......@@ -745,9 +778,9 @@ router.get('/report', function (req, res) {
},
athleticTotal: function (callback) {
var sql = `SELECT count(*) from battle_history where type = 'athletic' and start_time>= '${from_date} 00:00:00' and start_time < '${to_date} 00:00:00';`
var sql = `SELECT count(*) from battle_history where type = 'athletic' and start_time >= $1 and start_time < $2;`
console.log(sql)
client.query(sql, function (err, result) {
client.query(sql, time_args, function (err, result) {
done()
if (err) {
return console.error('error running query', err)
......@@ -758,9 +791,9 @@ router.get('/report', function (req, res) {
},
athleticDisconnect: function (callback) {
var sql = `SELECT count(*) from battle_history where type = 'athletic' and start_time>= '${from_date} 00:00:00' and (userscorea<0 or userscoreb<0) and start_time < '${to_date} 00:00:00';`
var sql = `SELECT count(*) from battle_history where type = 'athletic' and (userscorea<0 or userscoreb<0) and start_time >= $1 and start_time < $2;`
console.log(sql)
client.query(sql, function (err, result) {
client.query(sql, time_args, function (err, result) {
done()
if (err) {
return console.error('error running query', err)
......@@ -771,9 +804,9 @@ router.get('/report', function (req, res) {
},
athleticUsers: function (callback) {
var sql = `SELECT count(DISTINCT usernamea) from battle_history where type = 'athletic' and start_time>= '${from_date} 00:00:00' and start_time < '${to_date} 00:00:00';`
var sql = `SELECT count(DISTINCT usernamea) from battle_history where type = 'athletic' and start_time >= $1 and start_time < $2;`
console.log(sql)
client.query(sql, function (err, result) {
client.query(sql, time_args, function (err, result) {
done()
if (err) {
return console.error('error running query', err)
......@@ -784,9 +817,9 @@ router.get('/report', function (req, res) {
},
totalActive: function (callback) {
var sql = `SELECT count(DISTINCT usernamea) from battle_history where start_time>= '${from_date} 00:00:00' and start_time < '${to_date} 00:00:00';`
var sql = `SELECT count(DISTINCT usernamea) from battle_history where start_time >= $1 and start_time < $2;`
console.log(sql)
client.query(sql, function (err, result) {
client.query(sql, time_args, function (err, result) {
done()
if (err) {
return console.error('error running query', err)
......@@ -798,9 +831,9 @@ router.get('/report', function (req, res) {
//以小时为维度 计算每小时的战斗场数 竞技场
hourlyAthletic: function (callback) {
var sql = `SELECT start_time FROM battle_history WHERE type = 'athletic' and start_time>= '${from_date} 00:00:00' and start_time < '${to_date} 00:00:00';`
var sql = `SELECT start_time FROM battle_history WHERE type = 'athletic' and start_time >= $1 and start_time < $2;`
console.log(sql)
client.query(sql, function (err, result) {
client.query(sql, time_args, function (err, result) {
done()
if (err) {
return console.error('error running query', err)
......@@ -811,9 +844,9 @@ router.get('/report', function (req, res) {
},
//以小时为维度 计算每小时的战斗场数 娱乐场
hourlyEntertain: function (callback) {
var sql = `SELECT start_time FROM battle_history WHERE type = 'entertain' and start_time>= '${from_date} 00:00:00' and start_time < '${to_date} 00:00:00';`
var sql = `SELECT start_time FROM battle_history WHERE type = 'entertain' and start_time >= $1 and start_time < $2;`
console.log(sql)
client.query(sql, function (err, result) {
client.query(sql, time_args, function (err, result) {
done()
if (err) {
return console.error('error running query', err)
......@@ -953,27 +986,33 @@ router.post('/votes', function (req, res) {
var now = moment().format('YYYY-MM-DD HH:mm');
var sql = `insert into votes (title, options, create_time, start_time, end_time, status, multiple, max) values (
'${title}',
'${options}',
'${now}',
'${start_time}',
'${end_time}',
'${status}',
'${multiple}',
'${max}'
)`;
var sql = {
text: `insert into votes (title, options, create_time, start_time, end_time, status, multiple, max) values (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)`,
values: [title, options, now, start_time, end_time, status, multiple, max]
};
if (id) {
sql = `update votes set
title = '${title}',
options = '${options}',
start_time = '${start_time}',
end_time = '${end_time}',
status = '${status}',
multiple = '${multiple}',
max = '${max}'
where id = '${id}'`;
sql = {
text: `update votes set
title = $1,
options = $2,
start_time = $3,
end_time = $4,
status = $5,
multiple = $6,
max = $7
where id = $8`,
values: [title, options, start_time, end_time, status, multiple, max, id]
};
}
console.log(sql);
......@@ -1007,9 +1046,12 @@ router.post('/voteStatus', function (req, res) {
var now = moment().format('YYYY-MM-DD HH:mm')
var sql = `update votes set
status = '${status}'
where id = '${id}'`;
var sql = {
text: `update votes set
status = $1
where id = $2`,
values: [status, id]
};
console.log(sql);
......@@ -1063,34 +1105,43 @@ router.post('/submitVote', function (req, res) {
if (multiple === "true") {
_.each(opids, function (id) {
sql1 = `insert into vote_result (vote_id, option_id, userid, date_time, create_time) values (
'${voteid}',
'${id}',
'${user}',
'${date_time}',
'${create_time}'
)`;
sql1 = {
text: `insert into vote_result (vote_id, option_id, userid, date_time, create_time) values (
$1,
$2,
$3,
$4,
$5
)`,
values: [voteid, id, user, date_time, create_time]
};
voteResultSqls.push(sql1)
})
} else {
sql1 = `insert into vote_result (vote_id, option_id, userid, date_time, create_time) values (
'${voteid}',
'${opid}',
'${user}',
'${date_time}',
'${create_time}'
)`;
sql1 = {
text: `insert into vote_result (vote_id, option_id, userid, date_time, create_time) values (
$1,
$2,
$3,
$4,
$5
)`,
values: [voteid, opid, user, date_time, create_time]
};
voteResultSqls.push(sql1)
}
console.log(voteResultSqls);
var sql2 = `update user_info set
var sql2 = {
text: `update user_info set
exp = (exp + 1),
id = ${user}
where username = '${username}'`;
id = $2
where username = $1`,
values: [username, parseFloat(user)]
};
async.waterfall([
......@@ -1164,7 +1215,10 @@ router.get('/votes', function (req, res) {
var sql = `SELECT count(*) from votes `
if (status !== undefined) {
sql = `SELECT count(*) from votes where status=${status}`
sql = {
text: `SELECT count(*) from votes where status=$1`,
values: [parseFloat(status)]
}
}
console.log(sql);
......@@ -1173,10 +1227,16 @@ router.get('/votes', function (req, res) {
var total = result.rows[0].count
var sql2 = `SELECT * from votes order by create_time desc limit ${page_num} offset ${offset}`
var sql2 = {
text: `SELECT * from votes order by create_time desc limit $1 offset $2`,
values: [parseFloat(page_num), parseFloat(offset)]
}
if (status !== undefined) {
var sql2 = `SELECT * from votes where status=${status} order by create_time desc limit ${page_num} offset ${offset}`
var sql2 = {
text: `SELECT * from votes where status=$1 order by create_time desc limit $2 offset $3`,
values: [parseFloat(status), parseFloat(page_num), parseFloat(offset)]
}
}
console.log(sql2)
......@@ -1204,7 +1264,10 @@ router.get('/votes', function (req, res) {
async.each(options, function (option, callback2) {
var queryVoteOptionCount = `SELECT count(*) from vote_result where vote_id='${vateid}' and option_id ='${option.key}' `
var queryVoteOptionCount = {
text: `SELECT count(*) from vote_result where vote_id=$1 and option_id =$2 `,
values: [vateid, option.key]
}
option_ids.push(String(option.key))
// console.log(queryVoteOptionCount)
......@@ -1297,10 +1360,16 @@ router.get('/vote', function (req, res) {
var now = moment().format('YYYY-MM-DD HH:mm:ss')
// 找出可用投票 1 状态为可用 2 开始时间早于当前时间 3 结束时间大于当前时间
var sql1 = `SELECT * from votes where status='t' and start_time <= '${now}' and end_time >= '${now}' order by create_time desc `
var sql1 = {
text: `SELECT * from votes where status='t' and start_time <= $1 and end_time >= $1 order by create_time desc `,
values: [now]
}
console.log(sql1)
//找出此user投过的票的vote id, 利用这些vote 过滤已经投过的投票
var sql2 = `SELECT vote_id from vote_result where userid = '${user}'`
var sql2 = {
text: `SELECT vote_id from vote_result where userid = $1`,
values: [user]
}
//剩下的投票中随机选一个返回
async.waterfall([
......@@ -1367,9 +1436,15 @@ router.get('/deckinfo', function (req, res) {
return console.error('error fetching client from pool', err);
}
var sql = `SELECT * from deck_info where name like '%${name}%'`
var sql = {
text: `SELECT * from deck_info where name like $1`,
values: ["%" + (name) + "%"]
}
if (version) {
sql = `SELECT * from deck_info_history where name = '${name}' and id= ${version}`
sql = {
text: `SELECT * from deck_info_history where name = $1 and id= $2`,
values: [name, parseFloat(version)]
}
}
console.log(sql);
......@@ -1387,13 +1462,19 @@ router.get('/deckinfo', function (req, res) {
var resName = response.data.name
sql = `SELECT * from deck_info_history where name = '${resName}' order by start_time desc`
sql = {
text: `SELECT * from deck_info_history where name = $1 order by start_time desc`,
values: [resName]
}
console.log(sql);
client.query(sql, function (err, result) {
done()
response.history = result.rows
sql = `SELECT * from deck_demo where name = '${resName}' order by create_time desc`
sql = {
text: `SELECT * from deck_demo where name = $1 order by create_time desc`,
values: [resName]
}
console.log(sql);
client.query(sql, function (err, result) {
done()
......@@ -1470,15 +1551,24 @@ router.get('/deckdata/:id', function (req, res) {
var spellCardArr = []
_.each(main, function (value, key) {
mainCardArr.push({ id: key, num: value })
mainCardArr.push({
id: key,
num: value
})
})
_.each(extra, function (value, key) {
extraCardArr.push({ id: key, num: value })
extraCardArr.push({
id: key,
num: value
})
})
_.each(side, function (value, key) {
sideCardArr.push({ id: key, num: value })
sideCardArr.push({
id: key,
num: value
})
})
......@@ -1623,14 +1713,17 @@ router.post('/deckdemo', function (req, res) {
var now = moment().format('YYYY-MM-DD HH:mm')
var sql = `insert into deck_demo (name, author, url, title, file, create_time) values (
'${name}',
'${author}',
'${img_url}',
'${title}',
'${file}',
'${now}'
)`;
var sql = {
text: `insert into deck_demo (name, author, url, title, file, create_time) values (
$1,
$2,
$3,
$4,
$5,
$6
)`,
values: [name, author, img_url, title, file, now]
};
console.log(sql);
......@@ -1689,27 +1782,36 @@ router.post('/deckinfo', function (req, res) {
var now = moment().format('YYYY-MM-DD HH:mm')
if (isNew === "true") {
sql = `insert into deck_info (name, content, start_time) values (
'${name}',
'${contentStr}',
'${now}'
)`;
sql = {
text: `insert into deck_info (name, content, start_time) values (
$1,
$2,
$3
)`,
values: [name, contentStr, now]
};
} else {
sql = `update deck_info set
content = '${contentStr}',
end_time = '${now}'
where name = '${name}'`;
sql = {
text: `update deck_info set
content = $1,
end_time = $2
where name = $3`,
values: [contentStr, now, name]
};
}
console.log(sql);
client.query(sql, function (err, result) {
done();
sql = `insert into deck_info_history (name, content, start_time) values (
'${name}',
'${contentStr}',
'${now}'
)`;
sql = {
text: `insert into deck_info_history (name, content, start_time) values (
$1,
$2,
$3
)`,
values: [name, contentStr, now]
};
console.log(sql);
client.query(sql, function (err, result) {
......@@ -1762,39 +1864,60 @@ router.get('/history', function (req, res) {
var sql = 'SELECT count(*) from battle_history '
if (username && arena) {
sql = `SELECT count(*) from battle_history where (usernamea = '${username}' or usernameb = '${username}' ) and type = '${arena}'`
sql = {
text: `SELECT count(*) from battle_history where (usernamea = $1 or usernameb = $1 ) and type = $2`,
values: [username, arena]
}
}
if (username && !arena) {
sql = `SELECT count(*) from battle_history where usernamea = '${username}' or usernameb = '${username}' `
sql = {
text: `SELECT count(*) from battle_history where usernamea = $1 or usernameb = $1 `,
values: [username]
}
}
if (!username && arena) {
sql = `SELECT count(*) from battle_history where type = '${arena}'`
sql = {
text: `SELECT count(*) from battle_history where type = $1`,
values: [arena]
}
}
console.log(sql);
client.query(sql, function (err, result) {
if (err) {
if (err) {
return console.error('error running query', sql, err);
}
var total = result.rows[0].count
var sql2 = `SELECT * from battle_history order by start_time desc limit ${page_num} offset ${offset}`
var sql2 = {
text: `SELECT * from battle_history order by start_time desc limit $1 offset $2`,
values: [parseFloat(page_num), parseFloat(offset)]
}
if (username && arena) {
sql2 = `SELECT * from battle_history where ( usernamea = '${username}' or usernameb = '${username}' ) and type = '${arena}' order by start_time desc limit ${page_num} offset ${offset}`
sql2 = {
text: `SELECT * from battle_history where ( usernamea = $1 or usernameb = $1 ) and type = $2 order by start_time desc limit $3 offset $4`,
values: [username, arena, parseFloat(page_num), parseFloat(offset)]
}
}
if (username && !arena) {
sql2 = `SELECT * from battle_history where usernamea = '${username}' or usernameb = '${username}' order by start_time desc limit ${page_num} offset ${offset}`
sql2 = {
text: `SELECT * from battle_history where usernamea = $1 or usernameb = $1 order by start_time desc limit $2 offset $3`,
values: [username, parseFloat(page_num), parseFloat(offset)]
}
}
if (!username && arena) {
sql2 = `SELECT * from battle_history where type = '${arena}' order by start_time desc limit ${page_num} offset ${offset}`
sql2 = {
text: `SELECT * from battle_history where type = $1 order by start_time desc limit $2 offset $3`,
values: [arena, parseFloat(page_num), parseFloat(offset)]
}
}
console.log(sql2)
......@@ -1849,7 +1972,10 @@ router.get('/user', function (req, res) {
return res.json(resultData)
}
client.query(`SELECT * from user_info where username = '${username}'`, function (err, result) {
client.query({
text: `SELECT * from user_info where username = $1`,
values: [username]
}, function (err, result) {
//call `done()` to release the client back to the pool
done()
if (err) {
......@@ -1892,13 +2018,19 @@ router.get('/user', function (req, res) {
res.json(resultData)
});
client.query(`SELECT count(*) from user_info where pt >= ${resultData['pt']}`, function (err, result) {
client.query({
text: `SELECT count(*) from user_info where pt >= $1`,
values: [parseFloat(resultData['pt'])]
}, function (err, result) {
done()
resultData['arena_rank'] = result.rows[0]['count']
ep.emit('delay', '')
})
client.query(`SELECT count(*) from user_info where exp >= ${resultData['exp']}`, function (err, result) {
client.query({
text: `SELECT count(*) from user_info where exp >= $1`,
values: [parseFloat(resultData['exp'])]
}, function (err, result) {
done()
resultData['exp_rank'] = result.rows[0]['count']
ep.emit('delay', '')
......@@ -1934,33 +2066,39 @@ router.post('/ads', function (req, res) {
var now = moment().format('YYYY-MM-DD HH:mm')
var sql = `insert into ads (name, desctext, imgp_url, imgm_url, click_ref, click_url, impl_url, status, update_time, create_time, type) values (
'${name}',
'${desc}',
'${imgp}',
'${imgm}',
'${clkref}',
'${clkurl}',
'${implurl}',
'${status}',
'${now}',
'${now}',
'${type}'
)`;
var sql = {
text: `insert into ads (name, desctext, imgp_url, imgm_url, click_ref, click_url, impl_url, status, update_time, create_time, type) values (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$9,
$10
)`,
values: [name, desc, imgp, imgm, clkref, clkurl, implurl, status, now, type]
};
if (id) {
sql = `update ads set
name = '${name}',
desctext = '${desc}',
imgp_url = '${imgp}',
imgm_url = '${imgm}',
click_ref = '${clkref}',
click_url = '${clkurl}',
impl_url = '${implurl}',
status = '${status}',
update_time = '${now}',
type = ${type}
where id = '${id}'`;
sql = {
text: `update ads set
name = $1,
desctext = $2,
imgp_url = $3,
imgm_url = $4,
click_ref = $5,
click_url = $6,
impl_url = $7,
status = $8,
update_time = $9,
type = $11
where id = $10`,
values: [name, desc, imgp, imgm, clkref, clkurl, implurl, status, now, id, parseFloat(type)]
};
}
console.log(sql);
......@@ -2017,7 +2155,10 @@ router.get('/ads', function (req, res) {
function (callback) {
var sql = `SELECT count(*) from ads `
if (status !== undefined) {
sql = `SELECT count(*) from ads where status=${status}`
sql = {
text: `SELECT count(*) from ads where status=$1`,
values: [parseFloat(status)]
}
}
console.log(sql);
......@@ -2034,10 +2175,16 @@ router.get('/ads', function (req, res) {
function (total, callback) {
var sql2 = `SELECT * from ads order by create_time desc limit ${page_num} offset ${offset}`
var sql2 = {
text: `SELECT * from ads order by create_time desc limit $1 offset $2`,
values: [parseFloat(page_num), parseFloat(offset)]
}
if (status !== undefined) {
var sql2 = `SELECT * from ads where status=${status} order by create_time desc limit ${page_num} offset ${offset}`
var sql2 = {
text: `SELECT * from ads where status=$1 order by create_time desc limit $2 offset $3`,
values: [parseFloat(status), parseFloat(page_num), parseFloat(offset)]
}
}
console.log(sql2)
......@@ -2098,9 +2245,12 @@ router.post('/adSwitchChange', function (req, res) {
let status = req.body.status;
var sql = `update site_config set
config_value = '${status}'
where config_key = 'auto_close_ad'`;
var sql = {
text: `update site_config set
config_value = $1
where config_key = 'auto_close_ad'`,
values: [status]
};
console.log(sql);
......@@ -2165,9 +2315,12 @@ router.post('/label', function (req, res) {
let labelone = req.body.labelone;
var sql = `update site_config set
config_value = '${labelone}'
where config_key = 'label'`;
var sql = {
text: `update site_config set
config_value = $1
where config_key = 'label'`,
values: [labelone]
};
console.log(sql);
......@@ -2212,9 +2365,12 @@ router.post('/activity', function (req, res) {
var activityStr = JSON.stringify(activity)
var sql = `update site_config set
config_value = '${activityStr}'
where config_key = 'activity'`;
var sql = {
text: `update site_config set
config_value = $1
where config_key = 'activity'`,
values: [activityStr]
};
console.log(sql);
......@@ -2248,9 +2404,12 @@ router.post('/adsStatus', function (req, res) {
var now = moment().format('YYYY-MM-DD HH:mm')
var sql = `update ads set
status = '${status}'
where id = '${id}'`;
var sql = {
text: `update ads set
status = $1
where id = $2`,
values: [status, id]
};
console.log(sql);
......@@ -2287,7 +2446,10 @@ router.get('/getAd', function (req, res) {
var now = moment().format('YYYY-MM-DD HH:mm:ss')
// 可用总数
var sql1 = `SELECT count(*) from ads where status='t' and type='${type}';`
var sql1 = {
text: `SELECT count(*) from ads where status='t' and type=$1;`,
values: [type]
}
console.log(sql1)
async.waterfall([
......@@ -2318,7 +2480,10 @@ router.get('/getAd', function (req, res) {
var total = rows[0].count - 0
//返回随机的一个
// SELECT myid FROM mytable OFFSET floor(random()*N) LIMIT 1;
var sql2 = `SELECT * from ads where status='t' and type='${type}' OFFSET floor(random() * ${total}) LIMIT 1 `
var sql2 = {
text: `SELECT * from ads where status='t' and type=$1 OFFSET floor(random() * $2) LIMIT 1 `,
values: [type, parseFloat(total)]
}
console.log(sql2)
client.query(sql2, function (err, result) {
done()
......@@ -2369,9 +2534,12 @@ router.post('/adClick', function (req, res) {
return
}
var sql = `update ads set
var sql = {
text: `update ads set
clk = clk + 1
where id = '${id}'`;
where id = $1`,
values: [id]
};
console.log(sql);
......@@ -2408,9 +2576,12 @@ router.post('/adImpl', function (req, res) {
return
}
var sql = `update ads set
var sql = {
text: `update ads set
impl = impl + 1
where id = '${id}'`;
where id = $1`,
values: [id]
};
console.log(sql);
......@@ -2457,7 +2628,10 @@ router.get('/firstwin', function (req, res) {
// console.log(end);
// var xx = moment(end).add(1, 'day').format('YYYY-MM-DD HH:mm')
// console.log(xx);
var sql2 = `select count(*) from battle_history where type ='athletic' and isfirstwin='t' and ( (usernameA = '${username}' AND userscorea > userscoreb ) OR (usernameB = '${username}' AND userscoreb > userscorea) ) and start_time > '${activity.start}' and start_time < '${activity.end}' `
var sql2 = {
text: `select count(*) from battle_history where type ='athletic' and isfirstwin='t' and ( (usernameA = $1 AND userscorea > userscoreb ) OR (usernameB = $1 AND userscoreb > userscorea) ) and start_time > $2 and start_time < $3 `,
values: [username, activity.start, activity.end]
}
console.log(sql2)
client.query(sql2, function (err, result) {
......@@ -2470,7 +2644,10 @@ router.get('/firstwin', function (req, res) {
function (activity, callback) {
var today = moment().format('YYYY-MM-DD')
var sql2 = `select count(*) from battle_history where type ='athletic' and isfirstwin='t' and ( (usernameA = '${username}' AND userscorea > userscoreb ) OR (usernameB = '${username}' AND userscoreb > userscorea) ) and start_time > '${today}' `
var sql2 = {
text: `select count(*) from battle_history where type ='athletic' and isfirstwin='t' and ( (usernameA = $1 AND userscorea > userscoreb ) OR (usernameB = $1 AND userscoreb > userscorea) ) and start_time > $2 `,
values: [username, today]
}
console.log(sql2)
client.query(sql2, function (err, result) {
done()
......@@ -2492,7 +2669,10 @@ router.get('/firstwin', function (req, res) {
createUser = function (username, ep, epEventName) {
pool.connect(function (err, client, done) {
let sql = `insert into user_info (username) values ('${username}')`
let sql = {
text: `insert into user_info (username) values ($1)`,
values: [username]
}
console.log(sql)
client.query(sql, function (err, result) {
done();
......
const fs = require('fs');
let content = fs.readFileSync("./routes/api.js", "utf8");
let sql_queries = content.match(/`((select|SELECT|update|UPDATE|insert|INSERT|delete|DELETE)([^`]+)`)/g);
let replaces = [];
//let test = sql_queries[35].match(/'\${[^']+}'/g);
//let test = sql_queries[63].match(/[^']\${[^}]+}[^']/g);
//console.log(test);
for (let sql of sql_queries) {
const strings = sql.match(/'\${[^}]+}'/g) || [];
const numbers = (sql.match(/[^'%]\${[^}]+}[^'%]/g) || []).map(m => m.substring(1, m.length - 1));
const strings_like = sql.match(/'%\${[^}]+}%'/g) || [];
let replaced_sql = sql;
let values = [];
let reused = false
const handle_pattern = (pattern, var_name) => {
const var_index = values.indexOf(var_name)
if (var_index !== -1) {
//console.log("reuse", var_name);
reused = true;
replaced_sql = replaced_sql.replace(pattern, `$${var_index + 1}`);
} else {
//console.log("add", var_name);
values.push(var_name);
replaced_sql = replaced_sql.replace(pattern, `$${values.length}`);
}
}
for (let pattern of strings) {
const var_name_raw = pattern.match(/^'\${([^}]+)}'$/)[1];
const var_name = var_name_raw;
//console.log(pattern, var_name);
handle_pattern(pattern, var_name);
}
for (let pattern of numbers) {
const var_name_raw = pattern.match(/^\${([^}]+)}$/)[1];
const var_name = `parseFloat(${var_name_raw})`;
//console.log(pattern, var_name);
handle_pattern(pattern, var_name);
}
for (let pattern of strings_like) {
const var_name_raw = pattern.match(/^'%\${([^}]+)}%'$/)[1];
const var_name = `"%" + (${var_name_raw}) + "%"`;
//console.log(pattern, var_name);
handle_pattern(pattern, var_name);
}
if (!values.length) {
continue;
}
const replaced_pattern = `{text: ${replaced_sql}, values: [${values.join(", ")}]}`
//console.log(sql, replaced_pattern);
replaces.push({
sql,
replaced_pattern
});
}
for (let rep of replaces) {
content = content.replace(rep.sql, rep.replaced_pattern);
}
fs.writeFileSync("tools/api.js", content);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment