2023-12-25 06:47:16 +00:00
|
|
|
import express from "express";
|
|
|
|
import mongoose from "mongoose";
|
|
|
|
import ImageModel from "./ImageModel";
|
2023-12-27 16:07:32 +00:00
|
|
|
import listEndpoints from "express-list-endpoints";
|
2023-12-25 06:47:16 +00:00
|
|
|
|
2023-12-25 11:15:19 +00:00
|
|
|
export const app = express();
|
2023-12-25 06:47:16 +00:00
|
|
|
|
|
|
|
app.use(express.json());
|
|
|
|
|
|
|
|
app.get("/", (_, res) => {
|
2023-12-27 16:07:32 +00:00
|
|
|
const endpoints = listEndpoints(app);
|
|
|
|
res.json({ endpoints });
|
2023-12-25 06:47:16 +00:00
|
|
|
});
|
|
|
|
|
2023-12-27 15:52:15 +00:00
|
|
|
app.get("/images", async (_, res) => {
|
|
|
|
try {
|
|
|
|
const allImages = await ImageModel.find();
|
|
|
|
res.json({ message: allImages });
|
|
|
|
} catch (error) {
|
|
|
|
res.status(500).json({ message: error });
|
|
|
|
}
|
|
|
|
});
|
2023-12-25 06:47:16 +00:00
|
|
|
|
2023-12-25 10:17:56 +00:00
|
|
|
app.post("/images", async (req, res) => {
|
2023-12-27 15:52:15 +00:00
|
|
|
try {
|
|
|
|
// Should add auth here before doing stuff
|
|
|
|
// Thowing a 401 if not auth provided
|
|
|
|
// Throwing a 403 for incorrect auth
|
|
|
|
const image = await ImageModel.create(req.body);
|
|
|
|
res.status(201).json({ message: image });
|
|
|
|
} catch (error: any) {
|
|
|
|
if (error.code == 11000) {
|
|
|
|
// Should return 409 Conflict for existing urls
|
|
|
|
res.status(409).json({ message: "Existing URL" });
|
2023-12-25 10:17:56 +00:00
|
|
|
}
|
2023-12-27 15:52:15 +00:00
|
|
|
// Should return 400 Bad request for invalid requests
|
|
|
|
res.status(400).json({ message: error });
|
|
|
|
}
|
|
|
|
});
|
2023-12-25 10:17:56 +00:00
|
|
|
|
2023-12-25 06:47:16 +00:00
|
|
|
// Set the default port to 8080, or use the PORT environment variable
|
|
|
|
|
|
|
|
const start = async () => {
|
2023-12-27 15:52:15 +00:00
|
|
|
const port = process.env.PORT || 8080;
|
|
|
|
const mongo_uri: string = process.env.MONGODB_URI || "";
|
|
|
|
const mongo_user = process.env.MONGODB_USER;
|
|
|
|
const mongo_pass = process.env.MONGODB_PASS;
|
|
|
|
|
|
|
|
try {
|
|
|
|
await mongoose.connect(mongo_uri, {
|
|
|
|
authSource: "admin",
|
|
|
|
user: mongo_user,
|
|
|
|
pass: mongo_pass,
|
|
|
|
});
|
|
|
|
app.listen(port, () =>
|
|
|
|
console.log(`Express server listening on port ${port}`)
|
|
|
|
);
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
|
|
|
process.exit(1);
|
|
|
|
}
|
|
|
|
};
|
2023-12-25 06:47:16 +00:00
|
|
|
|
|
|
|
start();
|