2022-10-09 22:46:31 +03:00
|
|
|
import { query } from "./database";
|
|
|
|
import { dispatch } from "./gateway";
|
|
|
|
import { GatewayPayloadType } from "./gateway/gatewaypayloadtype";
|
|
|
|
|
2022-10-30 16:53:52 +02:00
|
|
|
export default async function sendMessage(user: User, channelId: number, optimisticId: number | null, content: string, nickUsername: string | null) {
|
2022-10-09 22:46:31 +03:00
|
|
|
const authorId = user.id;
|
|
|
|
const createdAt = Date.now().toString();
|
|
|
|
|
2022-10-30 16:53:52 +02:00
|
|
|
const result = await query("INSERT INTO messages(content, channel_id, author_id, created_at, nick_username) VALUES ($1, $2, $3, $4, $5) RETURNING id", [content, channelId, authorId, createdAt, nickUsername]);
|
2022-10-09 22:46:31 +03:00
|
|
|
if (!result || result.rowCount < 1) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
let returnObject: any = {
|
|
|
|
id: result.rows[0].id,
|
|
|
|
content,
|
|
|
|
channel_id: channelId,
|
|
|
|
author_id: authorId,
|
|
|
|
author_username: user.username,
|
2023-02-25 02:35:12 +02:00
|
|
|
author_avatar: user.avatar,
|
2022-10-30 16:53:52 +02:00
|
|
|
created_at: createdAt,
|
|
|
|
nick_username: nickUsername
|
2022-10-09 22:46:31 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
dispatch(`channel:${channelId}`, (ws) => {
|
|
|
|
let payload: any = returnObject;
|
|
|
|
if (ws && ws.state && ws.state.user && ws.state.user.id === user.id && optimisticId) {
|
|
|
|
payload = {
|
|
|
|
...payload,
|
|
|
|
optimistic_id: optimisticId
|
|
|
|
}
|
|
|
|
returnObject = {
|
|
|
|
...returnObject,
|
|
|
|
optimistic_id: optimisticId
|
|
|
|
};
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
t: GatewayPayloadType.MessageCreate,
|
|
|
|
d: payload
|
|
|
|
};
|
|
|
|
});
|
|
|
|
|
|
|
|
return returnObject;
|
|
|
|
}
|