Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: refactor advertising.js to improve readability #104

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
192 changes: 100 additions & 92 deletions src/Advertising.js
PoChenKuo marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
const EXECUTE_PLUGINS_ACTION = {
SETUP: 'setup',
DISPLAYSLOTS: 'displaySlots',
DISPLAYOUTOFPAGESLOT: 'displayOutOfPageSlot',
REFRESHINTERSTITIALSLOT: 'refreshInterstitialSlot',
SETUPPREBID: 'setupPrebid',
TEARDOWNPREBID: 'teardownPrebid',
SETUPGPT: 'setupGpt',
TEARDOWNGPT: 'teardownGpt',
}

export default class Advertising {
constructor(config, plugins = [], onError = () => {}) {
constructor(config, plugins = [], onError = () => { }) {
this.config = config
this.slots = {}
this.outOfPageSlots = {}
Expand All @@ -21,26 +32,20 @@ export default class Advertising {
}
}


// ---------- PUBLIC METHODS ----------

async setup() {
this.isPrebidUsed =
typeof this.config.usePrebid === 'undefined' ? typeof window.pbjs !== 'undefined' : this.config.usePrebid
this.isAPSUsed =
typeof this.config.useAPS === 'undefined' ? typeof window.apstag !== 'undefined' : this.config.useAPS
this.executePlugins('setup')
this.executePlugins(EXECUTE_PLUGINS_ACTION.SETUP)
PoChenKuo marked this conversation as resolved.
Show resolved Hide resolved
const { slots, outOfPageSlots, queue, isPrebidUsed, isAPSUsed } = this
this.setupCustomEvents()
const setUpQueueItems = [Advertising.queueForGPT(this.setupGpt.bind(this), this.onError)]
if (isAPSUsed) {
try {
window.apstag.init({
...this.config.aps,
adServer: 'googletag',
})
} catch (error) {
this.onError(error)
}
this.initApstag()
}
if (isPrebidUsed) {
setUpQueueItems.push(Advertising.queueForPrebid(this.setupPrebid.bind(this), this.onError))
Expand All @@ -50,52 +55,15 @@ export default class Advertising {
if (queue.length === 0) {
return
}
for (let i = 0; i < queue.length; i++) {
const { id, customEventHandlers } = queue[i]
Object.keys(customEventHandlers).forEach((customEventId) => {
if (!this.customEventCallbacks[customEventId]) {
this.customEventCallbacks[customEventId] = {}
}
return (this.customEventCallbacks[customEventId][id] = customEventHandlers[customEventId])
})
}
const divIds = queue.filter(({ id }) => id)
const selectedSlots = queue.map(({ id }) => {
return slots[id].gpt || outOfPageSlots[id]
})
this.setCustomEventCallbackByQueue(queue)
const { divIds, selectedSlots } = this.getDivIdsAndSlots(queue, outOfPageSlots, slots)

if (isPrebidUsed) {
Advertising.queueForPrebid(
() =>
window.pbjs.requestBids({
adUnitCodes: divIds,
bidsBackHandler: () => {
window.pbjs.setTargetingForGPTAsync(divIds)
this.requestManager.prebid = true
this.refreshSlots(selectedSlots)
},
}),
this.onError
)
Advertising.queueForPrebid(this.getPbjFetchBidsCallback(divIds, selectedSlots), this.onError)
PoChenKuo marked this conversation as resolved.
Show resolved Hide resolved
}

if (this.isAPSUsed) {
try {
window.apstag.fetchBids(
{
slots: selectedSlots.map((slot) => slot.aps),
},
() => {
Advertising.queueForGPT(() => {
window.apstag.setDisplayBids()
this.requestManager.aps = true // signals that APS request has completed
this.refreshSlots(selectedSlots) // checks whether both APS and Prebid have returned
}, this.onError)
}
)
} catch (error) {
this.onError(error)
}
this.apstagFetchBids(selectedSlots, selectedSlots)
}

if (!isPrebidUsed && !isAPSUsed) {
Expand All @@ -122,44 +90,14 @@ export default class Advertising {
this.queue.push({ id, customEventHandlers })
return
}
Object.keys(customEventHandlers).forEach((customEventId) => {
if (!this.customEventCallbacks[customEventId]) {
this.customEventCallbacks[customEventId] = {}
}
return (this.customEventCallbacks[customEventId][id] = customEventHandlers[customEventId])
})
this.setCustomEventCallback(id, customEventHandlers)

if (isPrebidUsed) {
Advertising.queueForPrebid(
() =>
window.pbjs.requestBids({
adUnitCodes: [id],
bidsBackHandler: () => {
window.pbjs.setTargetingForGPTAsync([id])
this.requestManager.prebid = true
this.refreshSlots([slots[id].gpt])
},
}),
this.onError
)
Advertising.queueForPrebid(this.getPbjFetchBidsCallback([id], [slots[id].gpt]), this.onError)
}

if (this.isAPSUsed) {
try {
window.apstag.fetchBids(
{
slots: [slots[id].aps],
},
() => {
Advertising.queueForGPT(() => {
window.apstag.setDisplayBids()
this.requestManager.aps = true // signals that APS request has completed
this.refreshSlots([slots[id].gpt]) // checks whether both APS and Prebid have returned
}, this.onError)
}
)
} catch (error) {
this.onError(error)
}
this.apstagFetchBids([slots[id]], [slots[id].gpt]);
}

if (!this.isPrebidUsed && !this.isAPSUsed) {
Expand All @@ -177,6 +115,76 @@ export default class Advertising {
}

// ---------- PRIVATE METHODS ----------
apstagFetchBids(selectedSlots, checkedSlots) {
try {
window.apstag.fetchBids(
{
slots: selectedSlots.map((slot) => slot.aps),
},
() => {
Advertising.queueForGPT(() => {
window.apstag.setDisplayBids()
this.requestManager.aps = true // signals that APS request has completed
this.refreshSlots(checkedSlots) // checks whether both APS and Prebid have returned
}, this.onError)
}
)
} catch (error) {
this.onError(error)
}
}

getPbjFetchBidsCallback(divIds, selectedSlots) {
return () =>
window.pbjs.requestBids({
adUnitCodes: divIds,
bidsBackHandler: () => {
window.pbjs.setTargetingForGPTAsync(divIds)
this.requestManager.prebid = true
this.refreshSlots(selectedSlots)
},
})
}

getDivIdsAndSlots(queue, outOfPageSlots, slots) {
const divIds = []
const selectedSlots = []
queue.forEach((item) => {
const { id } = item;
if (id) {
divIds.push(item)
}
selectedSlots.push(slots[id]?.gpt || outOfPageSlots[id])
})
return { divIds, selectedSlots }
}

setCustomEventCallbackByQueue(queue) {
for (let i = 0; i < queue.length; i++) {
const { id, customEventHandlers } = queue[i]
this.setCustomEventCallback(id, customEventHandlers)
}
}

setCustomEventCallback(id, customEventHandlers) {
Object.keys(customEventHandlers).forEach((customEventId) => {
if (!this.customEventCallbacks[customEventId]) {
this.customEventCallbacks[customEventId] = {}
}
this.customEventCallbacks[customEventId][id] = customEventHandlers[customEventId]
})
}

initApstag() {
try {
window.apstag.init({
...this.config.aps,
adServer: 'googletag',
})
} catch (error) {
this.onError(error)
}
}

setupCustomEvents() {
if (!this.config.customEvents) {
Expand Down Expand Up @@ -303,14 +311,14 @@ export default class Advertising {
}

displaySlots() {
this.executePlugins('displaySlots')
this.executePlugins(EXECUTE_PLUGINS_ACTION.DISPLAYSLOTS)
this.config.slots.forEach(({ id }) => {
window.googletag.display(id)
})
}

displayOutOfPageSlots() {
this.executePlugins('displayOutOfPageSlot')
this.executePlugins(EXECUTE_PLUGINS_ACTION.DISPLAYOUTOFPAGESLOT)
if (this.config.outOfPageSlots) {
this.config.outOfPageSlots.forEach(({ id }) => {
window.googletag.display(id)
Expand All @@ -319,7 +327,7 @@ export default class Advertising {
}

refreshInterstitialSlot() {
this.executePlugins('refreshInterstitialSlot')
this.executePlugins(EXECUTE_PLUGINS_ACTION.REFRESHINTERSTITIALSLOT)
if (this.interstitialSlot) {
window.googletag.pubads().refresh([this.interstitialSlot])
}
Expand All @@ -340,19 +348,19 @@ export default class Advertising {
}

setupPrebid() {
this.executePlugins('setupPrebid')
this.executePlugins(EXECUTE_PLUGINS_ACTION.SETUPPREBID)
const adUnits = this.getAdUnits(this.config.slots)
window.pbjs.addAdUnits(adUnits)
window.pbjs.setConfig(this.config.prebid)
}

teardownPrebid() {
this.executePlugins('teardownPrebid')
this.executePlugins(EXECUTE_PLUGINS_ACTION.TEARDOWNPREBID)
this.getAdUnits(this.config.slots).forEach(({ code }) => window.pbjs.removeAdUnit(code))
}

setupGpt() {
this.executePlugins('setupGpt')
this.executePlugins(EXECUTE_PLUGINS_ACTION.SETUPGPT)
const pubads = window.googletag.pubads()
const { targeting } = this.config
this.defineGptSizeMappings()
Expand All @@ -374,7 +382,7 @@ export default class Advertising {
}

teardownGpt() {
this.executePlugins('teardownGpt')
this.executePlugins(EXECUTE_PLUGINS_ACTION.TEARDOWNGPT)
window.googletag.destroySlots()
}

Expand Down