2018-08-18 19:51:28 +03:00
|
|
|
import uuid from "uuid/v4"; // tslint:disable-line
|
|
|
|
import moment from "moment-timezone";
|
2018-10-26 06:41:20 +03:00
|
|
|
import { ArchiveEntry } from "./entities/ArchiveEntry";
|
|
|
|
import { getRepository, Repository } from "typeorm";
|
|
|
|
import { BaseRepository } from "./BaseRepository";
|
2018-08-18 19:51:28 +03:00
|
|
|
|
|
|
|
const DEFAULT_EXPIRY_DAYS = 30;
|
|
|
|
|
2018-10-26 06:41:20 +03:00
|
|
|
export class GuildArchives extends BaseRepository {
|
|
|
|
protected archives: Repository<ArchiveEntry>;
|
2018-08-18 19:51:28 +03:00
|
|
|
|
|
|
|
constructor(guildId) {
|
2018-10-26 06:41:20 +03:00
|
|
|
super(guildId);
|
|
|
|
this.archives = getRepository(ArchiveEntry);
|
2018-08-18 19:51:28 +03:00
|
|
|
|
2018-10-26 06:41:20 +03:00
|
|
|
// Clean expired archives at start and then every hour
|
|
|
|
this.deleteExpiredArchives();
|
|
|
|
setInterval(() => this.deleteExpiredArchives(), 1000 * 60 * 60);
|
2018-08-18 19:51:28 +03:00
|
|
|
}
|
|
|
|
|
2018-10-26 06:41:20 +03:00
|
|
|
private deleteExpiredArchives() {
|
|
|
|
this.archives
|
|
|
|
.createQueryBuilder()
|
|
|
|
.where("expires_at <= NOW()")
|
|
|
|
.delete()
|
|
|
|
.execute();
|
|
|
|
}
|
2018-08-18 19:51:28 +03:00
|
|
|
|
2018-10-26 06:41:20 +03:00
|
|
|
async find(id: string): Promise<ArchiveEntry> {
|
|
|
|
return this.archives.findOne({
|
|
|
|
where: { id },
|
|
|
|
relations: this.getRelations()
|
|
|
|
});
|
2018-08-18 19:51:28 +03:00
|
|
|
}
|
|
|
|
|
2018-10-26 06:41:20 +03:00
|
|
|
/**
|
|
|
|
* @returns ID of the created entry
|
|
|
|
*/
|
|
|
|
async create(body: string, expiresAt: moment.Moment = null): Promise<string> {
|
2018-08-18 19:51:28 +03:00
|
|
|
if (!expiresAt) {
|
|
|
|
expiresAt = moment().add(DEFAULT_EXPIRY_DAYS, "days");
|
|
|
|
}
|
|
|
|
|
2018-10-26 06:41:20 +03:00
|
|
|
const result = await this.archives.insert({
|
2018-08-18 19:51:28 +03:00
|
|
|
guild_id: this.guildId,
|
|
|
|
body,
|
|
|
|
expires_at: expiresAt.format("YYYY-MM-DD HH:mm:ss")
|
|
|
|
});
|
|
|
|
|
2018-10-26 06:41:20 +03:00
|
|
|
return result.identifiers[0].id;
|
2018-08-18 19:51:28 +03:00
|
|
|
}
|
|
|
|
}
|