server/database/entities/Emoji.ts

79 lines
2 KiB
TypeScript
Raw Normal View History

2024-04-07 07:30:49 +02:00
import type { Emoji } from "@prisma/client";
import { client } from "~database/datasource";
import type { APIEmoji } from "~types/entities/emoji";
import type * as Lysand from "lysand-types";
2023-09-12 22:48:10 +02:00
2023-09-28 20:19:21 +02:00
/**
* Represents an emoji entity in the database.
*/
2023-09-12 22:48:10 +02:00
/**
* Used for parsing emojis from local text
* @param text The text to parse
* @returns An array of emojis
*/
export const parseEmojis = async (text: string): Promise<Emoji[]> => {
2024-04-07 07:30:49 +02:00
const regex = /:[a-zA-Z0-9_]+:/g;
const matches = text.match(regex);
if (!matches) return [];
return await client.emoji.findMany({
where: {
shortcode: {
in: matches.map((match) => match.replace(/:/g, "")),
},
instanceId: null,
},
include: {
instance: true,
},
});
};
2023-09-12 22:48:10 +02:00
export const addEmojiIfNotExists = async (emoji: Lysand.Emoji) => {
2024-04-07 07:30:49 +02:00
const existingEmoji = await client.emoji.findFirst({
where: {
shortcode: emoji.name,
instance: null,
},
});
2024-04-07 07:30:49 +02:00
if (existingEmoji) return existingEmoji;
2024-04-07 07:30:49 +02:00
return await client.emoji.create({
data: {
shortcode: emoji.name,
url: emoji.url[0].content,
alt: emoji.alt || emoji.url[0].description || undefined,
content_type: Object.keys(emoji.url)[0],
2024-04-07 07:30:49 +02:00
visible_in_picker: true,
},
});
};
2023-09-12 22:48:10 +02:00
/**
* Converts the emoji to an APIEmoji object.
* @returns The APIEmoji object.
*/
2023-11-20 03:42:40 +01:00
export const emojiToAPI = (emoji: Emoji): APIEmoji => {
2024-04-07 07:30:49 +02:00
return {
shortcode: emoji.shortcode,
static_url: emoji.url, // TODO: Add static version
url: emoji.url,
visible_in_picker: emoji.visible_in_picker,
category: undefined,
};
};
export const emojiToLysand = (emoji: Emoji): Lysand.Emoji => {
2024-04-07 07:30:49 +02:00
return {
name: emoji.shortcode,
url: {
[emoji.content_type]: {
2024-04-07 07:30:49 +02:00
content: emoji.url,
description: emoji.alt || undefined,
2024-04-07 07:30:49 +02:00
},
},
alt: emoji.alt || undefined,
2024-04-07 07:30:49 +02:00
};
2024-03-04 01:45:21 +01:00
};