Skip to content

Commit

Permalink
feat(api): add history controller
Browse files Browse the repository at this point in the history
  • Loading branch information
virtual-designer committed Oct 10, 2022
1 parent 35b7573 commit ec9a670
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/api/controllers/HistoryController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import Punishment from "../../models/Punishment";
import Controller from "../Controller";
import RequireAuth from "../middleware/RequireAuth";
import ValidatorError from "../middleware/ValidatorError";
import Request from "../Request";

export default class HistoryController extends Controller {
globalMiddleware(): Function[] {
return [RequireAuth, ValidatorError];
}

async index(request: Request) {
if (!request.user?.guilds.includes(request.params.id)) {
return this.response({ error: "You don't have permission to access history of this guild." }, 403);
}

const queryLimit = parseInt((request.query.limit as string) ?? '0');
const limit = request.query.limit ? (queryLimit < 1 || queryLimit > 20 ? 20 : queryLimit) : 20;
const maxPages = Math.ceil((await Punishment.count({ guild_id: request.params.id })) / limit);
const page = request.query.page ? parseInt(request.query.page as string) : 1;

if (maxPages < page) {
return this.response({ error: "That page does not exist" }, 404);
}

const offset = (page - 1) * limit;

const data = (await Punishment.find({ guild_id: request.params.id }).skip(offset).limit(limit));
const newData = [];

for await (const row of data) {
let user = { id: row.user_id };

try {
user = this.client.users.cache.get(row.user_id) || await this.client.users.fetch(row.user_id);
}
catch (e) {
console.log(e);
}

const newRow = {
...(row.toJSON()),
user
};

newData.push(newRow);
}

return newData;
}
}
3 changes: 3 additions & 0 deletions src/api/routes/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/

import ConfigController from "../controllers/ConfigController";
import HistoryController from "../controllers/HistoryController";
import InfoController from "../controllers/InfoController";
import MainController from "../controllers/MainController";
import UserController from "../controllers/UserController";
Expand All @@ -32,6 +33,8 @@ Router.patch("/config/:id", [ConfigController, "update"]);
Router.resource("/users", UserController);
Router.post("/login", [UserController, "login"]);

Router.resource("/history/:id", HistoryController);

Router.get("/info/:id/channels", [InfoController, "indexChannels"]);
Router.get("/info/:id/roles", [InfoController, "indexRoles"]);
Router.get("/systeminfo/commands", [InfoController, "indexCommands"]);

0 comments on commit ec9a670

Please sign in to comment.