1 |
import Punishment from "../../models/Punishment"; |
2 |
import Controller from "../Controller"; |
3 |
import RequireAuth from "../middleware/RequireAuth"; |
4 |
import ValidatorError from "../middleware/ValidatorError"; |
5 |
import Request from "../Request"; |
6 |
|
7 |
export default class HistoryController extends Controller { |
8 |
globalMiddleware(): Function[] { |
9 |
return [RequireAuth, ValidatorError]; |
10 |
} |
11 |
|
12 |
async index(request: Request) { |
13 |
if (!request.user?.guilds.includes(request.params.id)) { |
14 |
return this.response({ error: "You don't have permission to access history of this guild." }, 403); |
15 |
} |
16 |
|
17 |
const queryLimit = parseInt((request.query.limit as string) ?? '0'); |
18 |
const limit = request.query.limit ? (queryLimit < 1 || queryLimit > 20 ? 20 : queryLimit) : 20; |
19 |
const maxPages = Math.ceil((await Punishment.count({ guild_id: request.params.id })) / limit); |
20 |
const page = request.query.page ? parseInt(request.query.page as string) : 1; |
21 |
|
22 |
if (maxPages < page) { |
23 |
return this.response({ error: "That page does not exist" }, 404); |
24 |
} |
25 |
|
26 |
const offset = (page - 1) * limit; |
27 |
|
28 |
const data = (await Punishment.find({ guild_id: request.params.id }).skip(offset).limit(limit)); |
29 |
const newData = []; |
30 |
|
31 |
for await (const row of data) { |
32 |
let user = { id: row.user_id }; |
33 |
|
34 |
try { |
35 |
user = this.client.users.cache.get(row.user_id) || await this.client.users.fetch(row.user_id); |
36 |
} |
37 |
catch (e) { |
38 |
console.log(e); |
39 |
} |
40 |
|
41 |
const newRow = { |
42 |
...(row.toJSON()), |
43 |
user |
44 |
}; |
45 |
|
46 |
newData.push(newRow); |
47 |
} |
48 |
|
49 |
return newData; |
50 |
} |
51 |
} |