@deer-management-company/brain_utils_node v1.0.5
@deer-management-company/brain_utils_node
Reusable utility package for Brain workflows - Node.js version
Installation
npm install @deer-management-company/brain_utils_nodeUsage
EmailDispatcherByType
A utility class for fetching and processing email subscribers by subscription type.
import { EmailDispatcherByType, SubscriptionType } from '@deer-management-company/brain_utils_node';
// Create an instance
const dispatcher = new EmailDispatcherByType('newsletters', 'my-app');
// Fetch emails for the subscription type
await dispatcher.fetchEmails();
// Get the fetched emails
const emails = dispatcher.getEmails();
console.log(`Found ${emails.length} subscribers`);
// Run a function for each email
await dispatcher.runForEachEmail(async (email, customArg) => {
console.log(`Processing ${email} with ${customArg}`);
// Your custom logic here
}, 'some-custom-argument');Available Subscription Types
newFundingAnnouncements- Notifications about new funding rounds and investmentsnewsletters- NewsLetter extraction and addition to salesforcenewStealthFounders- Updates about new stealth mode startup foundersnewExBigTechFounders- Information about founders who previously worked at major tech companiesnewExUnicornFounders- Updates about founders from previous unicorn companiesnewExAIFounders- Information about founders with AI company backgroundstopCompanies- Updates about top performing companies
Constructor Options
new EmailDispatcherByType(
subscriptionType: SubscriptionType,
origin?: string, // Default: 'unknown'
logFn?: LogFunction // Default: console.log with origin prefix
)Methods
fetchEmails(): Promise<void>
Fetches emails from the Brain API for the specified subscription type.
runForEachEmail<T>(fn: Function, ...args: T[]): Promise<void>
Runs a function for each fetched email. Automatically calls fetchEmails() first.
getEmails(): string[]
Returns a copy of the fetched emails array.
getSubscriptionType(): SubscriptionType
Returns the current subscription type.
getOrigin(): string
Returns the origin identifier.
static getValidTypes(): Record<SubscriptionType, string>
Returns all valid subscription types with their descriptions.
Custom Logging
You can provide a custom logging function:
const customLogger = (message: string) => {
console.log(`[MY-APP] ${new Date().toISOString()} - ${message}`);
};
const dispatcher = new EmailDispatcherByType('newsletters', 'my-app', customLogger);Error Handling
The class handles errors gracefully:
- Network errors during email fetching result in an empty email list
- Errors in the function passed to
runForEachEmailare logged but don't stop processing other emails
TypeScript Support
This package is written in TypeScript and includes full type definitions.
Development
Building
npm run buildTesting
npm testDevelopment Mode
npm run devRunning Examples
# Build and run the example
npm run build
node dist/example.js
# Or uncomment the last line in src/example.ts and run:
npm run build && node dist/example.js๐ Deployment & Versioning
This package uses automated deployment with GitHub Actions. The workflow automatically handles version bumping, tagging, GitHub releases, and npm publishing.
Prerequisites
- npm Account: Create an account at npmjs.com
- npm Token: Generate an automation token in your npm account settings
- GitHub Secret: Add the npm token as
NPM_TOKENin your repository secrets
Deploy via GitHub Actions (Recommended)
Option 1: GitHub Web Interface
- Go to your repository on GitHub
- Click Actions tab
- Find "Auto Bump, Tag, Release, and NPM Publish" workflow
- Click Run workflow
- Select the version bump type:
patch: Bug fixes (1.0.0 โ 1.0.1)minor: New features (1.0.0 โ 1.1.0)major: Breaking changes (1.0.0 โ 2.0.0)
- Click Run workflow
Option 2: GitHub CLI (Command Line)
# Install GitHub CLI if you haven't already
# macOS: brew install gh
# Other platforms: https://cli.github.com/
# Login to GitHub
gh auth login
# Deploy with patch version (bug fixes)
gh workflow run release.yml --ref main -f bump=patch
# Deploy with minor version (new features)
gh workflow run release.yml --ref main -f bump=minor
# Deploy with major version (breaking changes)
gh workflow run release.yml --ref main -f bump=majorOption 3: Simplified Commands (Recommended)
Via npm scripts:
# Deploy patch version (default - bug fixes)
npm run deploy
# Deploy specific version
npm run deploy:patch # 1.0.0 โ 1.0.1 (bug fixes)
npm run deploy:minor # 1.0.0 โ 1.1.0 (new features)
npm run deploy:major # 1.0.0 โ 2.0.0 (breaking changes)Via shell script:
# Make script executable (first time only)
chmod +x deploy.sh
# Deploy patch version (default)
./deploy.sh
# Deploy specific version
./deploy.sh patch
./deploy.sh minor
./deploy.sh majorWhat the Deployment Does
The automated workflow will:
- ๐ท๏ธ Calculate the next version based on the latest git tag
- ๐ Update
package.jsonwith the new version - ๐จ Build the TypeScript code
- ๐งช Run all tests
- ๐ค Commit and push the version bump
- ๐ท๏ธ Create a new git tag
- ๐ Create a GitHub release
- ๐ฆ Publish to npm registry
Manual Deployment (Alternative)
If you prefer to deploy manually:
# 1. Update version in package.json
npm version patch # or minor/major
# 2. Build the package
npm run build
# 3. Run tests
npm test
# 4. Publish to npm
npm publish
# 5. Push tags to GitHub
git push --tagsChecking Deployment Status
After deployment, verify:
# Check if package is published
npm view @deer-management-company/brain_utils_node
# Install and test in another project
npm install @deer-management-company/brain_utils_nodeVersion Strategy
- Patch (1.0.0 โ 1.0.1): Bug fixes, documentation updates
- Minor (1.0.0 โ 1.1.0): New features, backward compatible changes
- Major (1.0.0 โ 2.0.0): Breaking changes, API modifications
License
ISC
Repository
https://github.com/deer-management-company/brain_utils_node
๐ฆ Installation
npm install brain-utils-node๐ Usage
Basic Usage
import { EmailDispatcherByType, SubscriptionType } from 'brain-utils-node';
// Initialize the dispatcher
const dispatcher = new EmailDispatcherByType(
'newFundingAnnouncements',
'my-script',
(message) => console.log(message) // Optional custom logger
);
// Function to run for each email
const processEmail = async (email: string) => {
console.log(`Processing: ${email}`);
// Your email processing logic here
};
// Process all emails for the subscription type
await dispatcher.runForEachEmail(processEmail);Available Subscription Types
newFundingAnnouncements- Notifications about new funding rounds and investmentsnewsletters- NewsLetter extraction and addition to salesforcenewStealthFounders- Updates about new stealth mode startup foundersnewExBigTechFounders- Information about founders who previously worked at major tech companiesnewExUnicornFounders- Updates about founders from previous unicorn companiesnewExAIFounders- Information about founders with AI company backgroundstopCompanies- Updates about top performing companies
Advanced Usage
import { EmailDispatcherByType, SubscriptionType, LogFunction } from 'brain-utils-node';
// Custom logger
const customLogger: LogFunction = (message: string) => {
console.log(`[${new Date().toISOString()}] ${message}`);
};
const dispatcher = new EmailDispatcherByType('newsletters', 'newsletter-processor', customLogger);
// Process emails with additional parameters
const processEmailWithParams = async (email: string, batchId: string, priority: number) => {
console.log(`Processing ${email} - Batch: ${batchId}, Priority: ${priority}`);
// Your processing logic
};
await dispatcher.runForEachEmail(processEmailWithParams, 'batch-001', 1);
// Or fetch emails manually
await dispatcher.fetchEmails();
const emails = dispatcher.getEmails();
console.log(`Found ${emails.length} emails`);
// Get valid subscription types
const validTypes = EmailDispatcherByType.getValidTypes();
console.log('Available types:', Object.keys(validTypes));๐ Development
Setup
# Clone the repository
git clone https://github.com/deer-management-company/brain_utils.git
cd brain_utils/brain_utils_node
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm testTypeScript Support
This package is written in TypeScript and includes full type definitions. You get:
- Type safety for subscription types
- IntelliSense support
- Compile-time error checking
๐ License
This project is licensed under the ISC License.
๐ Related
API Reference
EmailDispatcherByType
Constructor
constructor(
subscriptionType: SubscriptionType,
origin?: string,
logFn?: LogFunction
)Methods
fetchEmails(): Promise<void>- Fetches emails from the APIrunForEachEmail<T>(fn: (email: string, ...args: T) => void | Promise<void>, ...args: T): Promise<void>- Runs a function for each emailgetEmails(): string[]- Returns the current list of emailsgetSubscriptionType(): SubscriptionType- Returns the subscription typegetOrigin(): string- Returns the origin identifier
Static Methods
getValidTypes(): Record<SubscriptionType, string>- Returns all valid subscription types and their descriptions