noteshare.space/server/server.ts

77 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-06-22 00:30:11 +03:00
import "dotenv/config";
import express, { Express, Request, Response } from "express";
2022-06-23 21:22:34 +03:00
import cors from "cors";
2022-06-22 00:30:11 +03:00
import { PrismaClient, EncryptedNote } from "@prisma/client";
2022-06-29 15:17:38 +03:00
import { addDays } from "./util";
2022-06-29 18:14:05 +03:00
import helmet from "helmet";
2022-06-22 00:30:11 +03:00
2022-06-29 15:17:38 +03:00
// Initialize middleware clients
2022-06-22 00:30:11 +03:00
const prisma = new PrismaClient();
const app: Express = express();
2022-06-29 15:17:38 +03:00
app.use(express.json());
2022-06-29 18:14:05 +03:00
app.use(helmet());
2022-06-22 00:30:11 +03:00
2022-06-29 15:17:38 +03:00
// Allow CORS in dev mode.
2022-06-23 21:22:34 +03:00
if (process.env.ENVIRONMENT == "dev") {
app.use(
cors({
origin: "*",
})
);
}
2022-06-22 00:30:11 +03:00
// start the Express server
app.listen(process.env.PORT, () => {
console.log(`server started at http://localhost:${process.env.PORT}`);
});
// Post new encrypted note
app.post("/note/", async (req: Request<{}, {}, EncryptedNote>, res) => {
const note = req.body;
2022-06-29 15:17:38 +03:00
const savedNote = await prisma.encryptedNote.create({
2022-06-29 17:05:25 +03:00
data: { ...note, expire_time: addDays(new Date(), 30) },
2022-06-29 15:17:38 +03:00
});
2022-06-29 15:32:02 +03:00
res.json({
view_url: `${process.env.FRONTEND_URL}/note/${savedNote.id}`,
expire_time: savedNote.expire_time,
});
2022-06-22 00:30:11 +03:00
});
// Get encrypted note
app.get("/note/:id", async (req, res) => {
const note = await prisma.encryptedNote.findUnique({
where: { id: req.params.id },
});
if (note != null) {
res.send(note);
}
res.status(404).send();
});
// Default response for any other request
app.use((req, res, next) => {
res.status(404).send();
});
2022-06-29 15:17:38 +03:00
// Clean up expired notes periodically
const interval =
Math.max(parseInt(<string>process.env.CLEANUP_INTERVAL_SECONDS) || 1, 1) *
1000;
setInterval(async () => {
try {
console.log("[Cleanup] Cleaning up expired notes...");
const deleted = await prisma.encryptedNote.deleteMany({
where: {
expire_time: {
lte: new Date(),
},
},
});
console.log(`[Cleanup] Deleted ${deleted.count} expired notes.`);
} catch (err) {
console.error(`[Cleanup] Error cleaning expired notes:`);
console.error(err);
}
}, interval);