fix: avoid connection leaks in frontpage code

This commit is contained in:
Vyacheslav Matyukhin 2022-04-06 02:16:55 +03:00
parent 340dd3ac19
commit afeca1e796
No known key found for this signature in database
GPG Key ID: 3D2A774C5489F96C
2 changed files with 4 additions and 11 deletions

View File

@ -2,22 +2,18 @@ import { pgRead, readWritePool } from "./database/pg-wrapper";
import { Forecast } from "./platforms"; import { Forecast } from "./platforms";
export async function getFrontpage(): Promise<Forecast[]> { export async function getFrontpage(): Promise<Forecast[]> {
const client = await readWritePool.connect(); const res = await readWritePool.query(
const res = await client.query(
"SELECT frontpage_sliced FROM frontpage ORDER BY id DESC LIMIT 1" "SELECT frontpage_sliced FROM frontpage ORDER BY id DESC LIMIT 1"
); );
if (!res.rows.length) return []; if (!res.rows.length) return [];
console.log(res.rows[0].frontpage_sliced);
return res.rows[0].frontpage_sliced; return res.rows[0].frontpage_sliced;
} }
export async function getFrontpageFull(): Promise<Forecast[]> { export async function getFrontpageFull(): Promise<Forecast[]> {
const client = await readWritePool.connect(); const res = await readWritePool.query(
const res = await client.query(
"SELECT frontpage_full FROM frontpage ORDER BY id DESC LIMIT 1" "SELECT frontpage_full FROM frontpage ORDER BY id DESC LIMIT 1"
); );
if (!res.rows.length) return []; if (!res.rows.length) return [];
console.log(res.rows[0]);
return res.rows[0].frontpage_full; return res.rows[0].frontpage_full;
} }
@ -26,9 +22,8 @@ export async function rebuildFrontpage() {
tableName: "questions", tableName: "questions",
}); });
const client = await readWritePool.connect();
const frontpageSliced = ( const frontpageSliced = (
await client.query(` await readWritePool.query(`
SELECT * FROM questions SELECT * FROM questions
WHERE WHERE
(qualityindicators->>'stars')::int >= 3 (qualityindicators->>'stars')::int >= 3
@ -39,7 +34,7 @@ export async function rebuildFrontpage() {
).rows; ).rows;
const start = Date.now(); const start = Date.now();
await client.query( await readWritePool.query(
"INSERT INTO frontpage(frontpage_full, frontpage_sliced) VALUES($1, $2)", "INSERT INTO frontpage(frontpage_full, frontpage_sliced) VALUES($1, $2)",
[JSON.stringify(frontpageFull), JSON.stringify(frontpageSliced)] [JSON.stringify(frontpageFull), JSON.stringify(frontpageSliced)]
); );

View File

@ -7,7 +7,5 @@ export default async function handler(
res: NextApiResponse res: NextApiResponse
) { ) {
let frontpageElements = await getFrontpage(); let frontpageElements = await getFrontpage();
console.log(frontpageElements.map((element) => element.title).slice(0, 5));
console.log("...");
res.status(200).json(frontpageElements); res.status(200).json(frontpageElements);
} }