Files
akmon/server/gateway-mqtt-node/scripts/simulate_chat_downlink.js
2026-01-20 08:04:15 +08:00

44 lines
1.8 KiB
JavaScript

import 'dotenv/config'
import { createClient } from '@supabase/supabase-js'
import { v4 as uuidv4 } from 'uuid'
async function main() {
const SUPABASE_URL = process.env.SUPABASE_URL
const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!SUPABASE_URL || !SUPABASE_SERVICE_ROLE_KEY) throw new Error('Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY')
const conversationId = process.env.SIM_CHAT_CONVERSATION_ID
if (!conversationId) throw new Error('SIM_CHAT_CONVERSATION_ID required')
const targetUserId = process.env.SIM_TARGET_USER_ID || ''
const topic = process.env.SIM_TOPIC || (targetUserId ? `device/${targetUserId}/down` : '')
if (!topic) throw new Error('Provide SIM_TOPIC or SIM_TARGET_USER_ID to derive topic')
const correlationId = process.env.SIM_CORRELATION_ID || uuidv4()
const payloadObj = process.env.SIM_PAYLOAD
? JSON.parse(process.env.SIM_PAYLOAD)
: { type: 'ping', t: Date.now(), correlation_id: correlationId }
const payload = typeof payloadObj === 'string' ? payloadObj : JSON.stringify(payloadObj)
const qos = parseInt(process.env.SIM_QOS || '1', 10)
const retain = /^true$/i.test(process.env.SIM_RETAIN || 'false')
const supa = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, { auth: { autoRefreshToken: false, persistSession: false } })
const row = {
conversation_id: conversationId,
target_user_id: targetUserId || null,
topic,
payload,
payload_encoding: 'utf8',
qos,
retain,
status: 'pending',
scheduled_at: new Date().toISOString(),
correlation_id: correlationId
}
const { data, error } = await supa.from('chat_mqtt_downlinks').insert(row).select('*').single()
if (error) throw error
console.log('Inserted chat downlink:', { id: data.id, correlation_id: correlationId, topic })
}
main().catch((e) => { console.error(e); process.exit(1) })