| 5 | import { TABLE_NAMES, ch, formatClickhouseDate } from '@openpanel/db'; |
| 6 | |
| 7 | export async function importEvents( |
| 8 | request: FastifyRequest<{ |
| 9 | Body: IClickhouseEvent[]; |
| 10 | }>, |
| 11 | reply: FastifyReply, |
| 12 | ) { |
| 13 | const projectId = request.client?.projectId; |
| 14 | if (!projectId) { |
| 15 | throw new Error('Project ID is required'); |
| 16 | } |
| 17 | |
| 18 | const importedAt = formatClickhouseDate(new Date()); |
| 19 | const values: IClickhouseEvent[] = request.body.map((event) => { |
| 20 | return { |
| 21 | ...event, |
| 22 | properties: toDots(event.properties), |
| 23 | project_id: projectId, |
| 24 | created_at: formatClickhouseDate(event.created_at), |
| 25 | imported_at: importedAt, |
| 26 | }; |
| 27 | }); |
| 28 | |
| 29 | try { |
| 30 | const res = await ch.insert({ |
| 31 | table: TABLE_NAMES.events, |
| 32 | values, |
| 33 | format: 'JSONEachRow', |
| 34 | }); |
| 35 | |
| 36 | console.log(res.summary?.written_rows, 'events imported'); |
| 37 | reply.send('OK'); |
| 38 | } catch (e) { |
| 39 | console.error(e); |
| 40 | reply.status(500).send('Error'); |
| 41 | } |
| 42 | } |