Skip to content

Commit

Permalink
endpoint location files
Browse files Browse the repository at this point in the history
  • Loading branch information
Kathund committed Nov 20, 2023
1 parent 1829ac9 commit 6e32b58
Show file tree
Hide file tree
Showing 4 changed files with 132 additions and 69 deletions.
84 changes: 15 additions & 69 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { apiMessage, errorMessage, otherMessage } from "./src/logger";
import fileUpload, { UploadedFile } from "express-fileupload";
import express, { Request, Response } from "express";
import { url, key, PORT } from "./config.json";
import { errorMessage, otherMessage } from "./src/logger";
import { loadEndpoints } from "./src/helper";
import fileUpload from "express-fileupload";
import { existsSync, mkdirSync } from "fs";
import { PORT } from "./config.json";
import express from "express";
import { join } from "path";

const filesDir = join(__dirname, "src", "files");
const filesDir = join(__dirname, "src", "files");
if (!existsSync(filesDir)) {
mkdirSync(filesDir);
}
Expand All @@ -15,70 +16,15 @@ const app = express();
try {
app.use(fileUpload());

app.post("/save/:name", async (req: Request, res: Response) => {
try {
const apiKey = req.headers["API-KEY"];
if (apiKey !== key) {
errorMessage("Invalid API key provided");
return res
.status(400)
.send({ sucsess: false, message: "Invalid API key" });
}
apiMessage(req.path, "User is trying to save a file");

const file = req.files?.file as UploadedFile;
if (!file) {
errorMessage("No file provided for upload");
return res
.status(400)
.send({ sucsess: false, message: "No file provided" });
}

const fileName = req.params.name;
const filePath = join(__dirname, "src", "files", fileName);
if (existsSync(filePath)) {
errorMessage(`File ${fileName} already exists`);
return res
.status(400)
.json({ sucsess: false, message: `File ${fileName} already exists` });
}

await file.mv(filePath);

apiMessage(req.path, `File ${fileName} saved successfully`);
return res.status(200).json({
sucsess: true,
message: `File has been saved at ${url}/${fileName}`,
});
} catch (err) {
errorMessage(err as string);
return res
.status(500)
.json({ sucsess: false, message: "Internal server error" });
}
});

app.get("/:name", async (req: Request, res: Response) => {
try {
const fileName = req.params.name;
apiMessage(req.path, `User is trying to get a file - ${fileName}`);
const filePath = join(__dirname, "src", "files", fileName);
if (!existsSync(filePath)) {
errorMessage(`File ${fileName} not found`);
return res
.status(404)
.send({ sucsess: false, message: `File ${fileName} not found` });
}

apiMessage(req.path, `File ${fileName} found`);
return res.sendFile(filePath);
} catch (err) {
errorMessage(err as string);
return res
.status(500)
.send({ sucsess: false, message: "Internal server error" });
}
});
const endpointsDir = join(__dirname, "src", "endpoints");
const result = loadEndpoints(endpointsDir, app);
if (result !== undefined) {
otherMessage(
`Loaded ${result.loaded} endpoints, skipped ${result.skipped} endpoints`
);
} else {
otherMessage(`No endpoints found in ${endpointsDir}`);
}

app.listen(PORT, () => {
otherMessage(`Server started on port ${PORT} @ http://localhost:${PORT}`);
Expand Down
28 changes: 28 additions & 0 deletions src/endpoints/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Application, Request, Response } from "express";
import { apiMessage, errorMessage } from "../logger";
import { existsSync } from "fs";
import { join } from "path";

export default (app: Application) => {
app.get("/:name", async (req: Request, res: Response) => {
try {
const fileName = req.params.name;
apiMessage(req.path, `User is trying to get a file - ${fileName}`);
const filePath = join(__dirname, "../", "files", fileName);
if (!existsSync(filePath)) {
errorMessage(`File ${fileName} not found`);
return res
.status(404)
.send({ sucsess: false, message: `File ${fileName} not found` });
}

apiMessage(req.path, `File ${fileName} found`);
return res.sendFile(filePath);
} catch (err) {
errorMessage(err as string);
return res
.status(500)
.send({ sucsess: false, message: "Internal server error" });
}
});
};
51 changes: 51 additions & 0 deletions src/endpoints/save.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Application, Request, Response } from "express";
import { apiMessage, errorMessage } from "../logger";
import { UploadedFile } from "express-fileupload";
import { url, key } from "../../config.json";
import { existsSync } from "fs";
import { join } from "path";

export default (app: Application) => {
app.post("/save/:name", async (req: Request, res: Response) => {
try {
const apiKey = req.headers["API-KEY"];
if (apiKey !== key) {
errorMessage("Invalid API key provided");
return res
.status(400)
.send({ sucsess: false, message: "Invalid API key" });
}
apiMessage(req.path, "User is trying to save a file");

const file = req.files?.file as UploadedFile;
if (!file) {
errorMessage("No file provided for upload");
return res
.status(400)
.send({ sucsess: false, message: "No file provided" });
}

const fileName = req.params.name;
const filePath = join(__dirname, "../", "files", fileName);
if (existsSync(filePath)) {
errorMessage(`File ${fileName} already exists`);
return res
.status(400)
.json({ sucsess: false, message: `File ${fileName} already exists` });
}

await file.mv(filePath);

apiMessage(req.path, `File ${fileName} saved successfully`);
return res.status(200).json({
sucsess: true,
message: `File has been saved at ${url}/${fileName}`,
});
} catch (err) {
errorMessage(err as string);
return res
.status(500)
.json({ sucsess: false, message: "Internal server error" });
}
});
};
38 changes: 38 additions & 0 deletions src/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { otherMessage, errorMessage } from './logger';
import { readdirSync, statSync } from 'fs';
import { Application } from 'express';
import { join } from 'path';

export const loadEndpoints = (directory: string, app: Application) => {
try {
const items = readdirSync(directory);

let skipped = 0;
let loaded = 0;

for (const item of items) {
const itemPath = join(directory, item);
const stats = statSync(itemPath);
if (stats.isDirectory()) {
const result = loadEndpoints(itemPath, app);
if (result) {
skipped += result.skipped;
loaded += result.loaded;
}
} else if (item.toLowerCase().endsWith('.ts')) {
if (item.toLowerCase().includes('disabled')) {
skipped++;
continue;
}
loaded++;
// eslint-disable-next-line
const route = require(itemPath).default;
route(app);
otherMessage(`Loaded ${itemPath.split('/src/endpoints/')[1].split('.ts')[0]} endpoint`);
}
}
return { loaded, skipped };
} catch (error: any) {
errorMessage(`Error loading endpoints: ${error}`);
}
};

0 comments on commit 6e32b58

Please sign in to comment.