|
| 1 | +import { QueryExecutor } from '../queryExecutor' |
| 2 | + |
| 3 | +export interface IMailingListToOnboard { |
| 4 | + name: string |
| 5 | + sourceUrl: string |
| 6 | +} |
| 7 | + |
| 8 | +/** |
| 9 | + * Upsert mailing lists (public-inbox/lore) for a segment/integration and |
| 10 | + * seed their processing state so the mailing_list_integration worker picks |
| 11 | + * them up. Re-running with the same sourceUrl re-points the list at the |
| 12 | + * given segment/integration without resetting its processing progress. |
| 13 | + * @param qx - Query executor (should be transactional) |
| 14 | + * @param segmentId - Segment the lists belong to |
| 15 | + * @param integrationId - Integration these lists are onboarded under |
| 16 | + * @param lists - Mailing lists to onboard, keyed by sourceUrl |
| 17 | + */ |
| 18 | +export async function upsertMailingLists( |
| 19 | + qx: QueryExecutor, |
| 20 | + segmentId: string, |
| 21 | + integrationId: string, |
| 22 | + lists: IMailingListToOnboard[], |
| 23 | +): Promise<string[]> { |
| 24 | + if (lists.length === 0) { |
| 25 | + return [] |
| 26 | + } |
| 27 | + |
| 28 | + const rows = await qx.select( |
| 29 | + ` |
| 30 | + WITH upserted_list AS ( |
| 31 | + INSERT INTO mailinglist.lists (id, name, "sourceUrl", "segmentId", "integrationId", "createdAt", "updatedAt") |
| 32 | + SELECT uuid_generate_v4(), v.name, v."sourceUrl", $(segmentId)::uuid, $(integrationId)::uuid, NOW(), NOW() |
| 33 | + FROM json_to_recordset($(lists)::json) AS v(name text, "sourceUrl" text) |
| 34 | + ON CONFLICT ("sourceUrl") DO UPDATE SET |
| 35 | + name = EXCLUDED.name, |
| 36 | + "segmentId" = EXCLUDED."segmentId", |
| 37 | + "integrationId" = EXCLUDED."integrationId", |
| 38 | + "updatedAt" = NOW() |
| 39 | + RETURNING id |
| 40 | + ), |
| 41 | + seed_processing AS ( |
| 42 | + INSERT INTO mailinglist."listProcessing" ("listId", state, priority, "lastProcessedHeads", "createdAt", "updatedAt") |
| 43 | + SELECT id, 'pending', 2, '{}'::jsonb, NOW(), NOW() |
| 44 | + FROM upserted_list |
| 45 | + ON CONFLICT ("listId") DO NOTHING |
| 46 | + ) |
| 47 | + SELECT id FROM upserted_list |
| 48 | + `, |
| 49 | + { |
| 50 | + segmentId, |
| 51 | + integrationId, |
| 52 | + lists: JSON.stringify(lists), |
| 53 | + }, |
| 54 | + ) |
| 55 | + |
| 56 | + return rows.map((row: { id: string }) => row.id) |
| 57 | +} |
0 commit comments