code made pretty

This commit is contained in:
Kevin Puig
2025-09-27 21:42:43 -04:00
parent 11f25ca915
commit c305298927
17 changed files with 1394 additions and 1292 deletions

View File

@@ -10,7 +10,7 @@ import{
CreateCategoryInput, CreateCategoryInput,
UpdateCategoryInput, UpdateCategoryInput,
DeleteCategoryInput, DeleteCategoryInput,
DeleteCategoriesByInstanceIdInput DeleteCategoriesByInstanceIdInput,
} from "../validators/categoryValidator"; } from "../validators/categoryValidator";
export async function createNewCategory(data: CreateCategoryInput) { export async function createNewCategory(data: CreateCategoryInput) {
@@ -33,7 +33,8 @@ export async function deleteExistingCategory(data: DeleteCategoryInput) {
return await deleteCategory(data); return await deleteCategory(data);
} }
export async function deleteAllCategoriesByInstance(data: DeleteCategoriesByInstanceIdInput) { export async function deleteAllCategoriesByInstance(
data: DeleteCategoriesByInstanceIdInput,
) {
return await deleteAllCategoriesFromInstance(data); return await deleteAllCategoriesFromInstance(data);
} }

View File

@@ -4,13 +4,13 @@ import{
getChannelsByCategory, getChannelsByCategory,
updateChannel, updateChannel,
deleteChannel, deleteChannel,
deleteAllChannelsFromCategory deleteAllChannelsFromCategory,
} from "../services/channelService"; } from "../services/channelService";
import { import {
CreateChannelInput, CreateChannelInput,
UpdateChannelInput, UpdateChannelInput,
DeleteChannelInput, DeleteChannelInput,
DeleteChannelsByCategoryIdInput DeleteChannelsByCategoryIdInput,
} from "../validators/channelValidator"; } from "../validators/channelValidator";
export async function createNewChannel(data: CreateChannelInput) { export async function createNewChannel(data: CreateChannelInput) {
@@ -33,6 +33,8 @@ export async function deleteExistingChannel(data: DeleteChannelInput) {
return await deleteChannel(data); return await deleteChannel(data);
} }
export async function deleteAllChannelsByCategory(data: DeleteChannelsByCategoryIdInput) { export async function deleteAllChannelsByCategory(
data: DeleteChannelsByCategoryIdInput,
) {
return await deleteAllChannelsFromCategory(data); return await deleteAllChannelsFromCategory(data);
} }

View File

@@ -1,4 +1,8 @@
import { getMessageInformation, getMessagesBefore, sendMessageToChannel } from "../services/messageService"; import {
getMessageInformation,
getMessagesBefore,
sendMessageToChannel,
} from "../services/messageService";
export async function fetchMessageData(id: string) { export async function fetchMessageData(id: string) {
return await getMessageInformation(id); return await getMessageInformation(id);
@@ -13,13 +17,13 @@ export async function sendMessage(
userId: string, userId: string,
content: string, content: string,
token: string, token: string,
repliedMessageId: string | null repliedMessageId: string | null,
) { ) {
return await sendMessageToChannel( return await sendMessageToChannel(
channelId, channelId,
userId, userId,
content, content,
token, token,
repliedMessageId repliedMessageId,
); );
} }

View File

@@ -24,7 +24,7 @@ import {
import { zValidator } from "@hono/zod-validator"; import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono"; import { Hono } from "hono";
import { describeRoute, resolver } from "hono-openapi"; import { describeRoute, resolver } from "hono-openapi";
const categoryRoutes = new Hono() const categoryRoutes = new Hono();
// Create a new category // Create a new category
categoryRoutes.post( categoryRoutes.post(
@@ -67,8 +67,8 @@ categoryRoutes.post(
} else { } else {
return c.json({ error: "Failed to create category" }, 400); return c.json({ error: "Failed to create category" }, 400);
} }
} },
) );
// Get a category by ID // Get a category by ID
categoryRoutes.get( categoryRoutes.get(
@@ -98,7 +98,7 @@ categoryRoutes.get(
} else { } else {
return c.json({ error: "Category not found" }, 404); return c.json({ error: "Category not found" }, 404);
} }
} },
); );
// Get all categories by instance ID // Get all categories by instance ID
@@ -110,13 +110,17 @@ categoryRoutes.get(
200: { 200: {
description: "Success getting all categories in instance", description: "Success getting all categories in instance",
content: { content: {
"application/json": { schema: resolver(getCategoriesByInstanceIdSchema) }, "application/json": {
schema: resolver(getCategoriesByInstanceIdSchema),
},
}, },
}, },
400: { 400: {
description: "Bad Request - Missing instance ID", description: "Bad Request - Missing instance ID",
content: { content: {
"application/json": { schema: resolver(getCategoriesByInstanceIdSchema) }, "application/json": {
schema: resolver(getCategoriesByInstanceIdSchema),
},
}, },
}, },
}, },
@@ -131,9 +135,12 @@ categoryRoutes.get(
if (categoryData) { if (categoryData) {
return c.json(categoryData); return c.json(categoryData);
} else { } else {
return c.json({ error: "Error getting all categories from instance" }, 500); return c.json(
} { error: "Error getting all categories from instance" },
500,
);
} }
},
); );
// Update a category // Update a category
@@ -189,7 +196,7 @@ categoryRoutes.put(
} else { } else {
return c.json({ error: "Failed to update category" }, 400); return c.json({ error: "Failed to update category" }, 400);
} }
} },
); );
// Delete a specific category // Delete a specific category
@@ -240,8 +247,8 @@ categoryRoutes.delete(
} else { } else {
return c.json({ error: "Failed to delete category" }, 400); return c.json({ error: "Failed to delete category" }, 400);
} }
} },
) );
// Delete all categories by instance ID // Delete all categories by instance ID
categoryRoutes.delete( categoryRoutes.delete(
@@ -252,25 +259,33 @@ categoryRoutes.delete(
200: { 200: {
description: "Success deleting all categories in instance", description: "Success deleting all categories in instance",
content: { content: {
"application/json": { schema: resolver(deleteCategoriesByInstanceIdSchema) }, "application/json": {
schema: resolver(deleteCategoriesByInstanceIdSchema),
},
}, },
}, },
400: { 400: {
description: "Bad Request - Invalid input data", description: "Bad Request - Invalid input data",
content: { content: {
"application/json": { schema: resolver(deleteCategoriesByInstanceIdSchema)}, "application/json": {
schema: resolver(deleteCategoriesByInstanceIdSchema),
},
}, },
}, },
401: { 401: {
description: "Unauthorized - Admin access required", description: "Unauthorized - Admin access required",
content: { content: {
"application/json": { schema: resolver(deleteCategoriesByInstanceIdSchema)}, "application/json": {
schema: resolver(deleteCategoriesByInstanceIdSchema),
},
}, },
}, },
404: { 404: {
description: "Instance id or User Id not found", description: "Instance id or User Id not found",
content: { content: {
"application/json": { schema: resolver(deleteCategoriesByInstanceIdSchema)}, "application/json": {
schema: resolver(deleteCategoriesByInstanceIdSchema),
},
}, },
}, },
}, },
@@ -282,7 +297,10 @@ categoryRoutes.delete(
// Ensure the instanceId in the path matches the one in the body // Ensure the instanceId in the path matches the one in the body
if (data.instanceId !== instanceId) { if (data.instanceId !== instanceId) {
return c.json({ error: "Instance ID in path does not match Instance ID in body" }, 400); return c.json(
{ error: "Instance ID in path does not match Instance ID in body" },
400,
);
} }
const categoryData = await deleteAllCategoriesByInstance(data); const categoryData = await deleteAllCategoriesByInstance(data);
@@ -291,7 +309,7 @@ categoryRoutes.delete(
} else { } else {
return c.json({ error: "Failed to delete categories" }, 400); return c.json({ error: "Failed to delete categories" }, 400);
} }
} },
) );
export { categoryRoutes }; export { categoryRoutes };

View File

@@ -14,7 +14,6 @@ import {
updateChannelSchema, updateChannelSchema,
deleteChannelSchema, deleteChannelSchema,
deleteChannelsByCategoryIdSchema, deleteChannelsByCategoryIdSchema,
CreateChannelInput, CreateChannelInput,
GetChannelInput, GetChannelInput,
GetChannelsByCategoryIdInput, GetChannelsByCategoryIdInput,
@@ -26,7 +25,7 @@ import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono"; import { Hono } from "hono";
import { describeRoute, resolver } from "hono-openapi"; import { describeRoute, resolver } from "hono-openapi";
const channelRoutes = new Hono() const channelRoutes = new Hono();
// Create a new channel // Create a new channel
channelRoutes.post( channelRoutes.post(
@@ -69,8 +68,8 @@ channelRoutes.post(
} else { } else {
return c.json({ error: "Failed to create channel" }, 400); return c.json({ error: "Failed to create channel" }, 400);
} }
} },
) );
// Get a channel by ID // Get a channel by ID
channelRoutes.get( channelRoutes.get(
@@ -100,7 +99,7 @@ channelRoutes.get(
} else { } else {
return c.json({ error: "Channel not found" }, 404); return c.json({ error: "Channel not found" }, 404);
} }
} },
); );
// Get all channels by category ID // Get all channels by category ID
@@ -112,13 +111,17 @@ channelRoutes.get(
200: { 200: {
description: "Success getting all channels in category", description: "Success getting all channels in category",
content: { content: {
"application/json": { schema: resolver(getChannelsByCategoryIdSchema) }, "application/json": {
schema: resolver(getChannelsByCategoryIdSchema),
},
}, },
}, },
400: { 400: {
description: "Bad Request - Missing category ID", description: "Bad Request - Missing category ID",
content: { content: {
"application/json": { schema: resolver(getChannelsByCategoryIdSchema) }, "application/json": {
schema: resolver(getChannelsByCategoryIdSchema),
},
}, },
}, },
}, },
@@ -135,7 +138,7 @@ channelRoutes.get(
} else { } else {
return c.json({ error: "Error getting channels from category" }, 500); return c.json({ error: "Error getting channels from category" }, 500);
} }
} },
); );
// Update a channel // Update a channel
@@ -191,7 +194,7 @@ channelRoutes.put(
} else { } else {
return c.json({ error: "Failed to update channel" }, 400); return c.json({ error: "Failed to update channel" }, 400);
} }
} },
); );
// Delete a specific channel // Delete a specific channel
@@ -242,7 +245,7 @@ channelRoutes.delete(
} else { } else {
return c.json({ error: "Failed to delete channel" }, 400); return c.json({ error: "Failed to delete channel" }, 400);
} }
} },
); );
// Delete all channels by category ID // Delete all channels by category ID
@@ -254,25 +257,33 @@ channelRoutes.delete(
200: { 200: {
description: "Success deleting all channels in category", description: "Success deleting all channels in category",
content: { content: {
"application/json": { schema: resolver(deleteChannelsByCategoryIdSchema) }, "application/json": {
schema: resolver(deleteChannelsByCategoryIdSchema),
},
}, },
}, },
400: { 400: {
description: "Bad Request - Invalid input data", description: "Bad Request - Invalid input data",
content: { content: {
"application/json": { schema: resolver(deleteChannelsByCategoryIdSchema)}, "application/json": {
schema: resolver(deleteChannelsByCategoryIdSchema),
},
}, },
}, },
401: { 401: {
description: "Unauthorized - Admin access required", description: "Unauthorized - Admin access required",
content: { content: {
"application/json": { schema: resolver(deleteChannelsByCategoryIdSchema)}, "application/json": {
schema: resolver(deleteChannelsByCategoryIdSchema),
},
}, },
}, },
404: { 404: {
description: "Category id or User Id not found", description: "Category id or User Id not found",
content: { content: {
"application/json": { schema: resolver(deleteChannelsByCategoryIdSchema)}, "application/json": {
schema: resolver(deleteChannelsByCategoryIdSchema),
},
}, },
}, },
}, },
@@ -284,7 +295,10 @@ channelRoutes.delete(
// Ensure the categoryId in the path matches the one in the body // Ensure the categoryId in the path matches the one in the body
if (data.categoryId !== categoryId) { if (data.categoryId !== categoryId) {
return c.json({ error: "Category ID in path does not match Category ID in body" }, 400); return c.json(
{ error: "Category ID in path does not match Category ID in body" },
400,
);
} }
const result = await deleteAllChannelsByCategory(data); const result = await deleteAllChannelsByCategory(data);
@@ -293,7 +307,7 @@ channelRoutes.delete(
} else { } else {
return c.json({ error: "Failed to delete channels" }, 400); return c.json({ error: "Failed to delete channels" }, 400);
} }
} },
) );
export { channelRoutes }; export { channelRoutes };

View File

@@ -1,8 +1,14 @@
import { Hono } from "hono"; import { Hono } from "hono";
import { describeRoute, resolver } from "hono-openapi"; import { describeRoute, resolver } from "hono-openapi";
import { createInstanceRequestSchema, getAllInstancesResponseSchema } from "../validators/instanceValidator"; import {
createInstanceRequestSchema,
getAllInstancesResponseSchema,
} from "../validators/instanceValidator";
import { zValidator } from "@hono/zod-validator"; import { zValidator } from "@hono/zod-validator";
import { createInstanceReq, getAllInstancesReq } from "../controller/instanceController"; import {
createInstanceReq,
getAllInstancesReq,
} from "../controller/instanceController";
const instanceRoutes = new Hono(); const instanceRoutes = new Hono();
@@ -14,15 +20,15 @@ instanceRoutes.post(
200: { 200: {
description: "Instance created", description: "Instance created",
content: { content: {
"application/json": { schema: resolver(createInstanceRequestSchema) } "application/json": { schema: resolver(createInstanceRequestSchema) },
}, },
}, },
400: { 400: {
description: "Invalid request", description: "Invalid request",
}, },
} },
}), }),
zValidator('json', createInstanceRequestSchema), zValidator("json", createInstanceRequestSchema),
async (c) => { async (c) => {
const data = await c.req.json(); const data = await c.req.json();
if (!data) { if (!data) {
@@ -31,7 +37,7 @@ instanceRoutes.post(
const instance = await createInstanceReq(data); const instance = await createInstanceReq(data);
return c.json(instance, 201); return c.json(instance, 201);
} },
); );
instanceRoutes.get( instanceRoutes.get(
@@ -42,22 +48,30 @@ instanceRoutes.get(
200: { 200: {
description: "List of all instances", description: "List of all instances",
content: { content: {
"application/json": { schema: resolver(getAllInstancesResponseSchema) } "application/json": {
schema: resolver(getAllInstancesResponseSchema),
},
}, },
}, },
500: { 500: {
description: "Server error", description: "Server error",
}, },
} },
}), }),
async (c) => { async (c) => {
const instances = await getAllInstancesReq(); const instances = await getAllInstancesReq();
if (instances.success) { if (instances.success) {
return c.json(instances, 200); return c.json(instances, 200);
} else { } else {
return c.json({ success: false, error: instances.error || "Failed to fetch instances" }, 500); return c.json(
} {
success: false,
error: instances.error || "Failed to fetch instances",
},
500,
);
} }
},
); );
export default instanceRoutes; export default instanceRoutes;

View File

@@ -1,8 +1,16 @@
import { Hono } from "hono"; import { Hono } from "hono";
import { describeResponse, describeRoute, resolver } from "hono-openapi"; import { describeResponse, describeRoute, resolver } from "hono-openapi";
import { getMessageByIdSchema, getMessagesBeforeDate, sendMessageSchema } from "../validators/messageValidator"; import {
getMessageByIdSchema,
getMessagesBeforeDate,
sendMessageSchema,
} from "../validators/messageValidator";
import { zValidator } from "@hono/zod-validator"; import { zValidator } from "@hono/zod-validator";
import { fetchMessageData, fetchMessagesBefore, sendMessage } from "../controller/messageController"; import {
fetchMessageData,
fetchMessagesBefore,
sendMessage,
} from "../controller/messageController";
const messageRoutes = new Hono(); const messageRoutes = new Hono();
@@ -14,16 +22,16 @@ messageRoutes.get(
200: { 200: {
description: "Success getting message", description: "Success getting message",
content: { content: {
"application/json": { schema: resolver(getMessageByIdSchema) } "application/json": { schema: resolver(getMessageByIdSchema) },
} },
}, },
404: { 404: {
description: "Message id not found", description: "Message id not found",
content: { content: {
"application/json": { schema: resolver(getMessageByIdSchema) } "application/json": { schema: resolver(getMessageByIdSchema) },
} },
} },
} },
}), }),
zValidator("param", getMessageByIdSchema), zValidator("param", getMessageByIdSchema),
async (c) => { async (c) => {
@@ -35,8 +43,8 @@ messageRoutes.get(
} else { } else {
return c.json({ error: "Message not found" }, 404); return c.json({ error: "Message not found" }, 404);
} }
} },
) );
messageRoutes.get( messageRoutes.get(
"", "",
@@ -46,10 +54,10 @@ messageRoutes.get(
200: { 200: {
description: "Success getting up to 50 messages", description: "Success getting up to 50 messages",
content: { content: {
"application/json": { schema: resolver(getMessagesBeforeDate) } "application/json": { schema: resolver(getMessagesBeforeDate) },
} },
} },
} },
}), }),
zValidator("query", getMessagesBeforeDate), zValidator("query", getMessagesBeforeDate),
async (c) => { async (c) => {
@@ -70,8 +78,8 @@ messageRoutes.get(
} else { } else {
return c.json({ error: "Failed to fetch messages" }, 500); return c.json({ error: "Failed to fetch messages" }, 500);
} }
} },
) );
messageRoutes.post( messageRoutes.post(
"", "",
@@ -81,41 +89,58 @@ messageRoutes.post(
201: { 201: {
description: "Message sent successfully", description: "Message sent successfully",
content: { content: {
"application/json": { schema: resolver(sendMessageSchema) } "application/json": { schema: resolver(sendMessageSchema) },
} },
}, },
401: { 401: {
description: "Unauthorized - invalid token or user credentials", description: "Unauthorized - invalid token or user credentials",
content: { content: {
"application/json": { schema: { type: "object", properties: { error: { type: "string" } } } } "application/json": {
} schema: {
type: "object",
properties: { error: { type: "string" } },
},
},
},
}, },
500: { 500: {
description: "Server error", description: "Server error",
content: { content: {
"application/json": { schema: { type: "object", properties: { error: { type: "string" } } } } "application/json": {
} schema: {
} type: "object",
} properties: { error: { type: "string" } },
},
},
},
},
},
}), }),
zValidator("json", sendMessageSchema), zValidator("json", sendMessageSchema),
async (c) => { async (c) => {
const { channelId, userId, content, token, repliedMessageId } = await c.req.json(); const { channelId, userId, content, token, repliedMessageId } =
await c.req.json();
const result = await sendMessage( const result = await sendMessage(
channelId, channelId,
userId, userId,
content, content,
token, token,
repliedMessageId || null repliedMessageId || null,
); );
if (result) { if (result) {
return c.json(result, 201); return c.json(result, 201);
} else { } else {
return c.json({ error: "Failed to send message. Check your credentials and try again." }, 401); return c.json(
{
error:
"Failed to send message. Check your credentials and try again.",
},
401,
);
} }
} },
) );
export default messageRoutes; export default messageRoutes;

View File

@@ -1,33 +1,30 @@
import{ import { Channel, Category } from "@prisma/client";
Channel,
Category
} from '@prisma/client';
import { PrismaClient } from "@prisma/client"; import { PrismaClient } from "@prisma/client";
import { getUserInformation, getUserCredentials } from './userService'; import { getUserInformation, getUserCredentials } from "./userService";
import { import {
CreateChannelInput, CreateChannelInput,
UpdateChannelInput, UpdateChannelInput,
DeleteChannelInput, DeleteChannelInput,
DeleteChannelsByCategoryIdInput DeleteChannelsByCategoryIdInput,
} from '../validators/channelValidator'; } from "../validators/channelValidator";
import { import {
UpdateCategoryInput, UpdateCategoryInput,
DeleteCategoryInput, DeleteCategoryInput,
DeleteCategoriesByInstanceIdInput, DeleteCategoriesByInstanceIdInput,
CreateCategoryInput CreateCategoryInput,
} from '../validators/categoryValidator'; } from "../validators/categoryValidator";
const prisma = new PrismaClient(); const prisma = new PrismaClient();
export async function createCategory(
export async function createCategory(data: CreateCategoryInput): Promise<Category | null>{ data: CreateCategoryInput,
): Promise<Category | null> {
try { try {
//Confirm if user exists and is admin //Confirm if user exists and is admin
const requestingUser = await getUserInformation(data.requestingUserId); const requestingUser = await getUserInformation(data.requestingUserId);
const requestingUserCredentials = await getUserCredentials( const requestingUserCredentials = await getUserCredentials(
data.requestingUserId, data.requestingUserId,
) );
if ( if (
!requestingUser || !requestingUser ||
@@ -42,8 +39,8 @@ export async function createCategory(data: CreateCategoryInput): Promise<Categor
const newCategory = await prisma.category.create({ const newCategory = await prisma.category.create({
data: { data: {
name: data.name, name: data.name,
position: data.position position: data.position,
} },
}); });
if (!newCategory) { if (!newCategory) {
@@ -54,11 +51,11 @@ export async function createCategory(data: CreateCategoryInput): Promise<Categor
if (data.instanceId) { if (data.instanceId) {
curInstance = await prisma.instance.findUnique({ curInstance = await prisma.instance.findUnique({
where: { where: {
id: data.instanceId id: data.instanceId,
}, },
include: { include: {
Category: true Category: true,
} },
}); });
if (!curInstance) { if (!curInstance) {
@@ -67,11 +64,11 @@ export async function createCategory(data: CreateCategoryInput): Promise<Categor
await prisma.category.update({ await prisma.category.update({
where: { where: {
id: newCategory.id id: newCategory.id,
}, },
data: { data: {
instanceId: curInstance.id instanceId: curInstance.id,
} },
}); });
return newCategory; return newCategory;
@@ -90,8 +87,8 @@ export async function getCategory(
try { try {
const category = await prisma.category.findUnique({ const category = await prisma.category.findUnique({
where: { where: {
id: categoryId id: categoryId,
} },
}); });
if (!category) { if (!category) {
@@ -106,19 +103,19 @@ export async function getCategory(
} }
export async function getCategoriesByInstance( export async function getCategoriesByInstance(
instanceId: string instanceId: string,
): Promise<Category[] | null> { ): Promise<Category[] | null> {
try { try {
const categories = await prisma.category.findMany({ const categories = await prisma.category.findMany({
where: { where: {
instanceId: instanceId instanceId: instanceId,
}, },
include: { include: {
Channel: true Channel: true,
}, },
orderBy: { orderBy: {
position: 'asc' position: "asc",
} },
}); });
if (!categories) { if (!categories) {
@@ -132,14 +129,15 @@ export async function getCategoriesByInstance(
} }
} }
export async function updateCategory(data: UpdateCategoryInput): Promise<Category | null>{ export async function updateCategory(
data: UpdateCategoryInput,
): Promise<Category | null> {
try { try {
//Confirm if user exists and is admin //Confirm if user exists and is admin
const requestingUser = await getUserInformation(data.requestingUserId); const requestingUser = await getUserInformation(data.requestingUserId);
const requestingUserCredentials = await getUserCredentials( const requestingUserCredentials = await getUserCredentials(
data.requestingUserId, data.requestingUserId,
) );
if ( if (
!requestingUser || !requestingUser ||
@@ -153,13 +151,13 @@ export async function updateCategory(data: UpdateCategoryInput): Promise<Categor
const updatedCategory = await prisma.category.update({ const updatedCategory = await prisma.category.update({
where: { where: {
id: data.id id: data.id,
}, },
data: { data: {
name: data.name, name: data.name,
position: data.position, position: data.position,
Channel: data.channels ? { set: data.channels } : undefined Channel: data.channels ? { set: data.channels } : undefined,
} },
}); });
if (!updatedCategory) { if (!updatedCategory) {
@@ -173,14 +171,15 @@ export async function updateCategory(data: UpdateCategoryInput): Promise<Categor
} }
} }
export async function deleteCategory(data: DeleteCategoryInput): Promise<boolean | null>{ export async function deleteCategory(
data: DeleteCategoryInput,
): Promise<boolean | null> {
try { try {
//Confirm if user exists and is admin //Confirm if user exists and is admin
const requestingUser = await getUserInformation(data.requestingUserId); const requestingUser = await getUserInformation(data.requestingUserId);
const requestingUserCredentials = await getUserCredentials( const requestingUserCredentials = await getUserCredentials(
data.requestingUserId, data.requestingUserId,
) );
if ( if (
!requestingUser || !requestingUser ||
@@ -194,8 +193,8 @@ export async function deleteCategory(data: DeleteCategoryInput): Promise<boolean
const deleteAllChannels = await prisma.channel.deleteMany({ const deleteAllChannels = await prisma.channel.deleteMany({
where: { where: {
categoryId: data.id categoryId: data.id,
} },
}); });
if (deleteAllChannels.count === 0) { if (deleteAllChannels.count === 0) {
@@ -204,8 +203,8 @@ export async function deleteCategory(data: DeleteCategoryInput): Promise<boolean
const deletedCategory = await prisma.category.delete({ const deletedCategory = await prisma.category.delete({
where: { where: {
id: data.id id: data.id,
} },
}); });
if (!deletedCategory) { if (!deletedCategory) {
@@ -219,14 +218,15 @@ export async function deleteCategory(data: DeleteCategoryInput): Promise<boolean
} }
} }
export async function deleteAllCategoriesFromInstance(data: DeleteCategoriesByInstanceIdInput): Promise<boolean | null>{ export async function deleteAllCategoriesFromInstance(
data: DeleteCategoriesByInstanceIdInput,
): Promise<boolean | null> {
try { try {
//Confirm if user exists and is admin //Confirm if user exists and is admin
const requestingUser = await getUserInformation(data.requestingUserId); const requestingUser = await getUserInformation(data.requestingUserId);
const requestingUserCredentials = await getUserCredentials( const requestingUserCredentials = await getUserCredentials(
data.requestingUserId, data.requestingUserId,
) );
if ( if (
!requestingUser || !requestingUser ||
@@ -240,8 +240,8 @@ export async function deleteAllCategoriesFromInstance(data: DeleteCategoriesByIn
const deletedCategories = await prisma.category.deleteMany({ const deletedCategories = await prisma.category.deleteMany({
where: { where: {
instanceId: data.instanceId instanceId: data.instanceId,
} },
}); });
if (deletedCategories.count === 0) { if (deletedCategories.count === 0) {
@@ -250,19 +250,23 @@ export async function deleteAllCategoriesFromInstance(data: DeleteCategoriesByIn
return true; return true;
} catch (err) { } catch (err) {
console.log("services::channelService::deleteAllCategoriesFromInstance - ", err); console.log(
"services::channelService::deleteAllCategoriesFromInstance - ",
err,
);
return false; return false;
} }
} }
export async function createChannel(data: CreateChannelInput): Promise<Channel | null>{ export async function createChannel(
data: CreateChannelInput,
): Promise<Channel | null> {
try { try {
//Confirm if user exists and is admin //Confirm if user exists and is admin
const requestingUser = await getUserInformation(data.requestingUserId); const requestingUser = await getUserInformation(data.requestingUserId);
const requestingUserCredentials = await getUserCredentials( const requestingUserCredentials = await getUserCredentials(
data.requestingUserId, data.requestingUserId,
) );
if ( if (
!requestingUser || !requestingUser ||
@@ -279,8 +283,8 @@ export async function createChannel(data: CreateChannelInput): Promise<Channel |
type: data.type, type: data.type,
name: data.name, name: data.name,
description: data.description, description: data.description,
categoryId: data.categoryId ? data.categoryId : null categoryId: data.categoryId ? data.categoryId : null,
} },
}); });
if (!newChannel) { if (!newChannel) {
@@ -294,14 +298,12 @@ export async function createChannel(data: CreateChannelInput): Promise<Channel |
} }
} }
export async function getChannel( export async function getChannel(channelId: string): Promise<Channel | null> {
channelId: string
): Promise<Channel | null>{
try { try {
const channel = await prisma.channel.findUnique({ const channel = await prisma.channel.findUnique({
where: { where: {
id: channelId id: channelId,
} },
}); });
if (!channel) { if (!channel) {
@@ -316,34 +318,34 @@ export async function getChannel(
} }
export async function getChannelsByCategory( export async function getChannelsByCategory(
categoryId: string categoryId: string,
): Promise<Channel[] | null> { ): Promise<Channel[] | null> {
try { try {
const channels = await prisma.channel.findMany({ const channels = await prisma.channel.findMany({
where: { where: {
categoryId: categoryId categoryId: categoryId,
} },
}); });
if (!channels) { if (!channels) {
throw new Error("could not find channels for category"); throw new Error("could not find channels for category");
} }
return channels; return channels;
} } catch (err) {
catch(err){
console.log("services::channelService::getChannelsByCategory - ", err); console.log("services::channelService::getChannelsByCategory - ", err);
return null; return null;
} }
} }
export async function updateChannel(data: UpdateChannelInput): Promise<Channel | null>{ export async function updateChannel(
data: UpdateChannelInput,
): Promise<Channel | null> {
try { try {
//Confirm if user exists and is admin //Confirm if user exists and is admin
const requestingUser = await getUserInformation(data.requestingUserId); const requestingUser = await getUserInformation(data.requestingUserId);
const requestingUserCredentials = await getUserCredentials( const requestingUserCredentials = await getUserCredentials(
data.requestingUserId, data.requestingUserId,
) );
if ( if (
!requestingUser || !requestingUser ||
@@ -357,13 +359,13 @@ export async function updateChannel(data: UpdateChannelInput): Promise<Channel |
const updatedChannel = await prisma.channel.update({ const updatedChannel = await prisma.channel.update({
where: { where: {
id: data.id id: data.id,
}, },
data: { data: {
name: data.name, name: data.name,
description: data.description, description: data.description,
categoryId: data.categoryId ? data.categoryId : undefined categoryId: data.categoryId ? data.categoryId : undefined,
} },
}); });
if (!updatedChannel) { if (!updatedChannel) {
@@ -377,14 +379,15 @@ export async function updateChannel(data: UpdateChannelInput): Promise<Channel |
} }
} }
export async function deleteChannel(data: DeleteChannelInput): Promise<boolean | null>{ export async function deleteChannel(
data: DeleteChannelInput,
): Promise<boolean | null> {
try { try {
//Confirm if user exists and is admin //Confirm if user exists and is admin
const requestingUser = await getUserInformation(data.requestingUserId); const requestingUser = await getUserInformation(data.requestingUserId);
const requestingUserCredentials = await getUserCredentials( const requestingUserCredentials = await getUserCredentials(
data.requestingUserId, data.requestingUserId,
) );
if ( if (
!requestingUser || !requestingUser ||
@@ -398,8 +401,8 @@ export async function deleteChannel(data: DeleteChannelInput): Promise<boolean |
const deletedChannel = await prisma.channel.delete({ const deletedChannel = await prisma.channel.delete({
where: { where: {
id: data.id id: data.id,
} },
}); });
if (!deletedChannel) { if (!deletedChannel) {
@@ -413,14 +416,15 @@ export async function deleteChannel(data: DeleteChannelInput): Promise<boolean |
} }
} }
export async function deleteAllChannelsFromCategory(data: DeleteChannelsByCategoryIdInput): Promise<boolean | null> export async function deleteAllChannelsFromCategory(
{ data: DeleteChannelsByCategoryIdInput,
): Promise<boolean | null> {
try { try {
//Confirm if user exists and is admin //Confirm if user exists and is admin
const requestingUser = await getUserInformation(data.requestingUserId); const requestingUser = await getUserInformation(data.requestingUserId);
const requestingUserCredentials = await getUserCredentials( const requestingUserCredentials = await getUserCredentials(
data.requestingUserId, data.requestingUserId,
) );
if ( if (
!requestingUser || !requestingUser ||
@@ -434,8 +438,8 @@ export async function deleteAllChannelsFromCategory(data: DeleteChannelsByCatego
const deletedChannels = await prisma.channel.deleteMany({ const deletedChannels = await prisma.channel.deleteMany({
where: { where: {
categoryId: data.categoryId categoryId: data.categoryId,
} },
}); });
if (deletedChannels.count === 0) { if (deletedChannels.count === 0) {
@@ -444,7 +448,10 @@ export async function deleteAllChannelsFromCategory(data: DeleteChannelsByCatego
return true; return true;
} catch (err) { } catch (err) {
console.log("services::channelService::deleteAllChannelsFromCategory - ", err); console.log(
"services::channelService::deleteAllChannelsFromCategory - ",
err,
);
return false; return false;
} }
} }

View File

@@ -8,29 +8,31 @@ export async function createInstance(data: CreateInstanceRequest) {
try { try {
const creds = await getUserCredentials(data.requestingUserId); const creds = await getUserCredentials(data.requestingUserId);
const user = await getUserInformation(data.requestingUserId); const user = await getUserInformation(data.requestingUserId);
if (!creds if (
|| creds.token != data.requestingUserToken !creds ||
|| !user creds.token != data.requestingUserToken ||
|| !user.admin) { !user ||
!user.admin
) {
return null; return null;
} }
const newInstance = await prisma.instance.create({ const newInstance = await prisma.instance.create({
data: { data: {
name: data.name, name: data.name,
icon: data.icon icon: data.icon,
} },
}); });
return { return {
success: true, success: true,
data: newInstance data: newInstance,
}; };
} catch (error) { } catch (error) {
console.error("Error creating instance:", error); console.error("Error creating instance:", error);
return { return {
success: false, success: false,
error: "Failed to create instance" error: "Failed to create instance",
}; };
} }
} }
@@ -39,19 +41,19 @@ export async function getAllInstances() {
try { try {
const instances = await prisma.instance.findMany({ const instances = await prisma.instance.findMany({
orderBy: { orderBy: {
createdAt: 'desc' createdAt: "desc",
} },
}); });
return { return {
success: true, success: true,
data: instances data: instances,
}; };
} catch (error) { } catch (error) {
console.error("Error fetching instances:", error); console.error("Error fetching instances:", error);
return { return {
success: false, success: false,
error: "Failed to fetch instances" error: "Failed to fetch instances",
}; };
} }
} }

View File

@@ -1,16 +1,14 @@
import { import { PrismaClient } from "@prisma/client";
PrismaClient,
} from "@prisma/client";
import { getUserCredentials } from "./userService"; import { getUserCredentials } from "./userService";
const prisma = new PrismaClient(); const prisma = new PrismaClient();
export async function getMessageInformation(id: string): Promise<{ export async function getMessageInformation(id: string): Promise<{
id: string, id: string;
channelId: string, channelId: string;
userId: string, userId: string;
text: string, text: string;
deleted: boolean, deleted: boolean;
replies: null | { replies: null | {
messageId: string; messageId: string;
repliesToId: string; repliesToId: string;
@@ -66,20 +64,22 @@ export async function getMessageInformation(id:string): Promise<{
const errMessage = err as Error; const errMessage = err as Error;
if (errMessage.message === "missing messageId") { if (errMessage.message === "missing messageId") {
console.log("services::actions::getMessageInformation - missing messageId"); console.log(
"services::actions::getMessageInformation - missing messageId",
);
return null; return null;
} }
if (errMessage.message === "could not find message") { if (errMessage.message === "could not find message") {
console.log( console.log(
"services::actions::getMessageInformation - unable to find message" "services::actions::getMessageInformation - unable to find message",
); );
return null; return null;
} }
console.log( console.log(
"services::actions::getMessageInformation - unknown error", "services::actions::getMessageInformation - unknown error",
errMessage errMessage,
); );
return null; return null;
} }
@@ -141,13 +141,15 @@ export async function getMessagesBefore(date:string, channelId:string) {
const errMessage = err as Error; const errMessage = err as Error;
if (errMessage.message === "missing date or channelId") { if (errMessage.message === "missing date or channelId") {
console.log("services::actions::getMessagesBefore - missing date or channelId"); console.log(
"services::actions::getMessagesBefore - missing date or channelId",
);
return null; return null;
} }
console.log( console.log(
"services::actions::getMessagesBefore - unknown error", "services::actions::getMessagesBefore - unknown error",
errMessage errMessage,
); );
return null; return null;
} }

View File

@@ -1,4 +1,3 @@
import { import {
Message, Message,
MessagePing, MessagePing,

View File

@@ -1,4 +1,4 @@
import { z } from 'zod'; import { z } from "zod";
//category validators //category validators
@@ -8,48 +8,54 @@ export const createCategorySchema = z.object({
instanceId: z.uuidv7().optional(), instanceId: z.uuidv7().optional(),
admin: z.boolean(), admin: z.boolean(),
requestingUserId: z.uuidv7(), requestingUserId: z.uuidv7(),
requestingUserToken: z.uuidv4() requestingUserToken: z.uuidv4(),
}) });
export const getCategorySchema = z.object({ export const getCategorySchema = z.object({
id: z.uuidv7() id: z.uuidv7(),
}) });
export const getCategoriesByInstanceIdSchema = z.object({ export const getCategoriesByInstanceIdSchema = z.object({
instanceId: z.uuidv7() instanceId: z.uuidv7(),
});
})
export const updateCategorySchema = z.object({ export const updateCategorySchema = z.object({
id: z.uuidv7(), id: z.uuidv7(),
name: z.string().min(1).max(50).optional(), name: z.string().min(1).max(50).optional(),
position: z.number().min(0).optional(), position: z.number().min(0).optional(),
channels: z.array(z.object({ channels: z
id: z.string() .array(
})).optional(), z.object({
id: z.string(),
}),
)
.optional(),
admin: z.boolean(), admin: z.boolean(),
requestingUserId: z.uuidv7(), requestingUserId: z.uuidv7(),
requestingUserToken: z.uuidv4() requestingUserToken: z.uuidv4(),
}) });
export const deleteCategorySchema = z.object({ export const deleteCategorySchema = z.object({
id: z.uuidv7(), id: z.uuidv7(),
admin: z.boolean(), admin: z.boolean(),
requestingUserId: z.uuidv7(), requestingUserId: z.uuidv7(),
requestingUserToken: z.uuidv4() requestingUserToken: z.uuidv4(),
}) });
export const deleteCategoriesByInstanceIdSchema = z.object({ export const deleteCategoriesByInstanceIdSchema = z.object({
instanceId: z.uuidv7(), instanceId: z.uuidv7(),
admin: z.boolean(), admin: z.boolean(),
requestingUserId: z.uuidv7(), requestingUserId: z.uuidv7(),
requestingUserToken: z.uuidv4() requestingUserToken: z.uuidv4(),
}) });
export type CreateCategoryInput = z.infer<typeof createCategorySchema>;
export type CreateCategoryInput = z.infer<typeof createCategorySchema> export type GetCategoryInput = z.infer<typeof getCategorySchema>;
export type GetCategoryInput = z.infer<typeof getCategorySchema> export type GetCategoriesByInstanceIdInput = z.infer<
export type GetCategoriesByInstanceIdInput = z.infer<typeof getCategoriesByInstanceIdSchema> typeof getCategoriesByInstanceIdSchema
export type UpdateCategoryInput = z.infer<typeof updateCategorySchema> >;
export type DeleteCategoryInput = z.infer<typeof deleteCategorySchema> export type UpdateCategoryInput = z.infer<typeof updateCategorySchema>;
export type DeleteCategoriesByInstanceIdInput = z.infer<typeof deleteCategoriesByInstanceIdSchema> export type DeleteCategoryInput = z.infer<typeof deleteCategorySchema>;
export type DeleteCategoriesByInstanceIdInput = z.infer<
typeof deleteCategoriesByInstanceIdSchema
>;

View File

@@ -3,22 +3,22 @@ import { z } from "zod";
//channel validators //channel validators
export const createChannelSchema = z.object({ export const createChannelSchema = z.object({
type: z.enum(['text', 'voice']), type: z.enum(["text", "voice"]),
name: z.string().min(1).max(50), name: z.string().min(1).max(50),
description: z.string().max(255), description: z.string().max(255),
categoryId: z.uuidv7().optional(), categoryId: z.uuidv7().optional(),
admin: z.boolean(), admin: z.boolean(),
requestingUserId: z.uuidv7(), requestingUserId: z.uuidv7(),
requestingUserToken: z.uuidv4() requestingUserToken: z.uuidv4(),
}) });
export const getChannelSchema = z.object({ export const getChannelSchema = z.object({
id: z.uuidv7() id: z.uuidv7(),
}) });
export const getChannelsByCategoryIdSchema = z.object({ export const getChannelsByCategoryIdSchema = z.object({
categoryId: z.uuidv7() categoryId: z.uuidv7(),
}) });
export const updateChannelSchema = z.object({ export const updateChannelSchema = z.object({
id: z.uuidv7(), id: z.uuidv7(),
@@ -27,26 +27,30 @@ export const updateChannelSchema = z.object({
categoryId: z.uuidv7().optional(), categoryId: z.uuidv7().optional(),
admin: z.boolean(), admin: z.boolean(),
requestingUserId: z.uuidv7(), requestingUserId: z.uuidv7(),
requestingUserToken: z.uuidv4() requestingUserToken: z.uuidv4(),
}) });
export const deleteChannelSchema = z.object({ export const deleteChannelSchema = z.object({
id: z.uuidv7(), id: z.uuidv7(),
admin: z.boolean(), admin: z.boolean(),
requestingUserId: z.uuidv7(), requestingUserId: z.uuidv7(),
requestingUserToken: z.uuidv4() requestingUserToken: z.uuidv4(),
}) });
export const deleteChannelsByCategoryIdSchema = z.object({ export const deleteChannelsByCategoryIdSchema = z.object({
categoryId: z.uuidv7(), categoryId: z.uuidv7(),
admin: z.boolean(), admin: z.boolean(),
requestingUserId: z.uuidv7(), requestingUserId: z.uuidv7(),
requestingUserToken: z.uuidv4() requestingUserToken: z.uuidv4(),
}) });
export type CreateChannelInput = z.infer<typeof createChannelSchema> export type CreateChannelInput = z.infer<typeof createChannelSchema>;
export type GetChannelInput = z.infer<typeof getChannelSchema> export type GetChannelInput = z.infer<typeof getChannelSchema>;
export type GetChannelsByCategoryIdInput = z.infer<typeof getChannelsByCategoryIdSchema> export type GetChannelsByCategoryIdInput = z.infer<
export type UpdateChannelInput = z.infer<typeof updateChannelSchema> typeof getChannelsByCategoryIdSchema
export type DeleteChannelInput = z.infer<typeof deleteChannelSchema> >;
export type DeleteChannelsByCategoryIdInput = z.infer<typeof deleteChannelsByCategoryIdSchema> export type UpdateChannelInput = z.infer<typeof updateChannelSchema>;
export type DeleteChannelInput = z.infer<typeof deleteChannelSchema>;
export type DeleteChannelsByCategoryIdInput = z.infer<
typeof deleteChannelsByCategoryIdSchema
>;

View File

@@ -1,29 +1,33 @@
import { z } from 'zod'; import { z } from "zod";
export const createInstanceRequestSchema = z.object({ export const createInstanceRequestSchema = z.object({
name: z.string().min(1, 'Instance name cannot be empty'), name: z.string().min(1, "Instance name cannot be empty"),
icon: z.url().optional(), icon: z.url().optional(),
requestingUserId: z.uuidv7(), requestingUserId: z.uuidv7(),
requestingUserToken: z.string() requestingUserToken: z.string(),
}); });
export const getAllInstancesResponseSchema = z.object({ export const getAllInstancesResponseSchema = z.object({
success: z.boolean(), success: z.boolean(),
data: z.array( data: z
.array(
z.object({ z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string(),
icon: z.string().nullable(), icon: z.string().nullable(),
createdAt: z.string().refine((val) => !isNaN(Date.parse(val)), { createdAt: z.string().refine((val) => !isNaN(Date.parse(val)), {
message: "Invalid date string format" message: "Invalid date string format",
}), }),
updatedAt: z.string().refine((val) => !isNaN(Date.parse(val)), { updatedAt: z.string().refine((val) => !isNaN(Date.parse(val)), {
message: "Invalid date string format" message: "Invalid date string format",
}) }),
}) }),
).optional(), )
error: z.string().optional() .optional(),
error: z.string().optional(),
}); });
export type CreateInstanceRequest = z.infer<typeof createInstanceRequestSchema>; export type CreateInstanceRequest = z.infer<typeof createInstanceRequestSchema>;
export type GetAllInstancesResponse = z.infer<typeof getAllInstancesResponseSchema>; export type GetAllInstancesResponse = z.infer<
typeof getAllInstancesResponseSchema
>;

View File

@@ -1,20 +1,20 @@
import { z } from "zod"; import { z } from "zod";
export const getMessageByIdSchema = z.object({ export const getMessageByIdSchema = z.object({
id: z.uuidv7() id: z.uuidv7(),
}) });
export const getMessagesBeforeDate = z.object({ export const getMessagesBeforeDate = z.object({
date: z.string().refine((val) => !isNaN(Date.parse(val)), { date: z.string().refine((val) => !isNaN(Date.parse(val)), {
message: "Invalid date string format" message: "Invalid date string format",
}), }),
channelId: z.uuidv7() channelId: z.uuidv7(),
}) });
export const sendMessageSchema = z.object({ export const sendMessageSchema = z.object({
channelId: z.uuidv7(), channelId: z.uuidv7(),
userId: z.uuidv7(), userId: z.uuidv7(),
content: z.string(), content: z.string(),
token: z.string(), token: z.string(),
repliedMessageId: z.uuidv7().nullable().optional() repliedMessageId: z.uuidv7().nullable().optional(),
}) });

View File

@@ -7,7 +7,7 @@ export const queryUserByIdSchema = z.object({
export const queryAllUsersByInstanceId = z.object({ export const queryAllUsersByInstanceId = z.object({
instanceId: z.uuidv7(), instanceId: z.uuidv7(),
}); });
import { is } from 'zod/v4/locales'; import { is } from "zod/v4/locales";
export const createUserSchema = z.object({ export const createUserSchema = z.object({
username: z.string().min(3).max(30), username: z.string().min(3).max(30),
nickname: z.string().min(1).max(30).optional(), nickname: z.string().min(1).max(30).optional(),