backend/src/server.js (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
import express from 'express';
import rateLimit from 'express-rate-limit';
import { initDb } from './db.js';
import { MSG } from './messages.js';
import documentsRouter from './routes/documents.js';
const PORT = Number(process.env.PORT) || 41738;
const DATABASE_PATH =
process.env.DATABASE_PATH ||
(process.env.NODE_ENV === 'production' ? '/app/data/snow.db' : './data/snow.db');
const CORS_ORIGIN = process.env.CORS_ORIGIN?.trim() || '';
initDb(DATABASE_PATH);
const app = express();
app.set('trust proxy', 1);
if (CORS_ORIGIN) {
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin === CORS_ORIGIN) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
}
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
next();
});
}
app.use(express.json({ limit: '1.1mb' }));
const apiLimiter = rateLimit({
windowMs: 60 * 1000,
max: 60,
standardHeaders: true,
legacyHeaders: false,
message: {
error: 'RATE_LIMIT',
message: MSG.RATE_LIMIT,
},
});
app.use('/api', apiLimiter, documentsRouter);
app.use((err, _req, res, next) => {
if (err instanceof SyntaxError && 'body' in err) {
return res.status(400).json({
error: 'INVALID_JSON',
message: MSG.INVALID_JSON,
});
}
next(err);
});
app.use((err, _req, res, _next) => {
if (err?.type === 'entity.too.large') {
return res.status(413).json({
error: 'CONTENT_TOO_LARGE',
message: MSG.CONTENT_TOO_LARGE,
});
}
console.error(err);
res.status(500).json({
error: 'INTERNAL_ERROR',
message: MSG.INTERNAL_ERROR,
});
});
app.listen(PORT, '0.0.0.0', () => {
console.log(`Snow Editor API listening on http://0.0.0.0:${PORT}`);
console.log(`Database: ${DATABASE_PATH}`);
});
|