import { context } from '../context'; export interface IChannelPolicy { /** * The rate at which interstitial ads should be shown. * A value of 1 means always bypass interstitials call, while a value of 0 means always forbid calling interstitials. * A value between 0 and 1 means the interstitial call will be bypassed with a probability of `rate`. */ interstitialRate?: number; } interface HttpClient { get(url: string, options?: { query?: Record }): Promise; } export class ChannelPolicy { private configs: Record | null = null; private firstRun = true; constructor(readonly httpClient: HttpClient) { this.init(); } private async init() { try { this.configs = await this.httpClient.get>( '/api/fe-configs/js-sdk/ads-channel-config' ); } catch (error) { // no-op } } /** * Should bypass calling interstitial based on the channel policy. * @returns */ shouldBypassCallingInterstitial() { let result; if (!this.configs) { this.init(); result = !this.firstRun; // If configs are not loaded yet, should forbid calling interstitial on first run. } else { const channel = context.channel ?? ''; const policy: IChannelPolicy | undefined = this.configs[channel]; const rate = policy?.interstitialRate ?? 1; result = Math.random() < rate; // Bypass interstitial calling with the given rate. } this.firstRun = false; return result; } }