@deer-management-company/brain_utils_node
Version:
Reusable utility package for Brain workflows - Node.js version
405 lines (275 loc) โข 10.1 kB
Markdown
# @deer-management-company/brain_utils_node
Reusable utility package for Brain workflows - Node.js version
## Installation
```bash
npm install @deer-management-company/brain_utils_node
```
## Usage
### EmailDispatcherByType
A utility class for fetching and processing email subscribers by subscription type.
```typescript
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 investments
- `newsletters` - NewsLetter extraction and addition to salesforce
- `newStealthFounders` - Updates about new stealth mode startup founders
- `newExBigTechFounders` - Information about founders who previously worked at major tech companies
- `newExUnicornFounders` - Updates about founders from previous unicorn companies
- `newExAIFounders` - Information about founders with AI company backgrounds
- `topCompanies` - Updates about top performing companies
### Constructor Options
```typescript
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:
```typescript
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 `runForEachEmail` are logged but don't stop processing other emails
## TypeScript Support
This package is written in TypeScript and includes full type definitions.
## Development
### Building
```bash
npm run build
```
### Testing
```bash
npm test
```
### Development Mode
```bash
npm run dev
```
### Running Examples
```bash
# 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
1. **npm Account**: Create an account at [npmjs.com](https://www.npmjs.com/)
2. **npm Token**: Generate an automation token in your npm account settings
3. **GitHub Secret**: Add the npm token as `NPM_TOKEN` in your repository secrets
### Deploy via GitHub Actions (Recommended)
#### Option 1: GitHub Web Interface
1. Go to your repository on GitHub
2. Click **Actions** tab
3. Find **"Auto Bump, Tag, Release, and NPM Publish"** workflow
4. Click **Run workflow**
5. 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)
6. Click **Run workflow**
#### Option 2: GitHub CLI (Command Line)
```bash
# 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=major
```
#### Option 3: Simplified Commands (Recommended)
**Via npm scripts:**
```bash
# 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:**
```bash
# 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 major
```
### What the Deployment Does
The automated workflow will:
1. ๐ท๏ธ Calculate the next version based on the latest git tag
2. ๐ Update `package.json` with the new version
3. ๐จ Build the TypeScript code
4. ๐งช Run all tests
5. ๐ค Commit and push the version bump
6. ๐ท๏ธ Create a new git tag
7. ๐ Create a GitHub release
8. ๐ฆ Publish to npm registry
### Manual Deployment (Alternative)
If you prefer to deploy manually:
```bash
# 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 --tags
```
### Checking Deployment Status
After deployment, verify:
```bash
# 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_node
```
### Version 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
```bash
npm install brain-utils-node
```
## ๐ Usage
### Basic Usage
```typescript
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 investments
- `newsletters` - NewsLetter extraction and addition to salesforce
- `newStealthFounders` - Updates about new stealth mode startup founders
- `newExBigTechFounders` - Information about founders who previously worked at major tech companies
- `newExUnicornFounders` - Updates about founders from previous unicorn companies
- `newExAIFounders` - Information about founders with AI company backgrounds
- `topCompanies` - Updates about top performing companies
### Advanced Usage
```typescript
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
```bash
# 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 test
```
### TypeScript 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
- [Original Python version](../README.md)
- [GitHub Repository](https://github.com/deer-management-company/brain_utils)
---
## API Reference
### `EmailDispatcherByType`
#### Constructor
```typescript
constructor(
subscriptionType: SubscriptionType,
origin?: string,
logFn?: LogFunction
)
```
#### Methods
- `fetchEmails(): Promise<void>` - Fetches emails from the API
- `runForEachEmail<T>(fn: (email: string, ...args: T) => void | Promise<void>, ...args: T): Promise<void>` - Runs a function for each email
- `getEmails(): string[]` - Returns the current list of emails
- `getSubscriptionType(): SubscriptionType` - Returns the subscription type
- `getOrigin(): string` - Returns the origin identifier
#### Static Methods
- `getValidTypes(): Record<SubscriptionType, string>` - Returns all valid subscription types and their descriptions