class PosthootAPI {
constructor() {
this.baseURL = 'https://api.posthoot.com';
this.tokens = this.loadTokens();
}
loadTokens() {
const stored = localStorage.getItem('posthoot_tokens');
return stored ? JSON.parse(stored) : null;
}
saveTokens(tokens) {
this.tokens = tokens;
localStorage.setItem('posthoot_tokens', JSON.stringify(tokens));
}
async makeRequest(endpoint, options = {}) {
if (!this.tokens?.access_token) {
throw new Error('No access token available');
}
const response = await fetch(`${this.baseURL}${endpoint}`, {
...options,
headers: {
'Authorization': `Bearer ${this.tokens.access_token}`,
'Content-Type': 'application/json',
...options.headers
}
});
if (response.status === 401) {
// Token expired, try to refresh
await this.refreshToken();
return this.makeRequest(endpoint, options);
}
return response;
}
async refreshToken() {
const response = await fetch(`${this.baseURL}/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: this.tokens.refresh_token })
});
if (response.ok) {
const newTokens = await response.json();
this.saveTokens(newTokens);
} else {
// Redirect to login
window.location.href = '/login';
}
}
async register(email, password, firstName, lastName) {
const response = await fetch(`${this.baseURL}/auth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, first_name: firstName, last_name: lastName })
});
if (response.ok) {
const data = await response.json();
this.saveTokens({
access_token: data.access_token,
refresh_token: data.refresh_token
});
return data;
} else {
throw new Error('Registration failed');
}
}
async sendEmail(to, subject, html) {
const response = await this.makeRequest('/email', {
method: 'POST',
body: JSON.stringify({
to,
subject,
html,
provider: 'CUSTOM',
data: []
})
});
return response.json();
}
async getAnalytics(emailId) {
const response = await this.makeRequest(`/api/v1/analytics/email?emailId=${emailId}`);
return response.json();
}
}
// Usage
const api = new PosthootAPI();
// Register (if not already registered)
await api.register('your-email@example.com', 'password123', 'Your', 'Name');
// Send email
const emailResult = await api.sendEmail(
'recipient@example.com',
'Hello from Posthoot!',
'<h1>Welcome</h1><p>This is a test email.</p>'
);
// Check analytics
const analytics = await api.getAnalytics(emailResult.emailId);
console.log('Analytics:', analytics);