import { query } from "./database"; import { dispatch } from "./gateway"; import { GatewayPayloadType } from "./gateway/gatewaypayloadtype"; export default async function sendMessage(user: User, channelId: number, optimisticId: number | null, content: string, nickUsername: string | null) { const authorId = user.id; const createdAt = Date.now().toString(); 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]); 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, created_at: createdAt, nick_username: nickUsername }; 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; }