Helpers
A Helper in an Andera Worker is a utility class that provides reusable logic for your functions or services. Helpers are defined in the src/helpers/ directory and are imported manually where needed.
Structure of a Helper
A helper can be any TypeScript module exporting functions or classes. There is no required structure, just export what you need.
Example
This helper hands out the Playwright browser contexts created by a service, one per slot, and resets them after use:
// src/helpers/playwrightPool.ts
import type { BrowserContext } from 'playwright'
import { contexts, contextStatus, contextBusySince } from '../services/playwright'
export async function getFreeContext(): Promise<{ context: BrowserContext; index: number } | null> {
for (let i = 0; i < contexts.length; i++) {
if (contextStatus[i] === 'free') {
contextStatus[i] = 'busy'
contextBusySince[i] = Date.now()
return { context: contexts[i], index: i }
}
}
return null
}
export async function releaseContext(index: number) {
// Clear state left by the previous task before reusing the context
await contexts[index].clearCookies()
await contexts[index].clearPermissions()
contextStatus[index] = 'free'
contextBusySince[index] = null
}
Logging in Helpers
You can use the logging utilities to trace helper usage or errors (see Logging):
import { log, error } from '@andera-top/worker-core/dist/utils/logger'
export async function getFreeContext() {
log('[PLAYWRIGHT]', 'Looking for a free context...')
// ...
}
export async function releaseContext(index: number) {
try {
// ...
} catch (e) {
error('[PLAYWRIGHT]', 'Failed to release context', e)
}
}
Creating and Using a Helper
- Create a new file in
src/helpers/, e.g.myHelper.ts. - Export your functions or classes.
- Import and use your helper in any function or service:
import { getFreeContext, releaseContext } from '../helpers/playwrightPool'
Helpers are not auto-discovered; you import them where you need them.
tip
Use helpers to keep your functions and services clean, DRY, and maintainable. See Logging for tracing helper usage.