server/database/entities/Like.ts

87 lines
2.5 KiB
TypeScript
Raw Normal View History

2024-04-07 07:30:49 +02:00
import { config } from "config-manager";
import { type InferSelectModel, and, eq } from "drizzle-orm";
import type * as Lysand from "lysand-types";
import { db } from "~drizzle/db";
import { like, notification } from "~drizzle/schema";
import type { StatusWithRelations } from "./Status";
import type { UserWithRelations } from "./User";
export type Like = InferSelectModel<typeof like>;
2023-10-28 22:21:04 +02:00
/**
* Represents a Like entity in the database.
*/
export const likeToLysand = (like: Like): Lysand.Like => {
2024-04-07 07:30:49 +02:00
return {
id: like.id,
// biome-ignore lint/suspicious/noExplicitAny: to be rewritten
author: (like as any).liker?.uri,
type: "Like",
created_at: new Date(like.createdAt).toISOString(),
// biome-ignore lint/suspicious/noExplicitAny: to be rewritten
object: (like as any).liked?.uri,
uri: new URL(
`/objects/like/${like.id}`,
config.http.base_url,
).toString(),
2024-04-07 07:30:49 +02:00
};
};
2023-11-23 19:43:56 +01:00
2023-11-26 22:54:20 +01:00
/**
* Create a like
* @param user User liking the status
* @param status Status being liked
*/
2023-11-23 19:43:56 +01:00
export const createLike = async (
2024-04-07 07:30:49 +02:00
user: UserWithRelations,
status: StatusWithRelations,
2023-11-23 19:43:56 +01:00
) => {
await db.insert(like).values({
likedId: status.id,
likerId: user.id,
2024-04-07 07:30:49 +02:00
});
2023-11-23 19:43:56 +01:00
2024-04-07 07:30:49 +02:00
if (status.author.instanceId === user.instanceId) {
// Notify the user that their post has been favourited
await db.insert(notification).values({
accountId: user.id,
type: "favourite",
notifiedId: status.authorId,
statusId: status.id,
2024-04-07 07:30:49 +02:00
});
} else {
// TODO: Add database jobs for federating this
}
2023-11-23 19:43:56 +01:00
};
2023-11-26 22:54:20 +01:00
/**
* Delete a like
* @param user User deleting their like
* @param status Status being unliked
*/
export const deleteLike = async (
2024-04-07 07:30:49 +02:00
user: UserWithRelations,
status: StatusWithRelations,
) => {
await db
.delete(like)
.where(and(eq(like.likedId, status.id), eq(like.likerId, user.id)));
2024-04-07 07:30:49 +02:00
// Notify the user that their post has been favourited
await db
.delete(notification)
.where(
and(
eq(notification.accountId, user.id),
eq(notification.type, "favourite"),
eq(notification.notifiedId, status.authorId),
eq(notification.statusId, status.id),
),
);
2024-04-07 07:30:49 +02:00
if (user.instanceId === null && status.author.instanceId !== null) {
// User is local, federate the delete
// TODO: Federate this
}
};