Create a Customer
Create a customer to track usage and enforce limits:Copy
import Limitry from '@limitry/sdk';
const client = new Limitry();
const customer = await client.customers.create({
externalId: 'user_123', // Your internal user/customer ID
name: 'Acme Corp',
email: '[email protected]',
metadata: {
plan: 'pro',
tier: 'enterprise'
}
});
console.log(`Created customer: ${customer.id}`);
List Customers
Copy
// List all customers
const customers = await client.customers.list();
for (const customer of customers.data) {
console.log(`${customer.id}: ${customer.name || customer.externalId}`);
}
// With pagination
const page = await client.customers.list({ limit: 50 });
if (page.hasMore) {
const nextPage = await client.customers.list({ cursor: page.nextCursor });
}
Retrieve a Customer
Copy
const customer = await client.customers.retrieve('cust_123');
console.log(`Customer: ${customer.name}`);
console.log(`External ID: ${customer.externalId}`);
console.log(`Metadata: ${JSON.stringify(customer.metadata)}`);
Update a Customer
Copy
const customer = await client.customers.update('cust_123', {
name: 'Acme Corporation',
metadata: {
plan: 'enterprise',
tier: 'premium'
}
});
Get Customer Events
Retrieve events for a customer within a date range:Copy
// Get events for the last 30 days
const events = await client.events.list({
customerId: 'cust_123',
startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
endDate: new Date().toISOString()
});
console.log(`Total events: ${events.data.length}`);
for (const event of events.data) {
console.log(`${event.eventType}: ${JSON.stringify(event.values)}`);
}
Use Cases
Customer Billing
Generate billing data for a customer using meters:Copy
async function getMonthlyBill(customerId: string, meterId: string, year: number, month: number) {
// Calculate month boundaries
const start = new Date(year, month - 1, 1);
const end = new Date(year, month, 1);
// Get meter value for the period
const meterValue = await client.meters.getValue(meterId, {
customerId,
startDate: start.toISOString(),
endDate: end.toISOString()
});
return {
customerId,
period: `${year}-${month.toString().padStart(2, '0')}`,
usage: meterValue.value,
// Apply your pricing logic
costDollars: meterValue.value * 0.001 // Example: $0.001 per unit
};
}
// Generate January 2024 bill
const bill = await getMonthlyBill('cust_123', 'mtr_tokens', 2024, 1);
console.log(`Invoice for ${bill.period}: $${bill.costDollars.toFixed(2)}`);
Customer Dashboard
Show usage stats in a customer-facing dashboard:Copy
async function getCustomerStats(customerId: string, meterId: string) {
const now = new Date();
// Current month usage
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const currentMonth = await client.meters.getValue(meterId, {
customerId,
startDate: monthStart.toISOString(),
endDate: now.toISOString()
});
// Previous month usage (for comparison)
const prevMonthEnd = new Date(monthStart.getTime() - 1);
const prevMonthStart = new Date(prevMonthEnd.getFullYear(), prevMonthEnd.getMonth(), 1);
const prevMonth = await client.meters.getValue(meterId, {
customerId,
startDate: prevMonthStart.toISOString(),
endDate: prevMonthEnd.toISOString()
});
return {
currentMonth: { usage: currentMonth.value },
previousMonth: { usage: prevMonth.value }
};
}
const stats = await getCustomerStats('cust_123', 'mtr_tokens');
console.log(`This month: ${stats.currentMonth.usage.toLocaleString()} units`);
console.log(`Last month: ${stats.previousMonth.usage.toLocaleString()} units`);
Usage Reports
Generate usage reports across multiple customers:Copy
async function generateUsageReport(
customerIds: string[],
meterId: string,
startDate: string,
endDate: string
) {
const report = await Promise.all(
customerIds.map(async (customerId) => {
const meterValue = await client.meters.getValue(meterId, {
customerId,
startDate,
endDate
});
return {
customerId,
usage: meterValue.value
};
})
);
// Sort by usage (highest first)
report.sort((a, b) => b.usage - a.usage);
return report;
}
// Top customers by usage
const customers = ['cust_001', 'cust_002', 'cust_003'];
const report = await generateUsageReport(
customers,
'mtr_tokens',
'2024-01-01T00:00:00Z',
'2024-01-31T23:59:59Z'
);
for (const row of report) {
console.log(`${row.customerId}: ${row.usage.toLocaleString()} units`);
}
React Dashboard Component
Copy
import { useState, useEffect } from 'react';
import Limitry from '@limitry/sdk';
const client = new Limitry();
interface CustomerUsage {
usage: number;
limit: number;
}
function CustomerUsageCard({ customerId, meterId, limitId }: {
customerId: string;
meterId: string;
limitId: string;
}) {
const [data, setData] = useState<CustomerUsage | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchUsage() {
const now = new Date();
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const [meterValue, limit] = await Promise.all([
client.meters.getValue(meterId, {
customerId,
startDate: monthStart.toISOString(),
endDate: now.toISOString()
}),
client.limits.retrieve(limitId)
]);
setData({
usage: meterValue.value,
limit: limit.value
});
setLoading(false);
}
fetchUsage();
}, [customerId, meterId, limitId]);
if (loading) return <div>Loading...</div>;
if (!data) return <div>No data</div>;
const percentage = (data.usage / data.limit) * 100;
return (
<div className="usage-card">
<h3>This Month</h3>
<div className="progress-bar" style={{ width: `${Math.min(percentage, 100)}%` }} />
<p>{data.usage.toLocaleString()} / {data.limit.toLocaleString()}</p>
</div>
);
}
Combining with Limits
Check limit status alongside usage:Copy
async function getCustomerLimitStatus(customerId: string) {
// Check all limits for the customer
const check = await client.limits.check({ customerId });
return {
allowed: check.allowed,
limits: check.limits.map(l => ({
name: l.name,
currentValue: l.currentValue,
value: l.value,
remaining: l.remaining,
percentage: l.value > 0 ? (l.currentValue / l.value) * 100 : 0,
exceeded: l.exceeded
}))
};
}
const status = await getCustomerLimitStatus('cust_123');
console.log(`Allowed: ${status.allowed}`);
for (const limit of status.limits) {
console.log(`${limit.name}: ${limit.currentValue}/${limit.value} (${limit.percentage.toFixed(1)}%)`);
}