Skip to content

Commit

Permalink
Adds a dynamic audience field, pulls down all customaudiences as choices
Browse files Browse the repository at this point in the history
  • Loading branch information
nick-Ag committed Jul 16, 2024
1 parent 27e4903 commit 151d26c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RequestClient } from '@segment/actions-core'
import { DynamicFieldItem, DynamicFieldError, RequestClient } from '@segment/actions-core'

const FACEBOOK_API_VERSION = 'v20.0'

Expand All @@ -7,6 +7,19 @@ interface AudienceCreationResponse {
message: string
}

interface GetAllAudienceResponse {
data: {
id: string
name: string
}[]
paging: {
cursors: {
before: string
after: string
}
next: string
}
}
export default class FacebookClient {
request: RequestClient
baseUrl: string
Expand All @@ -15,7 +28,7 @@ export default class FacebookClient {
constructor(request: RequestClient, adAccountId: string) {
this.request = request
this.baseUrl = `https://graph.facebook.com/${FACEBOOK_API_VERSION}/`
this.adAccountId = adAccountId
this.adAccountId = this.formatAdAccount(adAccountId)
}

createAudience = async (name: string) => {
Expand All @@ -29,4 +42,25 @@ export default class FacebookClient {
}
})
}

getAllAudiences = async (): Promise<[DynamicFieldItem[], DynamicFieldError | undefined]> => {
const { data } = await this.request<GetAllAudienceResponse>(
`${this.baseUrl}${this.adAccountId}/customaudiences?fields=id,name`
)

// console.log('data.paging', data.paging)
const choices = data.data.map(({ id, name }) => ({
value: id,
label: name
}))

return [choices, undefined]
}

private formatAdAccount(adAccountId: string) {
if (adAccountId.startsWith('act_')) {
return adAccountId
}
return `act_${adAccountId}`
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,23 @@ const action: ActionDefinition<Settings, Payload> = {
label: 'Audience Name',
description: 'The name of the audience in Facebook.',
default: 'TODO: Model Name by default'
},
existingAudienceId: {
type: 'string',
label: 'Existing Audience ID',
description: 'The ID of the audience in Facebook.',
dynamic: async (request, { settings }) => {
const fbClient = new FacebookClient(request, settings.adAccountId)
const [choices, error] = await fbClient.getAllAudiences()

if (error) {
return { error, choices: [] }
}

return {
choices
}
}
}
},
outputTypes: {
Expand Down

0 comments on commit 151d26c

Please sign in to comment.