@ad-execute-manager/core
v2.0.6
Published
Core functionality for ad execution management including AdExecuteManager, utility functions, and middleware composition.
Maintainers
Readme
@ad-execute-manager/core
Core functionality for ad execution management including AdExecuteManager, utility functions, and middleware composition.
Installation
npm install @ad-execute-manager/coreFeatures
- AdExecuteManager: A powerful ad execution management class for handling reward-based ads, interstitial ads, and other advertising formats
- compose: A middleware composition utility inspired by Koa
- needRetryAdError: A utility function for determining if an ad error should be retried
Usage
AdExecuteManager
import { AdExecuteManager } from '@ad-execute-manager/core';
const adManager = new AdExecuteManager({
// Configuration options
});
// Initialize ad
const result = await adManager.init();
// Show ad
const showResult = await adManager.show();Middleware Composition
import { compose } from '@ad-execute-manager/core';
const middlewares = [
async (ctx, next) => {
console.log('Middleware 1 start');
await next();
console.log('Middleware 1 end');
},
async (ctx, next) => {
console.log('Middleware 2 start');
await next();
console.log('Middleware 2 end');
}
];
const composedMiddleware = compose(middlewares);
await composedMiddleware({});Error Retry Utility
import { needRetryAdError } from '@ad-execute-manager/core';
const apiError = {
errMsg: 'ad_show_timeout: normal',
timeout: 5000
};
const shouldRetry = needRetryAdError({
apiError,
configuredAdTimeout: 5000,
errorRetryStrategy: {
timeout: true,
background: true
}
});
console.log('Should retry:', shouldRetry);Examples
实际应用场景示例
1. 完整的广告执行流程
import { AdExecuteManager } from '@ad-execute-manager/core';
// 创建广告执行管理器实例
const adManager = new AdExecuteManager({
log: true,
enableVisibilityListener: true,
maxRetryCount: 2,
errorRetryStrategy: {
timeout: true,
background: true
}
});
// 假设我们有一个广告实例类
class MyRewardAd {
constructor() {
this._adTimeoutTime = 5000;
}
initialize(options) {
console.log('Initializing ad with options:', options);
return this;
}
async ad(ctx, next) {
const { options, collection, recovered } = ctx;
console.log('Showing ad with options:', options);
console.log('Recovered info:', recovered);
try {
// 模拟广告加载和显示
await new Promise(resolve => setTimeout(resolve, 1000));
// 模拟广告成功
if (collection && collection.onSuccess) {
collection.onSuccess();
}
await next({ success: true });
return { success: true };
} catch (error) {
// 模拟广告失败
if (collection && collection.onFail) {
collection.onFail(error);
}
await next({ success: false, error });
return { success: false, error };
}
}
clear() {
console.log('Clearing ad resources');
}
record(info) {
console.log('Recording ad info:', info);
}
}
// 创建广告实例
const rewardAd = new MyRewardAd();
// 添加广告任务
const result = await adManager.addTask(rewardAd, {
options: {
adUnitId: 'your-ad-unit-id',
userId: 'user123'
},
collection: {
onSuccess: () => console.log('Ad success callback'),
onFail: (error) => console.log('Ad fail callback:', error),
onCancel: () => console.log('Ad cancel callback')
}
});
console.log('Ad execution result:', result);
// 等待所有任务完成
await adManager.whenAllTasksComplete();
console.log('All tasks completed');2. 自定义中间件组合
import { compose } from '@ad-execute-manager/core';
// 定义中间件
const middleware1 = async (ctx, next) => {
console.log('Middleware 1 start');
ctx.value1 = 'value1';
await next();
console.log('Middleware 1 end');
};
const middleware2 = async (ctx, next) => {
console.log('Middleware 2 start');
console.log('Received value1:', ctx.value1);
ctx.value2 = 'value2';
await next();
console.log('Middleware 2 end');
};
const middleware3 = async (ctx, next) => {
console.log('Middleware 3 start');
console.log('Received value1:', ctx.value1);
console.log('Received value2:', ctx.value2);
ctx.value3 = 'value3';
await next();
console.log('Middleware 3 end');
};
// 组合中间件
const composedMiddleware = compose([middleware1, middleware2, middleware3]);
// 执行组合后的中间件
const ctx = { initialValue: 'initial' };
await composedMiddleware(ctx);
console.log('Final ctx:', ctx);3. 错误处理和重试策略
import { needRetryAdError } from '@ad-execute-manager/core';
// 模拟不同类型的错误
const timeoutError = {
errMsg: 'ad_show_timeout: normal',
timeout: 5000
};
const backgroundError = {
errMsg: 'app in background is not support show ad'
};
const otherError = {
errMsg: 'ad_load_fail: network error'
};
// 配置重试策略
const retryStrategy = {
timeout: true,
background: true
};
// 检查各种错误是否需要重试
const shouldRetryTimeout = needRetryAdError({
apiError: timeoutError,
configuredAdTimeout: 5000,
errorRetryStrategy: retryStrategy
});
const shouldRetryBackground = needRetryAdError({
apiError: backgroundError,
configuredAdTimeout: 5000,
errorRetryStrategy: retryStrategy
});
const shouldRetryOther = needRetryAdError({
apiError: otherError,
configuredAdTimeout: 5000,
errorRetryStrategy: retryStrategy
});
console.log('Should retry timeout error:', shouldRetryTimeout);
console.log('Should retry background error:', shouldRetryBackground);
console.log('Should retry other error:', shouldRetryOther);API
AdExecuteManager
The main class for managing ad execution with support for initialization, showing, and error handling.
Constructor
new AdExecuteManager(args)- args (Object): 构造函数参数
- options (Object, optional): 广告执行选项
- log (Boolean, optional): 是否打印日志
- enableVisibilityListener (Boolean, optional): 是否启用前后台监听
- maxRetryCount (Number, optional): 最大重试次数,默认为 1,0 表示不重试
- errorRetryStrategy (Object, optional): 错误重试策略
- timeout (Boolean, optional): 是否重试超时错误
- background (Boolean, optional): 是否重试后台错误
Methods
initialize(_args): 初始化 AdExecuteManager 实例
- _args (Any): 初始化参数
- 返回: AdExecuteManager 实例
addTask(adInstance, ctx): 添加广告任务
- adInstance (Object): RewardAdFather 的子类实例
- ctx (Object): 广告执行上下文
- options (Object): 广告执行选项
- collection (Object): 回调集合
- 返回: Promise,广告执行结果的 Promise
clearTasks(): 清空任务栈并取消所有任务
getTaskCount(): 获取当前未完成的任务总数
- 返回: Number,未完成的任务数量
isRunning(): 是否有任务正在运行
- 返回: Boolean
getCurrentTaskId(): 获取当前执行的任务 ID
- 返回: String|null,当前任务 ID
whenAllTasksComplete(): 返回一个 Promise,当任务队列中的所有任务都完成时 resolve
- 返回: Promise
enableVisibilityListener(): 启用前后台监听
disableVisibilityListener(): 禁用前后台监听
isVisibilityListenerEnabled(): 获取前后台监听器状态
- 返回: Boolean,是否启用
destroyVisibilityListener(): 销毁前后台监听器
static getInstance(args): 获取单例实例
- args (Object, optional): 构造函数参数
- 返回: AdExecuteManager 实例
static build(args): 获取单例实例
- args (Object, optional): 构造函数参数
- 返回: AdExecuteManager 实例
static new(args): 创建新实例
- args (Object, optional): 构造函数参数
- 返回: AdExecuteManager 实例
static getSafeInstance(): 获取单例实例,如果不存在则返回 null
- 返回: AdExecuteManager|null
compose
function compose(middlewares: Array<(ctx: any, next: () => Promise<void>) => Promise<void>>): (ctx: any) => Promise<void>- middlewares (Array): KOA 中间件数组,每个中间件函数接收 ctx 和 next 参数
- 返回: Function,返回一个组合后的中间件函数,接收 ctx 参数并按顺序执行所有中间件
needRetryAdError
function needRetryAdError({
apiError,
configuredAdTimeout,
errorRetryStrategy
}: {
apiError: { errMsg?: string; timeout?: number };
configuredAdTimeout: number;
errorRetryStrategy?: {
timeout?: boolean;
background?: boolean;
};
}): boolean- apiError (Object): 广告错误信息
- errMsg (String, optional): 错误信息
- timeout (Number, optional): 超时时间
- configuredAdTimeout (Number): 配置的广告超时时间
- errorRetryStrategy (Object, optional): 错误重试策略
- timeout (Boolean, optional): 是否重试超时错误
- background (Boolean, optional): 是否重试后台错误
- 返回: Boolean,是否需要重试
License
MIT
