@singcl/ad-execute-manager
v1.8.5
Published
A powerful and flexible ad execution management library for handling reward-based ads, interstitial ads, and other advertising formats in JavaScript applications.
Readme
AD Execute Manager
A powerful and flexible ad execution management library for handling reward-based ads, interstitial ads, and other advertising formats in JavaScript applications.
Table of Contents
Features
- Unified Ad Execution: Single interface for managing different types of ads
- Task Queue Management: Handles multiple ad execution tasks in a queue
- Flexible Control: Manual control over ad execution flow with
nextfunction - Error Handling: Comprehensive error handling and logging
- State Persistence: Built-in storage for ad state management
- Analytics Integration: Built-in analytics support
- Middleware Pattern: Uses middleware pattern for ad execution flow
- Cancellation Support: Ability to clear and cancel pending tasks
Installation
npm install @singcl/ad-execute-managerUsage
Basic Usage
import { AdExecuteManager, RewardAdFather } from '@singcl/ad-execute-manager';
// Get the singleton instance
const adManager = AdExecuteManager.getInstance();
// Create an ad instance (extend RewardAdFather)
class MyRewardAd extends RewardAdFather {
async ad(ctx, next) {
// Your ad logic here
console.log('Executing reward ad');
// Call next when ready to proceed
await next();
return { success: true, message: 'Ad executed successfully' };
}
}
// Create ad instance
const myAd = new MyRewardAd();
// Add task to execution queue
const result = await adManager.addTask(myAd, {
options: { /* ad options */ },
collection: { /* callback collection */ }
});Advanced Usage
import { AdExecuteManager, RewardAdSceneTriggerManager } from '@singcl/ad-execute-manager';
// Initialize with logging enabled
const adManager = AdExecuteManager.getInstance({ log: true });
// Check if manager is running
if (adManager.isRunning()) {
console.log('Ad manager is currently executing tasks');
}
// Get current task ID
const currentTaskId = adManager.getCurrentTaskId();
// Get total number of pending tasks
const taskCount = adManager.getTaskCount();
// Wait for all tasks to complete
await adManager.whenAllTasksComplete();
// Clear all pending tasks
adManager.clearTasks();API Reference
AdExecuteManager
The main class for managing ad execution flow.
Methods
getInstance(args): Get the singleton instance of AdExecuteManagergetSafeInstance(): Get the instance, returns null if not initializedaddTask(adInstance, ctx): Add an ad task to the execution queueclearTasks(): Cancel all pending tasksgetTaskCount(): Get the number of pending tasksisRunning(): Check if tasks are currently runninggetCurrentTaskId(): Get the ID of the current executing taskwhenAllTasksComplete(): Returns a Promise that resolves when all tasks are complete
RewardAdFather
Base class for reward ad implementations.
InterstitialAdFather
Base class for interstitial ad implementations.
Other Exports
SerializableError: Error class that can be serializedLogger: Logging utilityStorage: Storage managementCountRecorder: Ad execution counterRewardAdGlobalRecorder: Global ad recorderRewardAdSceneTriggerManager: Scene-based ad trigger managerAdAnalyticsJS: Analytics integrationRewardAdNovel: Novel-specific reward ad implementationInterstitialAdNovel: Novel-specific interstitial ad implementationPubSub: Publish-subscribe pattern implementation
Examples
Reward Ad Unlock
import { AdExecuteManager, RewardAdFather } from '@singcl/ad-execute-manager';
class UnlockAd extends RewardAdFather {
async ad(ctx, next) {
const { options, collection } = ctx;
try {
// Show reward ad
const result = await this.showAd();
if (result.isRewarded) {
// Execute success callback
collection.onSuccess && collection.onSuccess(result);
// Proceed to next task
await next();
return { success: true, data: result };
} else {
// Ad not completed
collection.onCancel && collection.onCancel();
return { success: false, message: 'Ad not completed' };
}
} catch (error) {
collection.onError && collection.onError(error);
throw error;
}
}
}
const adManager = AdExecuteManager.getInstance();
const unlockAd = new UnlockAd();
await adManager.addTask(unlockAd, {
options: { /* ad options */ },
collection: {
onSuccess: () => console.log('Reward received!'),
onCancel: () => console.log('Ad cancelled'),
onError: (error) => console.error('Ad error:', error)
}
});More examples can be found in the examples directory.
Contributing
We welcome contributions to this project! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Scripts
npm run build: Build the library for productionnpm run dev: Turn on watch modenpm run lint: Lint your codenpm run format: Format your codenpm run test: Run tests
License
This project is licensed under the MIT License - see the LICENSE file for details.
