Skip to content

AltScore/altscore-typescript

Repository files navigation

AltScore TypeScript SDK

This is the TypeScript SDK for AltScore. It provides a simple interface to the AltScore API with full TypeScript support and modern JavaScript patterns.

Features

  • πŸ”’ Multiple authentication methods: user credentials, client credentials, token, form token
  • πŸ”„ Automatic token renewal with configurable callbacks
  • 🌐 Environment-specific configurations
  • πŸ“Š Rich API for working with Borrower Central
  • πŸ“ Fully typed with TypeScript for better IDE integration
  • πŸš€ Modern async/await API design
  • πŸ” Detailed error handling with specific error types
  • 🧩 Modular architecture for easy extension

Installation

npm install altscore

Or if you prefer pnpm:

pnpm add altscore

Usage

Initialization

You can initialize the SDK in two ways:

Using the Configuration Builder

import { AltScore } from 'altscore';

// Use the fluent builder pattern
const altScore = AltScore.configure()
  .withEnvironment('production')
  .withClientCredentials('your-client-id', 'your-client-secret')
  .withTokenRefreshCallback(token => {
    console.log('Token refreshed:', token);
  })
  .build();

Using the Constructor (Original Style)

import { AltScore } from 'altscore';

// Initialize with options object
const altScore = new AltScore({
  environment: 'production',
  auth: {
    type: 'client_credentials',
    clientId: 'your-client-id',
    clientSecret: 'your-client-secret',
  },
  onTokenRefresh: token => {
    console.log('Token refreshed:', token);
  },
});

Using a Direct Token

import { AltScore } from 'altscore';

// Create from token directly
const altScore = AltScore.fromToken('your-jwt-token', {
  environment: 'production',
});

Working with Borrowers

// Create a borrower
const borrowerId = await altScore.borrowerCentral.borrowers.create({
  persona: 'INDIVIDUAL',
  externalId: 'ext-123',
  label: 'John Doe',
});

// Retrieve a borrower
const borrower = await altScore.borrowerCentral.borrowers.retrieve(borrowerId);

// Update a borrower
if (borrower) {
  // Update label
  const updatedBorrower = await borrower.setLabel('Jane Doe');

  // Add tags
  await borrower.addTags(['vip', 'priority']);

  // Set risk rating
  await borrower.setRiskRating('A');
}

// Query borrowers with pagination
const response = await altScore.borrowerCentral.borrowers.queryPaginated({
  perPage: 10,
  page: 1,
  sortBy: 'createdAt',
  sortDirection: 'desc',
});

console.log(`Page ${response.meta.currentPage} of ${response.meta.totalPages}`);
console.log(`Total: ${response.meta.totalItems} borrowers`);

// Find by identity
const borrowerByEmail = await altScore.borrowerCentral.borrowers.findByIdentity(
  'email',
  'john@example.com'
);

Getting Tenant Information

The tenant ID is automatically read from the authentication token:

// Get the tenant from the token
const tenantId = client.getTenantFromToken();
console.log(`Current tenant: ${tenantId}`);

Error Handling

import { AltScore, HTTPError, TokenRenewalError, ResourceNotFoundError } from 'altscore';

try {
  const borrower = await altScore.borrowerCentral.borrowers.retrieve('nonexistent-id');
  // borrower will be null if not found
} catch (error) {
  if (error instanceof HTTPError) {
    console.log(`HTTP Error ${error.status}: ${error.message}`);
  } else if (error instanceof TokenRenewalError) {
    console.log('Token renewal failed:', error.message);
  } else if (error instanceof ResourceNotFoundError) {
    console.log(`${error.resourceType} with ID ${error.resourceId} not found`);
  }
}

Using in Next.js API Routes

// In an API route
import { AltScore } from 'altscore';

export default async function handler(req, res) {
  const token = req.headers.authorization?.replace('Bearer ', '');

  if (!token) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  try {
    // Create client from token
    const client = AltScore.fromToken(token, {
      environment: process.env.ALTSCORE_ENVIRONMENT,
    });

    // Tenant is automatically read from the token
    const tenant = client.getTenantFromToken();
    console.log(`Request for tenant: ${tenant}`);

    // Handle request
    if (req.method === 'GET') {
      const borrowers = await client.borrowerCentral.borrowers.query(req.query);
      return res.status(200).json(borrowers);
    }
  } catch (error) {
    if (error.status) {
      return res.status(error.status).json({
        error: error.message,
        details: error.response,
      });
    }

    return res.status(500).json({ error: error.message });
  }
}

Environment Variables

The SDK supports the following environment variables:

  • ALTSCORE_EMAIL - Email for user authentication
  • ALTSCORE_PASSWORD - Password for user authentication
  • ALTSCORE_CLIENT_ID - Client ID for API token authentication
  • ALTSCORE_CLIENT_SECRET - Client secret for API token authentication
  • ALTSCORE_TOKEN - Direct JWT token for authentication
  • ALTSCORE_FORM_TOKEN - Form token for public forms
  • ALTSCORE_TENANT - Tenant name for authentication (only needed when not using tokens)
  • ALTSCORE_ENVIRONMENT - Environment (default: 'production')
  • ALTSCORE_LOCAL_BC_URL - Custom URL for local borrower central environment
  • ALTSCORE_LOCAL_AUTH_URL - Custom URL for local authentication environment

Project Structure

src/
β”œβ”€β”€ core/              # Core functionality
β”‚   β”œβ”€β”€ auth/          # Authentication
β”‚   β”œβ”€β”€ http/          # HTTP handling
β”‚   └── config/        # Configuration
β”œβ”€β”€ modules/           # API modules
β”‚   └── borrower-central/
β”‚       β”œβ”€β”€ models/    # Data models
β”‚       β”œβ”€β”€ services/  # API services
β”‚       └── index.ts
β”œβ”€β”€ models/            # Shared models
β”œβ”€β”€ errors/            # Error types
└── utils/             # Utilities

Development

Setup

# Clone the repository
git clone https://github.com/altscore/altscore-typescript.git
cd altscore-typescript

# Install dependencies
npm install

# Build the SDK
npm run build

# Run in development mode with watch
npm run dev

Running Examples

# Configure your environment variables
cp .env.example .env
# Edit .env with your credentials

# Run examples:
# Test connection
npm run test:connection

# Test with token
npm run test:token

# Test builder pattern
npm run test:builder

License

MIT

About

AltScore TypeScript SDK

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published