npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@a5it/sku-generator

v1.1.10

Published

TypeORM + PostgreSQL library for generating SKUs for A5IT

Downloads

43

Readme

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 skus by default if using @Entity('skus')).
  • Supports efficient batch processing of multiple SKUs.

Table of Contents


Installation

npm install @a5it/sku-generator

Usage

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 null

Batch 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 performance

Error 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 SKUBatchResult objects 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 SKUParams to 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.

License

MIT