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) { const authorId = user.id; const createdAt = Date.now().toString(); const result = await query("INSERT INTO messages(content, channel_id, author_id, created_at) VALUES ($1, $2, $3, $4) RETURNING id", [content, channelId, authorId, createdAt]); 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 }; 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; }