UNPKG

smp-serverless-utils

Version:

Utilities for working with GCP Storage, file handling, and PDF/SVG conversions

267 lines (203 loc) 7.24 kB
# GCP Storage Utils A utility package for working with Google Cloud Storage, file handling, PDF/SVG conversions, and URL utilities. ## Installation ```bash npm install smp-serverless-utils ``` ## Features - 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: ```bash # 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:utils ``` ## Package Structure - `src/`: Source code - `dist/`: Compiled JavaScript (generated) - `examples/`: Example code for each utility - `test/`: Test files ## API Reference ### File Utilities #### `getFileName(queryObject: any, options?: any): string` Generates a filename based on query parameters. ```typescript 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].svg ``` #### `getUniqueFileName(name: string): string` Creates a unique filename using timestamp and random string. ```typescript const uniqueName = getUniqueFileName('document'); // Returns: document_[timestamp]_[random-string] ``` #### `validateRequest(body: any): string` Validates a request body to ensure it has a valid ID. ```typescript 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. ```typescript 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.svg ``` ### PDF Utilities #### `svgToPDF(svgData: string, tempDir: string, fileName: string, pageHeight: number, pageWidth: number): Promise<string>` Converts SVG data to a PDF file. ```typescript const pdfPath = await svgToPDF( '<svg>...</svg>', // SVG string data '/tmp', // Temporary directory 'document', // Base filename 800, // Page height 600 // Page width ); // Returns: /tmp/document.pdf ``` ### HTML 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:** ```typescript 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). ```typescript 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. ```typescript 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 URL ``` ### URL Utilities #### `getStoryExporterPageURL(storyId: string, organization: number, queryParams: URLSearchParams): string` Generates a URL for story export. ```typescript const url = getStoryExporterPageURL( 'story123', 456, new URLSearchParams({ format: 'pdf' }) ); // Returns: ${BASE_URL}/render/456/story123?sToken=${process.env.STOKEN}&format=pdf ``` #### `getDynamicStoryExporterPageURL(storyId: string, queryParams: URLSearchParams): string` Generates a URL for dynamic story export. ```typescript const url = getDynamicStoryExporterPageURL( 'story123', new URLSearchParams({ format: 'pdf' }) ); // Returns: ${BASE_URL}/dynamic-render/story123?sToken=${process.env.STOKEN}&format=pdf ``` #### `fetchHead(url: string): Promise<Headers>` Fetches HTTP headers from a URL using a HEAD request. ```typescript const headers = await fetchHead('https://example.com/file.pdf'); // Returns: Headers object with response headers ``` #### `fetchRedirectUrl(url: string): Promise<string>` Fetches the redirect URL from a URL. ```typescript const redirectUrl = await fetchRedirectUrl('https://bit.ly/example'); // Returns: The final URL after following redirects ``` #### `fetchMimeType(url: string): Promise<string>` Fetches the MIME type of a URL. ```typescript 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 operations - `STOKEN`: Security token for story exporter URLs - `FUNCTION_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: ```typescript 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