Add pages/api/pastes.js
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
import db from '../../lib/db';
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
export default function handler(req, res) {
|
||||
if (req.method === 'POST') {
|
||||
const { type } = req.body;
|
||||
|
||||
if (type === 'comment') {
|
||||
const { pasteId, author, commentContent } = req.body;
|
||||
db.prepare('INSERT INTO comments (paste_id, author, content, created_at) VALUES (?, ?, ?, ?)')
|
||||
.run(pasteId, author, commentContent, new Date().toISOString());
|
||||
return res.status(200).json({ success: true });
|
||||
}
|
||||
|
||||
const { content, language, filename, expiry, allowDiscussions, deleteToken } = req.body;
|
||||
const id = nanoid(10);
|
||||
|
||||
let expiresAt = null;
|
||||
let expiryType = 'time';
|
||||
|
||||
if (expiry === 'burn') {
|
||||
expiryType = 'burn';
|
||||
} else if (expiry !== 'never') {
|
||||
const hours = parseInt(expiry);
|
||||
expiresAt = new Date(Date.now() + hours * 60 * 60 * 1000).toISOString();
|
||||
}
|
||||
|
||||
try {
|
||||
db.prepare(
|
||||
`INSERT INTO pastes (id, content, language, filename, created_at, expires_at, expiry_type, allow_discussions, delete_token)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
).run(
|
||||
id, content, language, filename, new Date().toISOString(), expiresAt, expiryType, allowDiscussions ? 1 : 0, deleteToken
|
||||
);
|
||||
return res.status(200).json({ id });
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return res.status(500).json({ error: "Failed to save paste" });
|
||||
}
|
||||
}
|
||||
|
||||
if (req.method === 'DELETE') {
|
||||
const { id, token } = req.query;
|
||||
const paste = db.prepare('SELECT delete_token FROM pastes WHERE id = ?').get(id);
|
||||
|
||||
if (paste && paste.delete_token === token) {
|
||||
db.prepare('DELETE FROM pastes WHERE id = ?').run(id);
|
||||
return res.status(200).json({ success: true });
|
||||
}
|
||||
|
||||
return res.status(403).json({ error: 'Unauthorized' });
|
||||
}
|
||||
|
||||
res.status(405).end();
|
||||
}
|
||||
Reference in New Issue
Block a user