server/database/entities/Like.ts

78 lines
2.4 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 { Likes, Notifications } from "~drizzle/schema";
import type { Note } from "~packages/database-interface/note";
import type { User } from "~packages/database-interface/user";
export type Like = InferSelectModel<typeof Likes>;
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.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 note Status being liked
2023-11-26 22:54:20 +01:00
*/
export const createLike = async (user: User, note: Note) => {
await db.insert(Likes).values({
likedId: note.id,
likerId: user.id,
2024-04-07 07:30:49 +02:00
});
2023-11-23 19:43:56 +01:00
if (note.getAuthor().getUser().instanceId === user.getUser().instanceId) {
2024-04-07 07:30:49 +02:00
// Notify the user that their post has been favourited
await db.insert(Notifications).values({
accountId: user.id,
type: "favourite",
notifiedId: note.getAuthor().id,
noteId: note.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 note Status being unliked
2023-11-26 22:54:20 +01:00
*/
export const deleteLike = async (user: User, note: Note) => {
await db
.delete(Likes)
.where(and(eq(Likes.likedId, note.id), eq(Likes.likerId, user.id)));
2024-04-07 07:30:49 +02:00
// Notify the user that their post has been favourited
await db
.delete(Notifications)
.where(
and(
eq(Notifications.accountId, user.id),
eq(Notifications.type, "favourite"),
eq(Notifications.notifiedId, note.getAuthor().id),
eq(Notifications.noteId, note.id),
),
);
if (user.isLocal() && note.getAuthor().isRemote()) {
2024-04-07 07:30:49 +02:00
// User is local, federate the delete
// TODO: Federate this
}
};