smp-serverless-utils
v1.0.13
Published
Utilities for working with GCP Storage, file handling, and PDF/SVG conversions
Maintainers
Readme
GCP Storage Utils
A utility package for working with Google Cloud Storage, file handling, PDF/SVG conversions, and URL utilities.
Installation
npm install smp-serverless-utilsFeatures
- Upload files to Google Cloud Storage
- SVG to PDF conversion using Puppeteer
- File naming and handling utilities
- URL utilities for fetching headers, MIME types, and redirect URLs
- Snapshot generation from web pages
- Story exporting functionality
Examples
The package includes several examples demonstrating how to use the various utilities:
# Run storage example
npm run example:storage
# Run PDF conversion example
npm run example:pdf
# Run snapshot generator example
npm run example:snapshot
# Run story exporter example
npm run example:story
# Run general utilities example
npm run example:utilsPackage Structure
src/: Source codedist/: Compiled JavaScript (generated)examples/: Example code for each utilitytest/: Test files
API Reference
File Utilities
getFileName(queryObject: any, options?: any): string
Generates a filename based on query parameters.
const fileName = getFileName({
title: 'document',
format: 'png'
});
// Returns: document_[timestamp].png
const storyFileName = getFileName({
storyTitle: 'story',
index: 1,
format: 'jpg'
});
// Returns: story_1.jpg
const defaultFileName = getFileName({
artboardIndexes: 2,
format: 'svg'
});
// Returns: artboard_2_simplified_[timestamp].svggetUniqueFileName(name: string): string
Creates a unique filename using timestamp and random string.
const uniqueName = getUniqueFileName('document');
// Returns: document_[timestamp]_[random-string]validateRequest(body: any): string
Validates a request body to ensure it has a valid ID.
const id = validateRequest({ id: 'test-123' });
// Returns: 'test-123'
// Throws error for invalid input:
validateRequest({ id: 123 }); // Error: Invalid request: 'id' must be provided and must be a string.
validateRequest({}); // Error: Invalid request: 'id' must be provided and must be a string.
validateRequest(null); // Error: Invalid request: 'id' must be provided and must be a string.Storage Utilities
uploadToGCPBucket(bucketName: string, localPath: string, options: UploadOptions): Promise<string>
Uploads a file to Google Cloud Storage.
const url = await uploadToGCPBucket('my-bucket', 'path/to/file.svg', {
functionName: 'uploads',
orgId: 'org123', // optional
storyId: 'story123', // optional
fileName: 'file.svg'
});
// Returns: https://storage.googleapis.com/my-bucket/uploads/org123/story123/[timestamp]/file.svgPDF Utilities
svgToPDF(svgData: string, tempDir: string, fileName: string, pageHeight: number, pageWidth: number): Promise<string>
Converts SVG data to a PDF file.
const pdfPath = await svgToPDF(
'<svg>...</svg>', // SVG string data
'/tmp', // Temporary directory
'document', // Base filename
800, // Page height
600 // Page width
);
// Returns: /tmp/document.pdfHTML to PDF Utilities
htmlToPdf(params: HtmlToPDFParams): Promise<{message: string, url: string}>
Converts HTML content to a PDF, uploads it to a GCP bucket, and returns the public URL.
Parameters:
html(string): The HTML string to convert (must be a JSON stringified HTML string).fileName(string): The base name for the PDF file.margin(object, optional): PDF margin settings (top, right, bottom, left).
Example:
import { htmlToPdf } from 'smp-serverless-utils';
const result = await htmlToPdf({
html: JSON.stringify('<div>Hello World</div>'),
fileName: 'my-pdf',
margin: { top: '2cm', bottom: '2cm' }
});
// Returns: { message: 'PDF generated and uploaded successfully.', url: 'https://storage.googleapis.com/...' }Snapshot Utilities
snapshotGenerator(params: HtmlToPDFParams): Promise<{message: string, url: string}>
Generates a snapshot from a URL in various formats (PDF, PNG, JPEG, WebP).
const result = await snapshotGenerator({
url: 'https://example.com',
fileType: 'png',
pageSize: { width: 1200, height: 800 },
pageData: { /* configuration */ }
});
// Returns: { message: "PDF generated and uploaded successfully.", url: "https://storage..." }Story Export Utilities
exportStory(params: ExportStoryParams): Promise<ExportResult>
Exports a story to various formats.
const result = await exportStory({
title: 'Story Title',
format: 'png',
quality: 1,
multiplier: 2,
organization: 123,
storyId: 'story-id',
pageUrl: 'https://app.com/story/123/view',
// other parameters
});
// Returns export result with download URLURL Utilities
getStoryExporterPageURL(storyId: string, organization: number, queryParams: URLSearchParams): string
Generates a URL for story export.
const url = getStoryExporterPageURL(
'story123',
456,
new URLSearchParams({ format: 'pdf' })
);
// Returns: ${BASE_URL}/render/456/story123?sToken=${process.env.STOKEN}&format=pdfgetDynamicStoryExporterPageURL(storyId: string, queryParams: URLSearchParams): string
Generates a URL for dynamic story export.
const url = getDynamicStoryExporterPageURL(
'story123',
new URLSearchParams({ format: 'pdf' })
);
// Returns: ${BASE_URL}/dynamic-render/story123?sToken=${process.env.STOKEN}&format=pdffetchHead(url: string): Promise<Headers>
Fetches HTTP headers from a URL using a HEAD request.
const headers = await fetchHead('https://example.com/file.pdf');
// Returns: Headers object with response headersfetchRedirectUrl(url: string): Promise<string>
Fetches the redirect URL from a URL.
const redirectUrl = await fetchRedirectUrl('https://bit.ly/example');
// Returns: The final URL after following redirectsfetchMimeType(url: string): Promise<string>
Fetches the MIME type of a URL.
const mimeType = await fetchMimeType('https://example.com/image.png');
// Returns: 'image/png'Environment Variables
This package requires the following environment variables:
BASE_URL: Base URL for story exporter pages (for URL utility functions)BUCKET_NAME: Name of the GCP bucket for storage operationsSTOKEN: Security token for story exporter URLsFUNCTION_ENV: Environment name (e.g., 'local', 'prod')GOOGLE_APPLICATION_CREDENTIALS: Path to Google Cloud credentials JSON file (for GCP operations)
Error Handling
All functions include proper error handling and will throw descriptive errors when:
- Required parameters are missing or invalid
- Network requests fail
- File operations fail
- GCP operations fail
TypeScript Support
The package includes TypeScript type definitions and can be used in TypeScript projects:
import { uploadToGCPBucket } from 'smp-serverless-utils';
// TypeScript will provide type checking and autocompletion
const url = await uploadToGCPBucket('my-bucket', 'file.svg', {
functionName: 'uploads',
fileName: 'file.svg'
});License
MIT
