96 lines
2.6 KiB
JavaScript
96 lines
2.6 KiB
JavaScript
import { getPool } from "../db/index.js";
|
|
import { marked } from "marked";
|
|
|
|
async function getAgreementContent(userId, hash) {
|
|
let content = '';
|
|
const client = await getPool();
|
|
try {
|
|
let sql = `
|
|
SELECT markdown
|
|
FROM agreement_content
|
|
WHERE hash = $1
|
|
`;
|
|
let values = [hash];
|
|
if (userId) {
|
|
sql += `AND user_id = $2`;
|
|
values.push(userId);
|
|
} else {
|
|
sql += `AND user_id IS NULL`;
|
|
}
|
|
const res = await client.query(sql, values);
|
|
if (res.rows.length > 0 && res.rows[0].markdown) {
|
|
content = res.rows[0].markdown;
|
|
}
|
|
} catch(e) {
|
|
console.error(e)
|
|
} finally {
|
|
await client.release();
|
|
}
|
|
return content;
|
|
}
|
|
|
|
export async function getAgreements(userId) {
|
|
let agreements = [];
|
|
const client = await getPool();
|
|
try {
|
|
let sql = `
|
|
SELECT
|
|
title,
|
|
hash
|
|
FROM agreement_content
|
|
WHERE user_id IS null
|
|
`;
|
|
let values = [];
|
|
if (userId) {
|
|
sql += `
|
|
OR user_id = $1
|
|
`;
|
|
values.push(userId);
|
|
}
|
|
sql += `
|
|
ORDER BY title ASC
|
|
`
|
|
const res = await client.query(sql, values);
|
|
if (res.rows.length > 0) {
|
|
agreements = res.rows;
|
|
}
|
|
} catch(e) {
|
|
console.error(e)
|
|
} finally {
|
|
await client.release();
|
|
}
|
|
return agreements;
|
|
}
|
|
|
|
export function routeAgreements(app) {
|
|
|
|
app.get('/agreements/:hash', async (req, res) => {
|
|
const { hash } = req.params;
|
|
const agreement = await getAgreementContent(null, hash);
|
|
res.render('agreement', {
|
|
agreement: marked(agreement),
|
|
rawUrl: `/agreements/${hash}/raw`,
|
|
});
|
|
});
|
|
|
|
app.get('/agreements/:hash/raw', async (req, res) => {
|
|
const { hash } = req.params;
|
|
const agreement = await getAgreementContent(null, hash);
|
|
res.send(`<pre>${agreement}</pre>`);
|
|
});
|
|
|
|
app.get('/agreements/:userId/:hash', async (req, res) => {
|
|
const { userId, hash } = req.params;
|
|
const agreement = await getAgreementContent(userId, hash);
|
|
res.render('agreement', {
|
|
agreement: marked(agreement),
|
|
rawUrl: `/agreements/${hash}/raw`,
|
|
});
|
|
});
|
|
|
|
app.get('/agreements/:userId/:hash/raw', async (req, res) => {
|
|
const { hash } = req.params;
|
|
const agreement = await getAgreementContent(userId, hash);
|
|
res.send(`<pre>${agreement}</pre>`);
|
|
});
|
|
} |