Files
outline/server/models/View.ts
Tom Moor cc591ebc66 Conversion of User to event system (#9741)
* Conversion of User to event system

* fix

* warning

* fixes

* Skip lastActiveAt in changeset

* fix: Skip count in view changeset

* refactor: Remove userDestroyer

* refactor: Remove userSuspender

* refactor: Remove userUnsuspender

* tests
2025-07-27 13:15:21 -04:00

128 lines
2.4 KiB
TypeScript

import {
FindOrCreateOptions,
InferAttributes,
InferCreationAttributes,
Op,
} from "sequelize";
import {
BelongsTo,
Column,
Default,
ForeignKey,
Table,
DataType,
Scopes,
} from "sequelize-typescript";
import { APIContext } from "@server/types";
import Document from "./Document";
import User from "./User";
import IdModel from "./base/IdModel";
import Fix from "./decorators/Fix";
import { SkipChangeset } from "./decorators/Changeset";
@Scopes(() => ({
withUser: () => ({
include: [
{
model: User,
required: true,
as: "user",
},
],
}),
}))
@Table({ tableName: "views", modelName: "view" })
@Fix
class View extends IdModel<
InferAttributes<View>,
Partial<InferCreationAttributes<View>>
> {
@Column
lastEditingAt: Date | null;
@Default(1)
@Column(DataType.INTEGER)
@SkipChangeset
count: number;
// associations
@BelongsTo(() => User, "userId")
user: User;
@ForeignKey(() => User)
@Column(DataType.UUID)
userId: string;
@BelongsTo(() => Document, "documentId")
document: Document;
@ForeignKey(() => Document)
@Column(DataType.UUID)
documentId: string;
static async incrementOrCreate(
ctx: APIContext,
where: {
userId: string;
documentId: string;
},
options?: FindOrCreateOptions<InferAttributes<View>>
) {
const [model, created] = await this.findOrCreateWithCtx(ctx, {
...options,
where,
});
if (!created) {
model.count += 1;
await model.saveWithCtx(ctx, options, {
name: "create",
});
}
return model;
}
static async findByDocument(
documentId: string,
{ includeSuspended }: { includeSuspended?: boolean }
) {
return this.findAll({
where: {
documentId,
},
order: [["updatedAt", "DESC"]],
include: [
{
model: User,
required: true,
...(includeSuspended
? {}
: { where: { suspendedAt: { [Op.is]: null } } }),
},
],
});
}
static async touch(documentId: string, userId: string, isEditing: boolean) {
const values: Partial<View> = {
updatedAt: new Date(),
};
if (isEditing) {
values.lastEditingAt = new Date();
}
await this.update(values, {
where: {
userId,
documentId,
},
returning: false,
});
}
}
export default View;