@paroicms/server
Version:
The ParoiCMS server
84 lines • 3.2 kB
JavaScript
import { parseSqliteDateTime } from "@paroicms/internal-server-lib";
import { type } from "arktype";
const EventLogEntryRowAT = type({
id: "number",
eventType: "string",
actorEmail: "string|null",
actorName: "string|null",
targetType: "string",
targetId: "string",
eventData: "string|null",
createdAt: "string|number|Date",
"+": "reject",
}).pipe((r) => ({
id: String(r.id),
eventType: r.eventType,
actorEmail: r.actorEmail ?? undefined,
actorName: r.actorName ?? undefined,
targetType: r.targetType,
targetId: r.targetId,
eventData: r.eventData ?? undefined,
createdAt: parseSqliteDateTime(r.createdAt),
}));
const EventLogCountRowAT = type({
count: "number",
"+": "reject",
});
export async function getEventLog(siteContext, options) {
const { offset, limit: requestedLimit, searchText } = options;
const limit = requestedLimit > 200 ? 200 : requestedLimit;
let countQuery = siteContext
.cn("PaEventLog as e")
.leftJoin("PaAccount as a", "e.actorId", "a.id");
let dataQuery = siteContext
.cn("PaEventLog as e")
.select("e.id", "e.eventType", "a.email as actorEmail", "a.name as actorName", "e.targetType", "e.targetId", "e.eventData", "e.createdAt")
.leftJoin("PaAccount as a", "e.actorId", "a.id");
if (searchText) {
const searchPattern = `%${searchText}%`;
const applySearch = (builder) => {
builder
.where("e.eventData", "like", searchPattern)
.orWhere("a.email", "like", searchPattern)
.orWhere("a.name", "like", searchPattern);
};
countQuery = countQuery.where(applySearch);
dataQuery = dataQuery.where(applySearch);
}
const countResult = await countQuery.count("* as count").first();
const total = countResult ? EventLogCountRowAT.assert(countResult).count : 0;
const rows = await dataQuery.orderBy("e.createdAt", "desc").limit(limit).offset(offset);
const items = rows.map((row) => EventLogEntryRowAT.assert(row));
return {
items,
total,
offset,
};
}
export async function cleanupOldEventLogEntries(siteContext, { retainCount }) {
const deletedOld = await siteContext
.cn("PaEventLog")
.whereRaw("createdAt < datetime(current_timestamp, '-1 year')")
.delete();
const countResult = await siteContext.cn("PaEventLog").count("* as count").first();
const count = countResult ? EventLogCountRowAT.assert(countResult).count : 0;
if (count > retainCount + 500) {
const rowsToDelete = count - retainCount;
const deletedRecent = await siteContext
.cn("PaEventLog as e")
.whereExists(function () {
this.select(1)
.from(siteContext
.cn("PaEventLog")
.select("id")
.orderBy("createdAt", "asc")
.limit(rowsToDelete)
.as("old"))
.whereRaw("e.id = old.id");
})
.delete();
return deletedOld + deletedRecent;
}
return deletedOld;
}
//# sourceMappingURL=event-log.queries.js.map