npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cra-risk-management/sdk

v1.0.4

Published

Software Development Kit for JS apps - CRA Risk Management API Client

Downloads

413

Readme

CRA Risk Management SDK for JavaScript

A comprehensive JavaScript SDK for interacting with the CRA Risk Management API. This SDK provides a simple and intuitive interface for managing municipalities, critical points, users, and related resources.

Installation

Install the package via npm:

npm install @cra-risk-management/sdk-js

Quick Start

CommonJS

const Client = require('@cra-risk-management/sdk-js');

// Initialize the client
const client = new Client({
  baseURL: 'https://your-api-url.com',
  username: 'your-username',
  password: 'your-password'
});

// Authenticate (happens automatically when needed)
await client.login('username', 'password');

// Use resource clients
const municipalities = await client.municipalities.list();
console.log(municipalities);

ES Modules

import Client from '@cra-risk-management/sdk-js';

// Initialize the client
const client = new Client({
  baseURL: 'https://your-api-url.com',
  username: 'your-username',
  password: 'your-password'
});

// Authenticate (happens automatically when needed)
await client.login('username', 'password');

// Use resource clients
const municipalities = await client.municipalities.list();
console.log(municipalities);

Authentication

The SDK supports two authentication methods:

1. Username and Password

const client = new Client({
  baseURL: 'https://your-api-url.com',
  username: 'your-username',
  password: 'your-password'
});

// Login explicitly
await client.login('username', 'password');

// Or set credentials and let the SDK authenticate automatically
client.setCredentials('username', 'password');

2. Token-based Authentication

const client = new Client({
  baseURL: 'https://your-api-url.com'
});

// Set token directly (if you already have one)
client.setToken('your-access-token', 3600); // token and expiry in seconds

The SDK automatically handles token expiration and re-authentication when using username/password credentials.

Configuration Options

When creating a new client instance, you can provide the following options:

const client = new Client({
  baseURL: 'https://your-api-url.com',    // Required: Base URL of the API
  username: 'user',                        // Optional: Username for authentication
  password: 'pass',                        // Optional: Password for authentication
  authEndpoint: '/users/token',           // Optional: Custom auth endpoint (default: /users/token)
  timeout: 30000,                          // Optional: Request timeout in ms (default: 30000)
  maxRetries: 1                            // Optional: Max retry attempts (default: 1)
});

API Reference

Client Methods

Authentication Methods

  • login(username, password) - Authenticate with username and password

    const token = await client.login('username', 'password');
  • logout() - Clear credentials and token

    client.logout();
  • setCredentials(username, password) - Set credentials without authenticating

    client.setCredentials('username', 'password');
  • setToken(token, expiresIn) - Set token directly

    client.setToken('your-token', 3600);
  • isAuthenticated() - Check if client has a valid token

    if (client.isAuthenticated()) {
      // Client is authenticated
    }

HTTP Methods

  • get(endpoint, params) - Make a GET request

    const data = await client.get('/municipalities/items', { limit: 10 });
  • post(endpoint, data) - Make a POST request

    const result = await client.post('/municipalities', { name: 'New Municipality' });
  • patch(endpoint, data) - Make a PATCH request

    const updated = await client.patch('/municipalities/items/1', { name: 'Updated Name' });
  • delete(endpoint) - Make a DELETE request

    await client.delete('/municipalities/items/1');
  • confirm(endpoint, id) - Confirm a resource

    await client.confirm('/critical_points', 123);

Resource Clients

Municipalities

Access via client.municipalities:

  • list(params) - List all municipalities

    const municipalities = await client.municipalities.list({ limit: 10 });
  • get(id, params) - Get a municipality by ID

    const municipality = await client.municipalities.get(1);
  • create(data) - Create a new municipality

    const newMunicipality = await client.municipalities.create({
      name: 'New Municipality',
      code: 'NM001'
    });
  • update(id, data) - Update a municipality

    const updated = await client.municipalities.update(1, { name: 'Updated Name' });
  • delete(id) - Delete a municipality

    await client.municipalities.delete(1);

Critical Points

Access via client.criticalPoints:

  • list(params) - List all critical points

    const points = await client.criticalPoints.list({
      event_type_id: 1,
      municipality_id: 5,
      confirmed: true
    });
  • get(id, params) - Get a critical point by ID

    const point = await client.criticalPoints.get(123);
  • create(data) - Create a new critical point

    const newPoint = await client.criticalPoints.create({
      name: 'Critical Point 1',
      latitude: 40.7128,
      longitude: -74.0060
    });
  • update(id, data) - Update a critical point

    const updated = await client.criticalPoints.update(123, { confirmed: true });
  • delete(id) - Delete a critical point

    await client.criticalPoints.delete(123);
Critical Point Attributes

Access nested attribute resources via client.criticalPoints.attributes:

Event Zones - client.criticalPoints.attributes.eventZones

  • list(params) - List event zones
  • get(id, params) - Get event zone by ID
  • create(data) - Create event zone
  • update(id, data) - Update event zone
  • delete(id) - Delete event zone

Event Types - client.criticalPoints.attributes.eventTypes

  • list(params) - List event types
  • get(id, params) - Get event type by ID
  • create(data) - Create event type
  • update(id, data) - Update event type
  • delete(id) - Delete event type

Observations - client.criticalPoints.attributes.observations

  • list(params) - List observations
  • get(id, params) - Get observation by ID
  • create(data) - Create observation
  • update(id, data) - Update observation
  • delete(id) - Delete observation

Users

Access via client.users:

  • list(params) - List all users

    const users = await client.users.list();
  • get(id, params) - Get a user by ID

    const user = await client.users.get(1);
  • create(data) - Create a new user

    const newUser = await client.users.create({
      username: 'newuser',
      email: '[email protected]'
    });
  • update(id, data) - Update a user

    const updated = await client.users.update(1, { email: '[email protected]' });
  • delete(id) - Delete a user

    await client.users.delete(1);

Examples

Complete Usage Example

const Client = require('@cra-risk-management/sdk-js');

async function main() {
  // Initialize client
  const client = new Client({
    baseURL: 'https://api.example.com',
    username: 'your-username',
    password: 'your-password',
    timeout: 30000
  });

  try {
    // Authenticate
    await client.login('username', 'password');
    console.log('Authenticated successfully');

    // List municipalities
    const municipalities = await client.municipalities.list({ limit: 5 });
    console.log('Municipalities:', municipalities);

    // Create a critical point
    const newPoint = await client.criticalPoints.create({
      name: 'Flood Risk Area',
      latitude: 40.7128,
      longitude: -74.0060,
      event_type_id: 1,
      municipality_id: 5
    });
    console.log('Created critical point:', newPoint);

    // Update the critical point
    const updated = await client.criticalPoints.update(newPoint.id, {
      confirmed: true
    });
    console.log('Updated critical point:', updated);

    // List event zones
    const eventZones = await client.criticalPoints.attributes.eventZones.list();
    console.log('Event zones:', eventZones);

  } catch (error) {
    console.error('Error:', error.message);
  } finally {
    // Logout when done
    client.logout();
  }
}

main();

Error Handling

try {
  const municipalities = await client.municipalities.list();
} catch (error) {
  if (error.status === 404) {
    console.error('Resource not found');
  } else if (error.status === 401) {
    console.error('Authentication failed');
  } else if (error.status >= 500) {
    console.error('Server error');
  } else {
    console.error('Error:', error.message);
  }
}

Using Query Parameters

// List with filtering
const filteredPoints = await client.criticalPoints.list({
  event_type_id: 1,
  municipality_id: 5,
  confirmed: true,
  from_datetime: '2025-01-01',
  to_datetime: '2025-12-31'
});

// List with pagination
const paginatedMunicipalities = await client.municipalities.list({
  limit: 20,
  offset: 40
});

Requirements

  • Node.js >= 14.0.0
  • npm or yarn package manager

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Development Setup

  1. Clone the repository
  2. Install dependencies: npm install
  3. Run tests: npm test
  4. Run tests in watch mode: npm run test:watch
  5. Generate coverage report: npm run test:coverage

Support

For issues, questions, or contributions, please visit:

  • GitHub Issues: https://github.com/CRA-Risk-Management/sdk-js/issues
  • GitHub Repository: https://github.com/CRA-Risk-Management/sdk-js

Made with ❤️ by CRA Risk Management