Files
AppRefeicoes/server/server.mjs
T
2026-10-26 14:16:09 +00:00

134 lines
9.9 KiB
JavaScript

import http from 'node:http';
import { DatabaseSync } from 'node:sqlite';
import { mkdirSync, readFileSync, existsSync, statSync } from 'node:fs';
import { resolve, extname, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
const fail = (status, message) => Object.assign(new Error(message), { status });
export function createApp({ dataDir = process.env.DATA_DIR || './data', staticDir = './dist/a-mesa/browser' } = {}) {
mkdirSync(dataDir, { recursive: true });
const db = new DatabaseSync(resolve(dataDir, 'amesa.sqlite'));
db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
CREATE TABLE IF NOT EXISTS recipes (id TEXT PRIMARY KEY, name TEXT NOT NULL, image TEXT NOT NULL, ingredients TEXT NOT NULL, preparation TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS entries (id TEXT PRIMARY KEY, slot TEXT NOT NULL, recipeId TEXT NOT NULL REFERENCES recipes(id));
CREATE INDEX IF NOT EXISTS entries_slot ON entries(slot);
CREATE TABLE IF NOT EXISTS shopping_overrides (week TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(week, key));
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);`);
const insert = db.prepare('INSERT INTO recipes VALUES (?, ?, ?, ?, ?)');
if (!db.prepare("SELECT value FROM metadata WHERE key='seeded'").get()) {
const seed = JSON.parse(readFileSync(new URL('./seed.json', import.meta.url), 'utf8'));
db.exec('BEGIN');
try {
for (const r of seed) insert.run(r.id, r.name, r.image, r.ingredients, r.preparation);
db.prepare('INSERT INTO metadata VALUES (?, ?)').run('seeded', '1');
db.exec('COMMIT');
} catch (error) { db.exec('ROLLBACK'); throw error; }
}
function state() {
return { recipes: db.prepare('SELECT * FROM recipes ORDER BY rowid').all(), entries: db.prepare('SELECT * FROM entries ORDER BY rowid').all(), shoppingOverrides: db.prepare('SELECT * FROM shopping_overrides').all().map(r => ({week:r.week,key:r.key,...JSON.parse(r.value)})) };
}
function recipe(input) {
if (!input || typeof input !== 'object') throw fail(400, 'Receita inválida.');
const result = {};
for (const [key, max] of Object.entries({ id: 100, name: 100, image: 2900000, ingredients: 20000, preparation: 30000 })) {
if (typeof input[key] !== 'string' || !input[key].trim() || input[key].length > max) throw fail(400, `Campo inválido: ${key}.`);
result[key] = input[key].trim();
}
if (!/^[a-zA-Z0-9-]+$/.test(result.id)) throw fail(400, 'Identificador inválido.');
const data = result.image.match(/^data:image\/(png|jpeg|gif|webp);base64,([A-Za-z0-9+/]+={0,2})$/);
if (data) {
if (Buffer.from(data[2], 'base64').length > 2 * 1024 * 1024) throw fail(413, 'A imagem deve ter menos de 2 MB.');
} else {
let url; try { url = new URL(result.image); } catch { throw fail(400, 'Imagem inválida.'); }
if (!['http:', 'https:'].includes(url.protocol) || result.image.length > 4096) throw fail(400, 'Utilize uma imagem PNG, JPEG, GIF, WebP ou um URL HTTP/HTTPS.');
}
return result;
}
async function body(req) {
if (!req.headers['content-type']?.startsWith('application/json')) throw fail(415, 'Envie dados JSON.');
const chunks = []; let size = 0;
const limit = req.method === 'PUT' && req.url?.startsWith('/api/recipes/') ? 6000000 : 3000000;
for await (const chunk of req) { size += chunk.length; if (size > limit) throw fail(413, 'Pedido demasiado grande.'); chunks.push(chunk); }
try { return JSON.parse(Buffer.concat(chunks).toString()); } catch { throw fail(400, 'JSON inválido.'); }
}
function json(res, status, value) { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); }
const root = resolve(staticDir);
const server = http.createServer(async (req, res) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
try {
const path = new URL(req.url, 'http://localhost').pathname;
if (path === '/api/health' && req.method === 'GET') return json(res, 200, { ok: true });
if (path === '/api/state' && req.method === 'GET') return json(res, 200, state());
if (path.startsWith('/api/recipes/') && req.method === 'PUT') {
const input = await body(req), r = recipe(input), previous = recipe(input.previous);
if (r.id !== decodeURIComponent(path.slice('/api/recipes/'.length)) || previous.id !== r.id) throw fail(400, 'Identificador inválido.');
const result = db.prepare('UPDATE recipes SET name=?, image=?, ingredients=?, preparation=? WHERE id=? AND name=? AND image=? AND ingredients=? AND preparation=?').run(r.name,r.image,r.ingredients,r.preparation,r.id,previous.name,previous.image,previous.ingredients,previous.preparation);
if (!result.changes) throw fail(409, 'Esta receita foi alterada entretanto. Feche e volte a abrir a receita para editar a versão atual.');
return json(res, 200, r);
}
if (path === '/api/shopping' && ['PUT','DELETE'].includes(req.method)) {
const input = await body(req);
if (!input || typeof input.week !== 'string' || !/^\d{4}-\d{1,2}-\d{1,2}$/.test(input.week) || typeof input.key !== 'string' || !input.key.trim() || input.key.length > 21000) throw fail(400,'Lista inválida.');
const [y,m,d] = input.week.split('-').map(Number), date = new Date(Date.UTC(y,m-1,d));
if (date.getUTCFullYear()!==y || date.getUTCMonth()!==m-1 || date.getUTCDate()!==d || date.getUTCDay()!==1) throw fail(400,'Semana inválida.');
if (req.method === 'DELETE') {
db.prepare('DELETE FROM shopping_overrides WHERE week=? AND key=?').run(input.week,input.key);
} else {
if(typeof input.name!=='string'||!input.name.trim()||input.name.length>20000||typeof input.unit!=='string'||input.unit.length>100||typeof input.removed!=='boolean'||(input.quantity!==null&&(typeof input.quantity!=='number'||!Number.isFinite(input.quantity)||input.quantity<0||input.quantity>1e9))) throw fail(400,'Produto ou quantidade inválidos.');
const value=JSON.stringify({name:input.name.trim(),unit:input.unit.trim(),quantity:input.quantity,removed:input.removed});
db.prepare('INSERT INTO shopping_overrides VALUES (?,?,?) ON CONFLICT(week,key) DO UPDATE SET value=excluded.value').run(input.week,input.key,value);
}
return json(res,200,{ok:true});
}
if (path === '/api/recipes' && req.method === 'POST') {
const r = recipe(await body(req));
const existing = db.prepare('SELECT * FROM recipes WHERE id=?').get(r.id);
if (existing) {
if (Object.keys(r).some(key => r[key] !== existing[key])) throw fail(409, 'Já existe uma receita diferente com este identificador.');
return json(res, 200, existing);
}
insert.run(r.id, r.name, r.image, r.ingredients, r.preparation);
return json(res, 201, r);
}
if (path === '/api/entries' && req.method === 'POST') {
const data = await body(req);
if (!data || typeof data.slot !== 'string' || !/^\d{4}-\d{1,2}-\d{1,2}:[012]$/.test(data.slot)) throw fail(400, 'Dia ou refeição inválidos.');
const [year, month, day] = data.slot.split(':')[0].split('-').map(Number);
const date = new Date(Date.UTC(year, month - 1, day));
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) throw fail(400, 'Data inválida.');
if (typeof data.recipeId !== 'string' || !db.prepare('SELECT id FROM recipes WHERE id=?').get(data.recipeId)) throw fail(404, 'Receita não encontrada.');
if (typeof data.id !== 'string' || !/^[a-zA-Z0-9-]{1,100}$/.test(data.id)) throw fail(400, 'Identificador inválido.');
const existing = db.prepare('SELECT * FROM entries WHERE id=?').get(data.id);
if (existing && (existing.slot !== data.slot || existing.recipeId !== data.recipeId)) throw fail(409, 'Identificador já utilizado.');
if (!existing) db.prepare('INSERT INTO entries VALUES (?, ?, ?)').run(data.id, data.slot, data.recipeId);
return json(res, existing ? 200 : 201, { id: data.id, slot: data.slot, recipeId: data.recipeId });
}
if (path.startsWith('/api/entries/') && req.method === 'DELETE') {
db.prepare('DELETE FROM entries WHERE id=?').run(decodeURIComponent(path.slice('/api/entries/'.length)));
return json(res, 200, { ok: true });
}
if (path.startsWith('/api/')) throw fail(404, 'Operação não encontrada.');
if (!['GET', 'HEAD'].includes(req.method)) throw fail(405, 'Método não permitido.');
let file = resolve(root, '.' + decodeURIComponent(path));
if (file !== root && !file.startsWith(root + sep)) throw fail(403, 'Caminho inválido.');
if (!existsSync(file) || statSync(file).isDirectory()) file = resolve(root, 'index.html');
if (!existsSync(file)) throw fail(404, 'Compile a aplicação com npm run build.');
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.woff2': 'font/woff2' };
res.writeHead(200, { 'Content-Type': types[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
res.end(req.method === 'HEAD' ? undefined : readFileSync(file));
} catch (error) {
if (!error.status) console.error(error);
if (!res.headersSent) json(res, error.status || 500, { error: error.status ? error.message : 'Não foi possível guardar os dados. Tente novamente.' });
else res.end();
}
});
server.on('close', () => db.close());
return server;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const server = createApp();
const port = Number(process.env.PORT || 3000);
server.listen(port, '0.0.0.0', () => console.log(`À Mesa disponível na porta ${port}`));
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => server.close());
}