Node.js Examples
Complete Node.js/TypeScript examples for using the DocGenLab API.
Installation
npm install axios
# or
yarn add axios
Basic Usage
Initialize Client
import axios, { AxiosInstance } from 'axios';
import fs from 'fs';
class DocGenLabClient {
private client: AxiosInstance;
constructor(apiKey: string, baseURL = 'https://api.docgenlab.com/api/v1') {
this.client = axios.create({
baseURL,
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json',
},
});
}
async generateDocument(
templateId: string,
inputData: Record<string, any>,
outputFormat: 'pdf' | 'docx' = 'pdf'
) {
const response = await this.client.post('/documents/', {
template_id: templateId,
input_json: inputData,
output_format: outputFormat,
});
return response.data;
}
async getDocument(documentId: string) {
const response = await this.client.get(`/documents/${documentId}`);
return response.data;
}
async downloadDocument(documentId: string, outputPath: string) {
const response = await this.client.get(`/documents/${documentId}/download`, {
responseType: 'arraybuffer',
});
fs.writeFileSync(outputPath, response.data);
return outputPath;
}
}
// Initialize
const client = new DocGenLabClient(process.env.DOCGENLAB_API_KEY!);
Example 1: Generate Invoice
async function generateInvoice() {
const document = await client.generateDocument(
'invoice-template-id',
{
invoice_number: 'INV-001',
customer_name: 'Acme Corp',
amount: 1250.0,
due_date: '2024-02-15',
items: [
{ description: 'Consulting', quantity: 10, price: 100 },
{ description: 'Support', quantity: 5, price: 50 },
],
},
'pdf'
);
console.log(`Document created: ${document.id}`);
console.log(`Status: ${document.status}`);
if (document.status === 'ready') {
await client.downloadDocument(document.id, 'invoice.pdf');
console.log('Downloaded invoice.pdf');
}
}
generateInvoice();
Example 2: Express Webhook Handler
import express from 'express';
import axios from 'axios';
const app = express();
app.use(express.json());
app.post('/webhooks/docgenlab', async (req, res) => {
const payload = req.body;
if (payload.status === 'completed') {
// Download document from signed URL
const response = await axios.get(payload.download_url, {
responseType: 'arraybuffer',
});
// Save to file
fs.writeFileSync(`document_${payload.job_id}.pdf`, response.data);
console.log(`Document ${payload.job_id} saved!`);
}
res.status(200).json({ status: 'ok' });
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
Example 3: List Templates
async function listTemplates(isUat = false) {
const response = await client.client.get('/templates/', {
params: { is_uat: isUat },
});
const templates = response.data;
templates.forEach((template: any) => {
console.log(`${template.name} (${template.id})`);
console.log(` Tokens: ${template.tokens_json.map((t: any) => t.name).join(', ')}`);
});
return templates;
}
listTemplates(false); // Production templates
Example 4: Error Handling
async function generateWithRetry(
client: DocGenLabClient,
templateId: string,
inputData: Record<string, any>,
maxRetries = 3
) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const doc = await client.generateDocument(templateId, inputData);
return doc;
} catch (error: any) {
if (error.response?.status === 429) {
const waitTime = Math.pow(2, attempt) * 1000; // Exponential backoff
console.log(`Rate limited. Retrying in ${waitTime / 1000}s...`);
await new Promise((resolve) => setTimeout(resolve, waitTime));
} else {
throw error;
}
}
}
throw new Error('Max retries exceeded');
}
// Usage
const doc = await generateWithRetry(client, 'template-id', { name: 'John' });
Example 5: Parallel Generation
async function generateMultiple() {
const promises = Array.from({ length: 10 }, (_, i) =>
client.generateDocument('template-id', {
customer_name: `Customer ${i + 1}`,
amount: (i + 1) * 100,
})
);
const results = await Promise.all(promises);
results.forEach((doc) => {
console.log(`Generated: ${doc.id}`);
});
}
generateMultiple();
Example 6: TypeScript Types
// Define types for better IDE support
interface Document {
id: string;
template_id: string;
status: 'queued' | 'processing' | 'ready' | 'failed';
output_pdf_path?: string;
output_docx_path?: string;
error_message?: string;
created_at: string;
}
interface Template {
id: string;
name: string;
description?: string;
tokens_json: TokenDefinition[];
source_type: 'docx' | 'html';
is_uat: boolean;
}
interface TokenDefinition {
name: string;
type: 'text' | 'number' | 'date' | 'image';
description?: string;
required?: boolean;
}
// Use in client
class TypedDocGenLabClient extends DocGenLabClient {
async generateDocument(
templateId: string,
inputData: Record<string, any>,
outputFormat: 'pdf' | 'docx' = 'pdf'
): Promise<Document> {
return super.generateDocument(templateId, inputData, outputFormat);
}
async listTemplates(isUat = false): Promise<Template[]> {
const response = await this.client.get('/templates/', {
params: { is_uat: isUat },
});
return response.data;
}
}