|
| 1 | +import { action } from '@/sdk'; |
| 2 | +import { z } from 'zod'; |
| 3 | +import client from '../../client'; |
| 4 | + |
| 5 | +import { transformAssociation } from '@/platforms/hubspot/actions/mappers'; |
| 6 | +import { HUBSPOT_DEFINED_CATEGORY } from '../../constants'; |
| 7 | +import { hubspotModuleSchema } from '../../schemas'; |
| 8 | + |
| 9 | +export default action( |
| 10 | + 'associations-create', |
| 11 | + { |
| 12 | + operation: 'create', |
| 13 | + resource: 'associations', |
| 14 | + mutation: true, |
| 15 | + schema: z.object({ |
| 16 | + fromId: z.string(), |
| 17 | + fromType: hubspotModuleSchema, |
| 18 | + toId: z.string(), |
| 19 | + toType: hubspotModuleSchema, |
| 20 | + category: z.string().optional(), |
| 21 | + typeId: z.string().optional(), |
| 22 | + }), |
| 23 | + scopes: [ |
| 24 | + 'crm.schemas.companies.write', |
| 25 | + 'crm.schemas.contacts.write', |
| 26 | + 'crm.schemas.deals.write', |
| 27 | + ], |
| 28 | + }, |
| 29 | + async ({ auth, input }) => { |
| 30 | + const { category, typeId } = await (async () => { |
| 31 | + if (input.category && input.typeId) return input; |
| 32 | + const labelsResponse = await client.associations.labels(auth, { |
| 33 | + fromType: input.fromType, |
| 34 | + toType: input.toType, |
| 35 | + }); |
| 36 | + const associationTypeId = labelsResponse.data.results?.find( |
| 37 | + (id) => id.category === HUBSPOT_DEFINED_CATEGORY, |
| 38 | + )?.typeId; |
| 39 | + return { |
| 40 | + category: HUBSPOT_DEFINED_CATEGORY, |
| 41 | + typeId: associationTypeId, |
| 42 | + }; |
| 43 | + })(); |
| 44 | + const result = await client.associations.create(auth, { |
| 45 | + fromId: input.fromId, |
| 46 | + fromType: input.fromType, |
| 47 | + toId: input.toId, |
| 48 | + toType: input.toType, |
| 49 | + category, |
| 50 | + typeId, |
| 51 | + }); |
| 52 | + |
| 53 | + return { |
| 54 | + results: result.data.results?.map(transformAssociation), |
| 55 | + $native: result.$native, |
| 56 | + }; |
| 57 | + }, |
| 58 | +); |
0 commit comments