@cra-risk-management/sdk
v1.0.4
Published
Software Development Kit for JS apps - CRA Risk Management API Client
Downloads
413
Maintainers
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-jsQuick 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 secondsThe 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 passwordconst token = await client.login('username', 'password');logout()- Clear credentials and tokenclient.logout();setCredentials(username, password)- Set credentials without authenticatingclient.setCredentials('username', 'password');setToken(token, expiresIn)- Set token directlyclient.setToken('your-token', 3600);isAuthenticated()- Check if client has a valid tokenif (client.isAuthenticated()) { // Client is authenticated }
HTTP Methods
get(endpoint, params)- Make a GET requestconst data = await client.get('/municipalities/items', { limit: 10 });post(endpoint, data)- Make a POST requestconst result = await client.post('/municipalities', { name: 'New Municipality' });patch(endpoint, data)- Make a PATCH requestconst updated = await client.patch('/municipalities/items/1', { name: 'Updated Name' });delete(endpoint)- Make a DELETE requestawait client.delete('/municipalities/items/1');confirm(endpoint, id)- Confirm a resourceawait client.confirm('/critical_points', 123);
Resource Clients
Municipalities
Access via client.municipalities:
list(params)- List all municipalitiesconst municipalities = await client.municipalities.list({ limit: 10 });get(id, params)- Get a municipality by IDconst municipality = await client.municipalities.get(1);create(data)- Create a new municipalityconst newMunicipality = await client.municipalities.create({ name: 'New Municipality', code: 'NM001' });update(id, data)- Update a municipalityconst updated = await client.municipalities.update(1, { name: 'Updated Name' });delete(id)- Delete a municipalityawait client.municipalities.delete(1);
Critical Points
Access via client.criticalPoints:
list(params)- List all critical pointsconst points = await client.criticalPoints.list({ event_type_id: 1, municipality_id: 5, confirmed: true });get(id, params)- Get a critical point by IDconst point = await client.criticalPoints.get(123);create(data)- Create a new critical pointconst newPoint = await client.criticalPoints.create({ name: 'Critical Point 1', latitude: 40.7128, longitude: -74.0060 });update(id, data)- Update a critical pointconst updated = await client.criticalPoints.update(123, { confirmed: true });delete(id)- Delete a critical pointawait 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 zonesget(id, params)- Get event zone by IDcreate(data)- Create event zoneupdate(id, data)- Update event zonedelete(id)- Delete event zone
Event Types - client.criticalPoints.attributes.eventTypes
list(params)- List event typesget(id, params)- Get event type by IDcreate(data)- Create event typeupdate(id, data)- Update event typedelete(id)- Delete event type
Observations - client.criticalPoints.attributes.observations
list(params)- List observationsget(id, params)- Get observation by IDcreate(data)- Create observationupdate(id, data)- Update observationdelete(id)- Delete observation
Users
Access via client.users:
list(params)- List all usersconst users = await client.users.list();get(id, params)- Get a user by IDconst user = await client.users.get(1);create(data)- Create a new userconst newUser = await client.users.create({ username: 'newuser', email: '[email protected]' });update(id, data)- Update a userconst updated = await client.users.update(1, { email: '[email protected]' });delete(id)- Delete a userawait 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
- Clone the repository
- Install dependencies:
npm install - Run tests:
npm test - Run tests in watch mode:
npm run test:watch - 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
