đ§Šī¸ Product Block Functions
Product block functions provide pure business logic for comprehensive product management in NodeBlocks applications. These blocks handle product CRUD operations, image management, product variants, and data normalization with proper error handling.
đ¯ Overviewâ
Product block functions are designed to:
- Manage product lifecycle with full CRUD operations
- Handle product images with cloud storage integration
- Support product variants for inventory management
- Normalize product data for API responses
- Build database queries for flexible product searches
- Integrate with file storage for media management
- Ensure type safety with comprehensive error handling
- Return Result types for proper error handling
đ Product Block Typesâ
Product CRUD Blocksâ
Pure functions for creating, reading, updating, and deleting product entities.
Image Management Blocksâ
Pure functions for handling product images with cloud storage integration.
Product Variant Blocksâ
Pure functions for managing product variations and inventory.
Data Normalization Blocksâ
Pure functions for formatting product data for API responses.
Query Builder Blocksâ
Pure functions for constructing MongoDB queries for product searches.
đ§ Available Product Blocksâ
File Upload Blocksâ
generateProductImageUploadUrlâ
Generates signed upload URL for product image files with unique object ID.
Purpose: Create pre-signed URL for uploading a product image and return the generated storage objectId.
Parameters:
fileStorageDriver: FileStorageDriverâ File storage driver for generating signed URLscontentType: stringâ MIME type of the file to be uploadedcontentLength: numberâ Size of the file in bytes
Returns: Promise<Result<{ objectId: string; url: string }, FileStorageServiceError | ProductBlockError>>
Handler Process:
- Input: File storage driver,
contentType,contentLength - Process: Generates a UUID objectId with extension inferred from
contentType, and asks the driver for a signed upload URL - Output:
{ objectId, url }whereobjectIdis the storage key andurlis the signed upload URL - Errors:
FileStorageServiceErrorif signing fails;ProductBlockErrorfor domain-specific failures
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const uploadResult = await blocks.generateProductImageUploadUrl(
fileStorageDriver,
'image/jpeg',
1024 * 1024
);
if (uploadResult.isOk()) {
const { objectId, url } = uploadResult.value;
// Use url to upload and persist objectId alongside the product
}
Product Retrieval Blocksâ
getProductByIdâ
Retrieves a product by ID from the products collection.
Purpose: Fetches a single product entity by its unique identifier
Parameters:
productsCollection: Collection<BaseEntity>- MongoDB collection containing product entitiesproductId: string- Unique identifier of the product to retrieve
Returns: Promise<Result<BaseEntity, ProductNotFoundBlockError | ProductUnexpectedDBError>> - Product data or error
Handler Process:
- Input: Products collection and product ID string
- Process: Queries the database for a product with the specified ID
- Output: Result containing the found product or error details
- Errors: ProductNotFoundBlockError when product doesn't exist, ProductUnexpectedDBError for database failures
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in route composition:
const result = await blocks.getProductById(
productsCollection,
'product-123'
);
if (result.isOk()) {
const product = result.value;
// Process product data
}
findProductsâ
Retrieves products from database collection based on filter criteria.
Purpose: Queries products with flexible filtering options
Parameters:
productsCollection: Collection<BaseEntity>- MongoDB collection containing product entitiesfilter: Filter<BaseEntity>- Optional MongoDB filter for querying specific products
Returns: Promise<Result<BaseEntity[], ProductBlockError>> - Array of products or error
Handler Process:
- Input: Products collection and optional filter
- Process: Queries database collection with filter and converts cursor to array
- Output: Result with array of products or error
- Errors: ProductBlockError if database query fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Find all products:
const result = await blocks.findProducts(
productsCollection,
{}
);
// Find products with filter:
const filtered = await blocks.findProducts(
productsCollection,
{ category: 'electronics' }
);
if (result.isOk()) {
const products = result.value;
// Process products array
}
Product Normalization Blocksâ
normalizeProductâ
Normalizes a single product by removing _id field from product entity.
Purpose: Prepares product data for API responses by removing internal MongoDB fields
Parameters:
product: Record<string, unknown>- Product entity to normalize
Returns: Result<Omit<T, '_id'>, never> - Normalized product without _id field
Handler Process:
- Input: Product entity with generic
Record<string, unknown>type - Process: Destructures _id field and returns remaining object properties
- Output: Result with normalized product (without _id field) or never (no errors)
- Errors: Never - function always succeeds
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.normalizeProduct(productFromDb);
if (result.isOk()) {
const normalized = result.value;
// Normalized product without _id
}
normalizeProductsâ
Normalizes multiple products by removing _id field from each product entity.
Purpose: Prepares multiple products for API responses
Parameters:
products: Record<string, unknown>[]- Array of product entities to normalize
Returns: Result<Omit<T, '_id'>[], never> - Array of normalized products
Handler Process:
- Input: Array of products with generic
Record<string, unknown>type - Process: Maps over products array and normalizes each product using normalizeProduct function
- Output: Result with array of normalized products (without _id field) or never (no errors)
- Errors: Never - function always succeeds
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = blocks.normalizeProducts(productsFromDb);
if (result.isOk()) {
const normalized = result.value;
// Array of normalized products
}
Product Image Normalization Blocksâ
normalizeProductImageâ
Normalizes product image by converting objectId to signed download URL.
Purpose: Transforms product image objectId to signed download URL
Parameters:
fileStorageDriver: FileStorageDriver- File storage driver for URL generationproductImage: T- Product image with objectId and type
Returns: Promise<Result<NormalizedProductImage, FileStorageServiceError>> - Normalized image or error
Handler process:
- Input: ProductImage with objectId and type fields
- Process: Generates signed download URL using file storage driver
- Output: NormalizedProductImage with URL and type fields
- Errors: FileStorageServiceError if URL generation fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Normalize a single product image:
const result = await normalizeProductImage(fileStorageDriver, {
objectId: "abc123",
type: "image/jpeg"
});
// Result contains: { url: "https://signed-url...", type: "image/jpeg" }
normalizeImagesOfProductâ
Normalizes product images by converting ProductImage objects to signed URLs.
Purpose: Transforms all product images for API response
Parameters:
fileStorageDriver: FileStorageDriver- File storage driver for generating signed URLsproduct: T- Product object with images property to normalize
Returns: Promise<Result<Omit<T, 'images'> & { images?: NormalizedProductImage[] }, FileStorageServiceError>>
Handler process:
- Input: Product object with optional images array and file storage driver
- Process: Maps each ProductImage to NormalizedProductImage using file storage driver
- Output: Product object with normalized images containing signed URLs
- Errors: FileStorageServiceError if any image normalization fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Normalize product images:
const result = await normalizeImagesOfProduct(fileStorageDriver, {
id: "product123",
name: "Sample Product",
images: [
{ objectId: "img1", type: "image/jpeg" },
{ objectId: "img2", type: "image/png" }
]
});
// Result contains: { id: "product123", name: "Sample Product", images: [{ url: "https://signed-url1...", type: "image/jpeg" }, { url: "https://signed-url2...", type: "image/png" }] }
normalizeImagesOfProductsâ
Normalizes images for multiple products by processing their image arrays through file storage.
Purpose: Converts all images for multiple products to include signed download URLs
Parameters:
fileStorageDriver: FileStorageDriver- File storage driver for generating signed download URLsproducts: T[]- Array of products with optional ProductImage arrays to normalize, where T extends{ images?: ProductImage[] }
Returns: Promise<Result<(T & { images?: NormalizedProductImage[] })[], ProductBlockError | FileStorageServiceError>> - Array of products with normalized images or error
Handler Process:
- Input: File storage driver and array of products with optional images
- Process: Maps over products array and normalizes each product's images using normalizeImagesOfProduct function
- Output: Result with array of products containing normalized images with signed URLs or error
- Errors: ProductBlockError or FileStorageServiceError if normalization fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Normalize images for multiple products:
const result = await blocks.normalizeImagesOfProducts(
fileStorageDriver,
products
);
result.match(
(normalizedProducts) => console.log('Images normalized:', normalizedProducts),
(error) => console.error('Normalization failed:', error)
);
Product Image Management Blocksâ
createProductImageâ
Creates a new product image and adds it to the product's images array.
Purpose: Adds image metadata to a product's image collection
Parameters:
productsCollection: Collection<{ images: ProductImage[] }>- MongoDB collection containing product documents with images arrayproductId: string- Unique identifier of the product to add image toimage: ProductImage- Product image data to create and add
Returns: Promise<Result<string, ProductNotFoundBlockError | ProductUnexpectedDBError>>
Handler process:
- Input: Products collection, product ID, and image data
- Process: Creates base entity from image data and pushes it to product's images array using MongoDB updateOne
- Output: Result with image ID on success or error on failure
- Errors: ProductNotFoundBlockError when product doesn't exist, ProductUnexpectedDBError on database failures
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in route composition:
const result = await blocks.createProductImage(
productsCollection,
productId,
{ objectId: 'img-uuid', type: 'image/jpeg', alt: 'Product photo' }
);
if (result.isOk()) {
console.log('Image created with ID:', result.value);
}
getProductImageByIdâ
Retrieves a specific product image by product ID and image ID from database.
Purpose: Fetches a single image from a product's image collection
Parameters:
productsCollection: Collection<BaseEntity & { images: BaseEntity[] }>- MongoDB collection containing product documents with images arrayproductId: string- Unique identifier of the product containing the imageimageId: string- Unique identifier of the specific image to retrieve
Returns: Promise<Result<BaseEntity, ProductNotFoundBlockError | ProductImageNotFoundBlockError | ProductUnexpectedDBError>>
Handler process:
- Input: Product ID, image ID, and MongoDB collection with product documents
- Process: Queries database for product with matching ID, uses $elemMatch projection to find specific image
- Output: Result with image entity data or error details
- Errors: ProductUnexpectedDBError when product not found, ProductImageNotFoundBlockError when image not found, ProductUnexpectedDBError for database failures
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in route handlers:
const imageResult = await blocks.getProductImageById(
productsCollection,
'product-123',
'image-456'
);
if (imageResult.isOk()) {
const imageData = imageResult.value;
// Process image data
}
deleteProductImageâ
Deletes a product image from storage and removes it from the product's images array.
Purpose: Removes image from product's images array and deletes file from storage
Parameters:
fileStorageDriver: FileStorageDriver- File storage driver for deleting the actual image fileproductsCollection: Collection<{ images: (BaseEntity & ProductImage)[] }>- MongoDB collection containing products with images arrayproductId: string- Unique identifier of the product containing the imageimageId: string- Unique identifier of the image to be deleted
Returns: Promise<Result<true, ProductNotFoundBlockError | ProductImageNotFoundBlockError | ProductUnexpectedDBError | FileStorageServiceError>>
Handler process:
- Input: File storage driver, products collection, product ID, and image ID
- Process: Removes image from product's images array, deletes file from storage, updates product timestamp
- Output: Success result (true) or error result with specific error types
- Errors: ProductNotFoundBlockError, ProductImageNotFoundBlockError, ProductUnexpectedDBError, FileStorageServiceError
Key Features:
- Atomic database operation with proper error handling
- Automatic product timestamp update on image deletion
- File deletion from cloud storage
- Returns specific error for product not found vs image not found
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in route composition:
const deleteProductImageRoute = withRoute({
handler: compose(deleteProductImage, nextHandler)
});
// Delete product image:
const result = await blocks.deleteProductImage(
fileStorageDriver,
productsCollection,
'product123',
'image456'
);
if (result.isOk()) {
console.log('Image deleted successfully');
}
deleteImagesOfProductâ
Deletes all images associated with a product from file storage.
Purpose: Cleanup operation for removing all product images when products are deleted
Parameters:
fileStorageDriver: FileStorageDriver- File storage driver for image deletion operationsproductsCollection: Collection<{ images: (BaseEntity & ProductImage)[] }>- MongoDB collection containing product documents with images arrayproductId: string- Unique identifier of the product to delete images for
Returns: Promise<Result<true, FileStorageServiceError | ProductNotFoundBlockError | ProductUnexpectedDBError>>
Handler process:
- Input: File storage driver, products collection, and product ID
- Process: Retrieves product, validates existence, deletes all associated image files from storage using
Result.combinefor parallel deletion - Output: Success confirmation (true) or error details
- Errors: FileStorageServiceError when file deletion fails, ProductNotFoundBlockError when product doesn't exist, ProductUnexpectedDBError for database failures
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Delete all images for a product:
const result = await blocks.deleteImagesOfProduct(
fileStorageDriver,
productsCollection,
'product-123'
);
if (result.isOk()) {
console.log('All product images deleted successfully');
}
Product CRUD Blocksâ
getProductByIdâ
Retrieves a product from database collection by its unique identifier.
Purpose: Fetches a single product with existence validation
Parameters:
productsCollection: Collection<BaseEntity>- MongoDB collection containing product entitiesproductId: string- Unique identifier of the product to retrieve
Returns: Promise<Result<BaseEntity, ProductNotFoundBlockError | ProductUnexpectedDBError>>
Handler process:
- Input: MongoDB collection and product ID string
- Process: Queries database collection for product with matching ID
- Output: Result with product entity or error details
- Errors: ProductNotFoundBlockError when product doesn't exist, ProductUnexpectedDBError for database failures
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in service handlers:
const productResult = await blocks.getProductById(
productsCollection,
"product-123"
);
if (productResult.isOk()) {
const product = productResult.value;
// Process product data
}
findProductsâ
Queries products from database collection with optional filter criteria.
Purpose: Searches products with custom filter conditions
Parameters:
productsCollection: Collection<BaseEntity>- MongoDB collection containing product entitiesfilter: Filter<BaseEntity>- Optional MongoDB filter for querying specific products
Returns: Promise<Result<WithId<BaseEntity>[], ProductBlockError>>
Handler process:
- Input: MongoDB collection and optional filter for product querying
- Process: Executes find query with filter (or empty object if no filter) and converts cursor to array
- Output: Result with array of product entities or error
- Errors: ProductBlockError if database query fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Find all products:
const result = await blocks.findProducts(productsCollection, {});
// Find products by category:
const result = await blocks.findProducts(
productsCollection,
{ category: 'electronics' }
);
// Find products by organization and status:
const result = await blocks.findProducts(
productsCollection,
{ organizationId: 'org-123', status: 'ACTIVE' }
);
findProductResourcesâ
Finds product resources in database collection with specified filter criteria and options.
Purpose: Advanced product search with MongoDB find options
Parameters:
collection: Collection- MongoDB collection instance for productsfilter: Record<string, unknown>- Filter criteria for product searchoptions: FindOptions- MongoDB find options for query configuration (sorting, pagination, etc.)
Returns: Promise<Result<Record<string, unknown>[], ProductUnexpectedDBError>>
Handler process:
- Input: MongoDB collection, filter object, and find options
- Process: Queries collection using findResources utility with filter and options
- Output: Array of product documents or error
- Errors: ProductUnexpectedDBError for database operation failures
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Find products by organization:
const result = await blocks.findProductResources(
productsCollection,
{ organizationId: 'org123' },
{}
);
// Find products by category with sorting:
const result = await blocks.findProductResources(
productsCollection,
{ categoryId: 'cat456' },
{ sort: { createdAt: -1 } }
);
// Find products by status with pagination:
const result = await blocks.findProductResources(
productsCollection,
{ status: 'active' },
{ limit: 10, skip: 0 }
);
Product Normalization Blocksâ
normalizeProductâ
Normalizes a single product by removing _id field from product entity.
Purpose: Removes MongoDB internal _id field for API responses
Parameters:
product: T- Product entity to normalize, destructured to extract _id and rest
Returns: Result<Omit<T, '_id'>, never>
Handler process:
- Input: Product entity with generic
Record<string, unknown>type - Process: Destructures _id field and returns remaining object properties
- Output: Result with normalized product (without _id field) or never (no errors)
- Errors: Never - function always succeeds
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in route composition:
const result = blocks.normalizeProduct({
_id: 'mongo-id',
id: 'product-123',
name: 'Product Name'
});
// result.value => { id: 'product-123', name: 'Product Name' }
normalizeProductsâ
Normalizes multiple products by removing _id field from each product entity.
Purpose: Batch normalization for multiple products
Parameters:
products: T[]- Array of product entities to normalize
Returns: Result<Omit<T, '_id'>[], never>
Handler process:
- Input: Array of products with generic
Record<string, unknown>type - Process: Maps over products array and normalizes each product using normalizeProduct function
- Output: Result with array of normalized products (without _id field) or never (no errors)
- Errors: Never - function always succeeds or throws errors
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in route composition:
const result = blocks.normalizeProducts([
{ _id: '1', id: 'prod-1', name: 'Product 1' },
{ _id: '2', id: 'prod-2', name: 'Product 2' }
]);
// result.value => [
// { id: 'prod-1', name: 'Product 1' },
// { id: 'prod-2', name: 'Product 2' }
// ]
normalizeImagesOfProductsâ
Normalizes product images for multiple products by converting ProductImage objects to signed URLs.
Purpose: Batch image normalization for product lists
Parameters:
fileStorageDriver: FileStorageDriver- File storage driver for URL generation operationsproducts: T[]- Array of product objects with optional images property containing ProductImage objects
Returns: Promise<Result<(Omit<T, 'images'> & { images?: NormalizedProductImage[] })[], FileStorageServiceError>>
Handler process:
- Input: Array of product objects with optional images arrays and file storage driver
- Process: Maps each product through normalizeImagesOfProduct to convert ProductImage objects to NormalizedProductImage with signed URLs
- Output: Array of product objects with normalized images containing signed URLs
- Errors: FileStorageServiceError if any image normalization fails across any product
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Normalize images for multiple products:
const result = await normalizeImagesOfProducts(fileStorageDriver, [
{
id: "product1",
name: "Product 1",
images: [
{ objectId: "img1", type: "image/jpeg" },
{ objectId: "img2", type: "image/png" }
]
},
{
id: "product2",
name: "Product 2",
images: [
{ objectId: "img3", type: "image/gif" }
]
}
]);
// Result contains products with images: [{ url: "https://signed-url1...", type: "image/jpeg" }, ...]
Product Variant CRUD Blocksâ
createProductVariantâ
Creates product variant in MongoDB collection for a given product.
Purpose: Adds a new variant to a product
Parameters:
productVariantsCollection: Collection- MongoDBCollectionfor product variantsproductVariant: Record<string, unknown>- Plain object containing product variant fieldsproductId: string- Identifier of the parent product
Returns: Promise<Result<string, ProductVariantError>>
Handler process:
- Input: MongoDB collection, product variant payload, productId string
- Process: Builds base entity with id/timestamps and productId; inserts into collection
- Output: Returns created product variant id on success
- Errors: ProductVariantDbError when insert fails or on exception
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.createProductVariant(
productVariantsCollection,
{ sku: 'XL-RED', price: 1999 },
'prod_123'
);
if (result.isOk()) {
const variantId = result.value;
}
getProductVariantByIdâ
Retrieves product variant by id with optional parent product constraint.
Purpose: Fetches a single variant with validation
Parameters:
productVariantsCollection: Collection- MongoDBCollectionfor product variantsproductVariantId: string- Identifier of the product variant to retrieveproductId?: string- Optional parent product identifier to scope the lookup
Returns: Promise<Result<Record<string, unknown>, ProductVariantError>>
Handler process:
- Input: MongoDB collection, productVariantId string, optional productId string
- Process: Queries collection by
idand optionallyproductId - Output: Returns product variant record on success
- Errors: ProductVariantDbError when not found or on database exception
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.getProductVariantById(
productVariantsCollection,
'var_123',
'prod_123'
);
if (result.isOk()) {
const variant = result.value;
}
updateProductVariantâ
Updates product variant fields in MongoDB collection with optional constraints.
Purpose: Modifies existing variant data
Parameters:
productVariantsCollection: Collection- MongoDBCollectionfor product variantsproductVariant: Record<string, unknown>- Partial fields to update on the product variantproductVariantId: string- Identifier of the product variant to updatefilter?: Record<string, unknown>- Optional additional query constraints (e.g.,{ productId })
Returns: Promise<Result<boolean, ProductVariantError>>
Handler process:
- Input: MongoDB collection, partial variant fields,
productVariantId, optional filter - Process: Matches by
id(and optional filter), applies$setwith base entity update - Output: Returns
trueon successful modification - Errors:
ProductVariantNotFoundErrorif no match;ProductVariantDbErroron failure/exception
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.updateProductVariant(
productVariantsCollection,
{ price: 2099, stock: 10 },
'var_123',
{ productId: 'prod_123' }
);
if (result.isOk()) {
// updated
}
deleteProductVariantâ
Deletes product variant by id from MongoDB collection.
Purpose: Removes a variant from the system
Parameters:
productVariantsCollection: Collection- MongoDBCollectionfor product variantsproductVariantId: string- Identifier of the product variant to delete
Returns: Promise<Result<boolean, ProductVariantError>>
Handler process:
- Input: MongoDB collection and
productVariantIdstring - Process: Executes
deleteOne({ id })and verifiesdeletedCount - Output: Returns
trueon successful deletion - Errors:
ProductVariantDbErrorwhen not found or on deletion failure
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.deleteProductVariant(
productVariantsCollection,
'var_123'
);
if (result.isOk()) {
// deleted
}
findProductVariantsâ
Product variants retrieval with filter criteria from MongoDB collection.
Purpose: Queries variants with custom filters
Parameters:
productVariantsCollection: Collection- MongoDBCollectionfor product variantsfilter: Record<string, unknown>- Query constraints to filter results (e.g.,{ productId })
Returns: Promise<Result<Record<string, unknown>[], ProductVariantError>>
Handler process:
- Input: MongoDB collection and filter object with query constraints
- Process: Executes
find(filter)and materializes the cursor to an array - Output: Returns an array of product variant records on success
- Errors:
ProductVariantDbErroron query failure or thrown exception
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.findProductVariants(
productVariantsCollection,
{ productId: 'prod_123' }
);
if (result.isOk()) {
const variants = result.value;
}
Product Variant Bulk Operationsâ
createProductVariantBulkâ
Creates multiple product variants in bulk within a single database operation.
Purpose: Efficient batch variant creation with product association and comprehensive error handling
Parameters:
productVariantsCollection: Collection- MongoDB collection for product variantsproductVariants: Record<string, unknown>[]- Array of product variant data objects to createproductId: string- Target product ID to associate all variants with
Returns: Promise<Result<string[], ProductVariantError>>
Handler process:
- Input: Database collection, array of product variant data, and target product ID
- Process: Associates all variants with productId, maps to base entities, inserts bulk into collection, returns created IDs
- Output: Result with array of created product variant IDs or database error
- Errors: ProductVariantDbError for bulk write failures, index-specific errors, or general database errors
Key Features:
- Bulk Operations: Efficient single database operation for multiple variants
- Product Association: Automatically associates all variants with the specified product
- Error Reporting: Specific error details for bulk write failures including index information
- ID Generation: Automatic UUID generation for each created variant
- Atomic Operations: All variants succeed or entire operation fails
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.createProductVariantBulk(
productVariantsCollection,
[
{
title: 'Small - Red',
sku: 'S-RED',
price: { amount: 1999, currency: 'USD' }
},
{
title: 'Medium - Blue',
sku: 'M-BLUE',
price: { amount: 2099, currency: 'USD' }
}
],
'prod_123'
);
if (result.isOk()) {
const variantIds = result.value; // ['uuid1', 'uuid2']
}
updateProductVariantBulkâ
Updates multiple product variants in bulk via database collection update operation.
Purpose: Efficient batch update of product variants with comprehensive error handling and validation
Parameters:
productVariantsCollection: Collection- MongoDB collection for product variantsproductVariantIds: string[]- Array of product variant IDs to updateproductVariant: Record<string, unknown>- Update data to apply to all matching variantsfilter?: Record<string, unknown>- Optional additional filter criteria for the update
Returns: Promise<Result<boolean, ProductVariantError>>
Handler process:
- Input: Database collection, variant IDs array, update data, and optional filter
- Process: Updates all variants matching IDs using MongoDB updateMany with additional filtering
- Output: Success boolean (true) or specific error details
- Errors: ProductVariantNotFoundError if no variants found, ProductVariantDbError for database failures or no modifications
Key Features:
- Bulk Operations: Efficient single database operation for multiple variant updates
- Flexible Filtering: Supports additional filter criteria beyond ID matching
- Atomic Operations: All updates succeed or entire operation fails
- Error Specificity: Detailed error reporting for various failure scenarios
- Data Normalization: Automatic timestamp updates via base entity updates
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.updateProductVariantBulk(
productVariantsCollection,
['var-123', 'var-456', 'var-789'],
{
description: 'Updated description for all variants',
price: { amount: 2999, currency: 'USD' }
}
);
if (result.isOk()) {
console.log('All variants updated successfully');
}
deleteProductVariantBulkâ
Product variants deletion in bulk from MongoDB collection.
Purpose: Efficient batch removal of multiple product variants with comprehensive error handling and validation
Parameters:
productVariantsCollection: Collection- MongoDB collection for product variantsproductVariantIds: string[]- Array of product variant IDs to delete
Returns: Promise<Result<boolean, ProductVariantError>>
Handler process:
- Input: Database collection and array of product variant IDs
- Process: Executes MongoDB
deleteManyoperation with ID filter, validates deletion count - Output: Success boolean (true) when at least one variant is deleted
- Errors: ProductVariantDbError for database failures or when no variants are deleted
Key Features:
- Bulk Operations: Efficient single database operation for multiple variant deletions
- Atomic Operations: All deletions succeed or entire operation fails
- Error Specificity: Detailed error reporting for various failure scenarios
- Validation: Ensures at least one variant is deleted before returning success
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.deleteProductVariantBulk(
productVariantsCollection,
['var-123', 'var-456', 'var-789']
);
if (result.isOk()) {
console.log('All specified variants deleted successfully');
}
Query Builder Blocksâ
buildFilterToGetProductVariantsByProductIdâ
Builds database filter to retrieve existing product variants by product ID.
Purpose: Creates filter for product-specific variant queries
Parameters:
productId: string- Product identifier to filter variants
Returns: Promise<Result<Record<string, unknown> & { productId: string }, never>>
Handler process:
- Input: Product ID string to filter variants
- Process: Creates filter object with product ID
- Output: Result with filter containing productId
- Errors: Never fails (always returns ok result)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in route composition:
const filter = await blocks.buildFilterToGetProductVariantsByProductId(
'product-123'
);
const variants = await blocks.findProductVariants(
productVariantsCollection,
filter.value
);
buildFilterToGetProductVariantsByIdsâ
Builds database filter to retrieve product variants by their IDs using MongoDB $in operator.
Purpose: Creates filter for multi-variant queries
Parameters:
productVariantIds: string[]- Array of product variant identifiers to filter
Returns: Promise<Result<{ id: { $in: string[] } }, never>>
Handler process:
- Input: Array of product variant IDs to filter
- Process: Creates MongoDB filter with $in operator for ID matching
- Output: Result with filter containing id:
{ $in: string[] } - Errors: Never fails (always returns ok result)
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Used in route composition:
const filter = await blocks.buildFilterToGetProductVariantsByIds([
'var-1',
'var-2',
'var-3'
]);
const variants = await blocks.findProductVariants(
productVariantsCollection,
filter.value
);
buildProductLikersByLikeProductIdQueryâ
Builds MongoDB query filter to find products liked by specific product ID.
Purpose: Finds profiles that liked a specific product
Parameters:
likeProductId: string- The product ID to search for in productLikes
Returns: Result<Filter<T>, never> where T extends { productLikes: { likeProductId: string }[] }
Handler process:
- Input: Product ID to search for in productLikes array
- Process: Creates MongoDB $elemMatch filter for productLikes array
- Output: Result containing MongoDB filter object
- Type Safety: Generic type ensures productLikes array structure
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
// Find products that have liked a specific product:
const query = blocks.buildProductLikersByLikeProductIdQuery("product123");
const likers = await collection.find(query.value);
đ Related Documentationâ
- Product Schemas - Product data validation and contracts
- Product Handlers - Product business logic functions
- Product Routes - HTTP endpoint definitions
- Product Features - Complete product management features
- File Storage Blocks - File storage operations
đ§Š Error Classesâ
Product Error Hierarchyâ
All product block errors extend from ProductBlockError which extends BlockError:
ProductBlockErrorâ
Base error class for product-related block operations.
Usage Context: Common parent for all product-related errors
Example:
throw new ProductBlockError('Unexpected product error');
ProductNotFoundBlockErrorâ
Error thrown when a requested product cannot be found.
Usage Context: Product lookup operations fail
Example:
if (!product) {
return err(new ProductNotFoundBlockError('Product not found'));
}
ProductUnexpectedDBErrorâ
Error thrown when product database operations fail unexpectedly.
Usage Context: Database connection issues or unexpected errors
Example:
} catch (_error) {
return err(new ProductUnexpectedDBError('Failed to query products'));
}
ProductImageNotFoundBlockErrorâ
Error thrown when a requested product image cannot be found.
Usage Context: Image lookup operations fail
Example:
if (!image) {
return err(new ProductImageNotFoundBlockError('Product image not found'));
}
ProductDbErrorâ
Database operation error for product persistence operations.
Usage Context: Database-layer failures for products
Example:
throw new ProductDbError('Failed to insert product');
Product Variant Management Blocksâ
createProductVariantâ
Creates product variant in MongoDB collection for a given product.
Purpose: Creates a new product variant and associates it with an existing product
Handler process:
- Input: MongoDB collection, product variant payload, productId string
- Process: Builds base entity with id/timestamps and productId; inserts into collection
- Output: Returns created product variant id on success
- Errors: ProductVariantDbError when insert fails or on exception
Parameters:
productVariantsCollection: Collection- MongoDB collection for product variantsproductVariant: Record<string, unknown>- Plain object containing product variant fieldsproductId: string- Identifier of the parent product
Returns: Promise<Result<string, ProductVariantError>> with created variant id or error
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.createProductVariant(
productVariantsCollection,
{ sku: 'XL-RED', price: 1999 },
'prod_123'
);
if (result.isOk()) {
const variantId = result.value;
}
getProductVariantByIdâ
Retrieves product variant by id with optional parent product constraint.
Purpose: Fetches a product variant by its ID, optionally scoped to a specific product
Handler process:
- Input: MongoDB collection, productVariantId string, optional productId string
- Process: Queries collection by
idand optionallyproductId - Output: Returns product variant record on success
- Errors: ProductVariantDbError when not found or on database exception
Parameters:
productVariantsCollection: Collection- MongoDB collection for product variantsproductVariantId: string- Identifier of the product variant to retrieveproductId?: string- Optional parent product identifier to scope the lookup
Returns: Promise<Result<Record<string, unknown>, ProductVariantError>> with variant data or error
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.getProductVariantById(
productVariantsCollection,
'var_123',
'prod_123'
);
if (result.isOk()) {
const variant = result.value;
}
updateProductVariantâ
Updates product variant fields in MongoDB collection with optional constraints.
Purpose: Modifies existing product variant data with proper validation and error handling
Handler process:
- Input: MongoDB collection, partial variant fields,
productVariantId, optional filter - Process: Matches by
id(and optional filter), applies$setwith base entity update - Output: Returns
trueon successful modification - Errors:
ProductVariantNotFoundErrorif no match;ProductVariantDbErroron failure/exception
Parameters:
productVariantsCollection: Collection- MongoDB collection for product variantsproductVariant: Record<string, unknown>- Partial fields to update on the product variantproductVariantId: string- Identifier of the product variant to updatefilter?: Record<string, unknown>- Optional additional query constraints (e.g.,{ productId })
Returns: Promise<Result<boolean, ProductVariantError>> with success boolean or error
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.updateProductVariant(
productVariantsCollection,
{ price: 2099, stock: 10 },
'var_123',
{ productId: 'prod_123' }
);
if (result.isOk()) {
// Product variant updated successfully
}
deleteProductVariantâ
Deletes product variant by id from MongoDB collection.
Purpose: Removes a product variant from the database by its identifier
Handler process:
- Input: MongoDB collection and
productVariantIdstring - Process: Executes
deleteOne({ id })and verifiesdeletedCount - Output: Returns
trueon successful deletion - Errors:
ProductVariantDbErrorwhen not found or on deletion failure
Parameters:
productVariantsCollection: Collection- MongoDB collection for product variantsproductVariantId: string- Identifier of the product variant to delete
Returns: Promise<Result<boolean, ProductVariantError>> with success boolean or error
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const result = await blocks.deleteProductVariant(productVariantsCollection, 'var_123');
if (result.isOk()) {
// Product variant deleted successfully
}
Product Resource Query Blocksâ
findProductResourcesâ
Finds product resources in database collection with specified filter criteria and options.
Purpose: Retrieves multiple product documents from MongoDB collections with flexible filtering, sorting, and pagination support using the findResources utility.
Handler process:
- Input: MongoDB collection, filter object, and find options
- Process: Queries collection using
findResourcesutility with filter and options - Output: Array of product documents or error
- Errors:
ProductUnexpectedDBErrorfor database operation failures
Parameters:
collection: Collection- MongoDB collection instance for productsfilter: Record<string, unknown>- Filter criteria for product search (e.g.,{ organizationId: 'org123' })options: FindOptions- MongoDB find options for query configuration (sorting, pagination, etc.)
Returns: Promise<Result<Record<string, unknown>[], ProductUnexpectedDBError>> with product documents or error
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const { findProductResources } = blocks.product;
// Find products by organization:
const result = await findProductResources(productsCollection, { organizationId: 'org123' }, {});
// Find products by category with sorting:
const result = await findProductResources(
productsCollection,
{ categoryId: 'cat456' },
{ sort: { createdAt: -1 } }
);
// Find products by status with pagination:
const result = await findProductResources(
productsCollection,
{ status: 'active' },
{ limit: 10, skip: 0 }
);
if (result.isOk()) {
// Process the found products
console.log('Found products:', result.value);
}
buildProductLikersByLikeProductIdQueryâ
Builds MongoDB query filter to find products liked by specific product ID.
Purpose: Creates a MongoDB $elemMatch filter to query the productLikes array and find products that have liked a specific product.
Handler process:
- Input: Product ID that was liked
- Process: Constructs MongoDB filter with $elemMatch on productLikes array
- Output: Result containing MongoDB filter object
- Type Safety: Generic type ensures productLikes array structure
Parameters:
likeProductId: string- The product ID to search for in productLikes
Returns: Result<Filter<T>, never> with MongoDB query filter for finding likers
Example Usage:
import { blocks } from '@nodeblocks/backend-sdk';
const { buildProductLikersByLikeProductIdQuery } = blocks.product;
// Find products that have liked a specific product:
const query = buildProductLikersByLikeProductIdQuery("product123");
const likers = await collection.find(query.value);
// The query creates a filter like:
// { productLikes: { $elemMatch: { likeProductId: "product123" } } }
Product Variant Error Hierarchyâ
ProductVariantErrorâ
Base error class for product variant operations.
Usage Context: Common parent for variant-related errors
Example:
throw new ProductVariantError('Product variant not found');
ProductVariantDbErrorâ
Database error class for variant persistence operations.
Usage Context: Database-layer failures for product variants
Example:
throw new ProductVariantDbError('Failed to update product variant');
ProductVariantNotFoundErrorâ
Error thrown when a variant cannot be found.
Usage Context: Variant lookup or update operations fail
Example:
throw new ProductVariantNotFoundError('Product variant not found');