1.1.10 • Published 9 months ago
@a5it/sku-generator v1.1.10
SKU Generator (TypeORM + PostgreSQL)
A lightweight utility for generating and retrieving SKUs (Stock Keeping Units) stored in a PostgreSQL database using TypeORM. This library:
- Connects to PostgreSQL once and reuses the same connection until explicitly closed.
- Checks if a SKU already exists for a given manufacturer and part number.
- Creates a new SKU if none exists.
- Stores and retrieves SKUs in a database table (named
skusby default if using@Entity('skus')). - Supports efficient batch processing of multiple SKUs.
Table of Contents
Installation
npm install @a5it/sku-generatorUsage
Constructor Parameters
/**
* The options you can pass to the constructor:
* {
* database: {
* url: string; // PostgreSQL connection string
* synchronize: boolean; // Whether to auto-sync the database schema
* logging: boolean; // Enable TypeORM query logging
* extra: {
* max: number; // Max DB connections in the pool
* idleTimeoutMillis: number; // Idle timeout in ms
* connectionTimeoutMillis: number; // Connection timeout in ms
* };
* },
* skuFormat?: {
* prefix: string; // SKU prefix (default: 'A5')
* digitLength: number; // Length of random digits (default: 3)
* manufacturerNameChars: number; // Characters from manufacturer name (default: 2)
* partNumberChars: number; // Characters from part number (default: 1)
* }
* }
*/Basic Usage
import { SKUGenerator } from "@nishanprime/sku-generator";
const skuGen = new SKUGenerator({
database: {
url: "postgres://user:password@localhost:5432/mydb",
synchronize: true, // For dev only
logging: false
},
skuFormat: {
prefix: "B7", // Custom prefix (default: 'A5')
digitLength: 4, // Use 4 random digits (default: 3)
manufacturerNameChars: 2, // Use 2 chars from mfg name (default: 2)
partNumberChars: 1 // Use 1 char from part number (default: 1)
}
});
await skuGen.init();
// Single SKU generation
const sku = await skuGen.getOrCreateSKU({
manufacturerName: "Apple",
manufacturerPartNumber: "M1Chip"
});
// Result: "B71234APM"
// Lookup existing SKU
const existingSku = await skuGen.getSKU("Apple", "M1Chip");
// Result: "B71234APM" if exists, null if not found
// Get details from SKU
const details = await skuGen.getDetails("B71234APM");
// Result: { manufacturerName: "apple", manufacturerPartNumber: "m1chip" } or nullBatch Processing
import { SKUGenerator } from "@nishanprime/sku-generator";
const skuGen = new SKUGenerator();
await skuGen.init();
// 1. Generate/Retrieve Multiple SKUs
const batchResults = await skuGen.generateBatch({
items: [
{ manufacturerName: "Apple", manufacturerPartNumber: "M1Chip" },
{ manufacturerName: "Intel", manufacturerPartNumber: "i7-12700" },
{ manufacturerName: "AMD", manufacturerPartNumber: "Ryzen-7600" }
],
skipExisting: false // Include existing SKUs in results
});
/* Result example:
[
{
sku: "a5123apm",
manufacturerName: "apple",
manufacturerPartNumber: "m1chip",
isNew: true // This SKU was newly generated
},
{
sku: "a5456ini",
manufacturerName: "intel",
manufacturerPartNumber: "i7-12700",
isNew: false // This SKU already existed
},
{
sku: "a5789amr",
manufacturerName: "amd",
manufacturerPartNumber: "ryzen-7600",
isNew: true
}
]
*/
// 2. Lookup Multiple Existing SKUs
const existingSkus = await skuGen.getBatch([
{ manufacturerName: "Apple", manufacturerPartNumber: "M1Chip" },
{ manufacturerName: "Intel", manufacturerPartNumber: "i7-12700" }
]);
/* Result example (only returns existing SKUs):
[
{
sku: "a5123apm",
manufacturerName: "apple",
manufacturerPartNumber: "m1chip",
isNew: false
}
]
*/
// 3. Process Large Batches
const largeBatch = await skuGen.generateBatch({
items: Array.from({ length: 1000 }, (_, i) => ({
manufacturerName: `Manufacturer${i}`,
manufacturerPartNumber: `Part${i}`
})),
skipExisting: true // Only generate new SKUs
});
// Processes in chunks of 100 items for optimal performanceError Handling
import { SKUGenerator } from "@nishanprime/sku-generator";
try {
const skuGen = new SKUGenerator({
database: {
url: "postgres://user:password@localhost:5432/mydb"
}
});
await skuGen.init(); // Throws if connection fails
const results = await skuGen.generateBatch({
items: [
{ manufacturerName: "Apple", manufacturerPartNumber: "M1Chip" },
{ manufacturerName: "", manufacturerPartNumber: "" } // Invalid input
]
});
} catch (error) {
if (error instanceof Error) {
console.error("SKU Generation failed:", error.message);
}
} finally {
await skuGen.close(); // Always close the connection
}Performance Tips
// 1. Reuse the SKUGenerator instance
const skuGen = new SKUGenerator({
database: {
url: process.env.POSTGRES_CONNECTION_STRING,
extra: {
max: 20, // Increase pool size for batch operations
idleTimeoutMillis: 30000
}
}
});
// 2. Use batch operations instead of loops
// ❌ Avoid this:
for (const item of items) {
await skuGen.getOrCreateSKU(item);
}
// ✅ Do this instead:
const results = await skuGen.generateBatch({ items });
// 3. Use skipExisting when appropriate
const newSkusOnly = await skuGen.generateBatch({
items,
skipExisting: true // Don't include existing SKUs in results
});
// 4. Close when done
await skuGen.close();Methods
init()
public async init(): Promise<void>;Ensures the data source is initialized exactly once.
getOrCreateSKU(params)
public async getOrCreateSKU(params: SKUParams): Promise<string>;Returns an existing SKU or creates a new one.
generateBatch(params)
public async generateBatch(params: SKUBatchParams): Promise<SKUBatchResult[]>;Efficiently processes multiple SKUs in batch.
- Params:
interface SKUBatchParams { items: SKUParams[]; // Array of items to process skipExisting?: boolean; // Whether to exclude existing SKUs from results } - Returns: Array of
SKUBatchResultobjects containing generated/existing SKUs and their status. - Features:
- Processes items in chunks to prevent memory issues
- Handles existing SKUs efficiently
- Parallel processing of new SKU generation
- Returns detailed results including whether each SKU is new or existing
getBatch(items)
public async getBatch(items: SKUParams[]): Promise<SKUBatchResult[]>;Retrieves multiple existing SKUs efficiently.
- Params: Array of
SKUParamsto look up - Returns: Array of found SKUs with their details
- Note: Only returns existing SKUs, does not generate new ones
close()
public async close(): Promise<void>;Closes the database connection.
Environment Variables
SKU_DB_CONNECTION_STRING: Default database connection string if not provided in constructor options.