Skip to content

Commit

Permalink
Checks for existence of user selected audience. Saves audience name a…
Browse files Browse the repository at this point in the history
…nd ID when returning from hook
  • Loading branch information
nick-Ag committed Jul 18, 2024
1 parent a2a642c commit fc4f5ed
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ interface GetAllAudienceResponse {
name: string
}[]
}

interface GetSingleAudienceResponse {
name: string
id: string
}

interface FacebookResponseError {
error: {
message: string
type: string
code: number
}
}

export default class FacebookClient {
request: RequestClient
baseUrl: string
Expand All @@ -35,8 +49,16 @@ export default class FacebookClient {
})
}

getSingleAudience = async (audienceId: string): void | Error => {
return this.request(`${this.baseUrl}${audienceId}`)
getSingleAudience = async (
audienceId: string
): Promise<{ data?: GetSingleAudienceResponse; error?: FacebookResponseError }> => {
try {
const fields = '?fields=id,name'
const { data } = await this.request<GetSingleAudienceResponse>(`${this.baseUrl}${audienceId}${fields}`)
return { data, error: undefined }
} catch (error) {
return { data: undefined, error: error as FacebookResponseError }
}
}

getAllAudiences = async (): Promise<{ choices: DynamicFieldItem[]; error: DynamicFieldError | undefined }> => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ const action: ActionDefinition<Settings, Payload> = {
}
},
outputTypes: {
audienceName: {
type: 'string',
label: 'Audience Name',
description: 'The name of the audience in Facebook this mapping is connected to.',
required: true
},
audienceId: {
type: 'string',
label: 'Audience ID',
Expand All @@ -48,18 +54,22 @@ const action: ActionDefinition<Settings, Payload> = {
const fbClient = new FacebookClient(request, settings.adAccountId)

if (hookInputs.existingAudienceId) {
const error = fbClient.getSingleAudience(hookInputs.existingAudienceId)
const { data, error } = await fbClient.getSingleAudience(hookInputs.existingAudienceId)

if (error) {
return {
error
error: {
message: error.error.message,
code: error.error.type
}
}
}

return {
successMessage: `Audience selected with ID: ${hookInputs.existingAudienceId}`,
successMessage: `Connected to audience with ID: ${hookInputs.existingAudienceId}`,
savedData: {
audienceId: hookInputs.existingAudienceId
audienceId: hookInputs.existingAudienceId,
audienceName: data?.name
}
}
}
Expand All @@ -68,7 +78,8 @@ const action: ActionDefinition<Settings, Payload> = {
return {
successMessage: `Audience created with ID: ${data.id}`,
savedData: {
audienceId: data.id
audienceId: data.id,
audienceName: hookInputs.audienceName
}
}
}
Expand Down

0 comments on commit fc4f5ed

Please sign in to comment.