import { query } from "./database"; import { dispatch } from "./gateway"; import { GatewayPayloadType } from "./gateway/gatewaypayloadtype"; import { RPCContext } from "./rpc/rpc"; export default async function sendMessage(user: User, channelId: number, optimisticId: number | null, content: string, nickUsername: string | null, pendingAttachments: number, ctx: RPCContext) { 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, pending_attachments) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id", [content, channelId, authorId, createdAt, nickUsername, pendingAttachments]); 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, author_avatar: user.avatar, created_at: createdAt, nick_username: nickUsername, pending_attachments: pendingAttachments, attachments: null }; ctx.gatewayDispatch(`channel:${channelId}`, (ws) => { let payload: any = returnObject; if (ws && ws.user && ws.user.id === user.id && optimisticId) { payload = { ...payload, optimistic_id: optimisticId } returnObject = { ...returnObject, optimistic_id: optimisticId }; } return { t: GatewayPayloadType.MessageCreate, d: payload }; }); return returnObject; }