Changelog
2025-11-07
🔄 Changed
⚠️ Breaking Changes
- Chat Channels:
createChatChannelSchemano longer requiresiconfield - channels can be created without specifying an icon (previously required)
Blocks
- Chat:
createChatMessage: Simplified to create messages without attachment handling - attachments now managed via separate endpointsnormalizeChatMessageandnormalizeChatMessages: Refactored to use centralizednormalizeFileutility for attachment processingnormalizeChatMessageAttachment: Simplified to usenormalizeFileutility directly
- Product:
normalizeProductImage,normalizeImagesOfProduct, andnormalizeImagesOfProducts: Refactored to use centralizednormalizeFileutility- Made
imagesproperty optional to handle products without images gracefully
Schemas
- Chat:
createChatMessageSchema: Removedattachmentsrequirement - messages can be created without attachmentscreateChatChannelSchema: Madeiconfield optional - channels can be created without icons
- Product:
createProductSchemaandcreateProductBatchSchema: Removedimagesrequirement - products can be created without images
Routes
- Product:
createProductRouteandcreateProductBatchRoute: Updated to use simplified normalization functions without image processing - Chat: Removed
ProductBlockErrorandChatMessageBlockErrorfrom route error mappings - Chat:
updateChatMessageRoute: Restricted access control to message owners only, removing admin override permissions
🔒 Security Improvements
Chat Message Access Control: Strengthened security by restricting chat message updates to message owners only. Previously, both message owners and administrators could update messages. Now only the original message author can modify their messages:
- Before:
some(checkIdentityType(['admin']), ownsMessage)- Admin override allowed - After:
ownsMessage- Owner-only access control - Impact: Prevents unauthorized message modifications and improves data integrity
🗃️ Data Management Enhancements
Soft Delete Combinator: New withSoftDelete combinator provides automatic soft delete functionality with audit trail capabilities:
- Safe Deletions: Converts hard deletes to soft deletes by marking records with
deletedAttimestamp instead of permanent removal - Automatic Filtering: All read operations (
find,findOne,countDocuments) automatically exclude soft-deleted records - Audit Trail: Maintains deleted records in database for compliance and recovery purposes
- API Compatibility: Existing handlers work without modification - just wrap with
withSoftDelete - Data Recovery: Soft-deleted records can be restored by removing the
deletedAtfield
Usage:
import { withSoftDelete } from '@nodeblocks/backend-sdk';
// Wrap any handler for automatic soft delete functionality
const safeDeleteHandler = withSoftDelete(deleteUserHandler);
// Works with all database operations automatically:
// - DELETE operations become UPDATE with deletedAt timestamp
// - FIND operations exclude records where deletedAt exists
// - UPDATE operations respect soft delete filters
🔧 Type Safety Improvements
MongoDB ID Type Consistency: Enhanced type safety across database operations by ensuring all ID fields are properly cast to strings before MongoDB queries. This prevents potential type mismatches between numeric and string IDs:
- Chat Operations: Chat message attachment deletion queries now use
String(attachmentId) - Organization Management: Member operations use
String(organizationId)andString(identityId)for consistent ID handling - Product Operations: Batch operations now use
productIds.map(String)for$inqueries - Authentication: Identity operations consistently use
String(identityId)for all database updates and queries - Invitation Management: All invitation CRUD operations use
String(invitationId)for MongoDB queries
These changes improve runtime reliability and prevent potential query failures due to type inconsistencies while maintaining full backward compatibility.
🎯 Architectural Improvements
Entity Creation Simplification: Core entities (messages and products) are now created without file attachments, promoting cleaner separation of concerns. File attachments are managed through dedicated endpoints:
- Messages:
POST /messages(core) +POST /messages/:id/attachments(attachments) - Products:
POST /products(core) +POST /products/:id/images(images)
Normalization Centralization: File normalization logic has been centralized into a normalizeFile utility function, reducing code duplication and improving maintainability. All image and attachment normalization now uses this unified approach.
Access Control Refinement: Chat message permissions have been tightened to enforce strict ownership-based access control, removing administrative overrides for message updates. This aligns with the principle of least privilege and improves data security.
Schema Simplification: Channel creation has been streamlined by making the icon field optional, allowing channels to be created without specifying an icon. This reduces friction in the channel creation process while maintaining full functionality for icon management through separate endpoints.
Data Safety Infrastructure: Introduction of soft delete capabilities provides robust data protection and audit trails. The withSoftDelete combinator ensures data integrity by preventing permanent data loss while maintaining full API compatibility and enabling data recovery when needed.
This refactoring improves API design by making entity creation simpler while maintaining full functionality through dedicated resource endpoints, enhances code maintainability through centralized file handling utilities, strengthens security through granular access controls, and ensures data safety with comprehensive soft delete capabilities.
2025-11-06
main
✨ Added
Profile Follow Management
-
Delete Profile Follow: Added ability to delete profile follow relationships (unfollowing)
- Added
deleteProfileFollowRoute- DELETE endpoint for removing follow relationships - Added
deleteProfileFollowFeature- Complete feature with validation and routing - Added
deleteProfileFollowSchema- Path parameter validation for profile follow deletion - Updated User Service to include DELETE
/profiles/:profileId/profile-follows/:followProfileIdendpoint - Authorization: Requires admin role or profile ownership
- Returns
204 No Contenton successful deletion - Returns
404 Not Foundif profile or follow relationship doesn't exist - See merge request nodeblocks/nodeblocks-backend-sdk!261
- Added
-
Get Profile Followers: Added ability to retrieve paginated list of followers for a profile
- Added
getProfileFollowersRoute- GET endpoint for retrieving followers with pagination - Added
getProfileFollowersFeature- Complete feature with validation, pagination, and routing - Added
getProfileFollowersSchema- Path parameter validation for followers retrieval - Added
normalizeFollowers- Block function for normalizing follower data with avatar URLs - Added
buildProfileFollowersByFollowProfileIdQuery- Block function for building MongoDB follower queries - Updated User Service to include GET
/profiles/:profileId/followersendpoint - Authorization: Requires admin role or profile ownership
- Returns
200 OKwith paginated follower list and normalized avatar URLs - Supports pagination with query parameters (page, limit)
- Returns
404 Not Foundif profile doesn't exist - See merge request nodeblocks/nodeblocks-backend-sdk!232
- Added
-
Create Organization Follow: Added ability to create organization follow relationships
- Added
createOrganizationFollowRoute- PUT endpoint for creating organization follow relationships - Added
createOrganizationFollowFeature- Complete feature with validation and routing - Added
createOrganizationFollowSchema- Path parameter validation for organization follow creation - Added
createOrganizationFollow- Block function for creating organization follow relationships - Added
OrganizationAlreadyFollowedBlockError- Error for duplicate organization follows - Added
OrganizationNotFoundError- Error for missing organization records - Updated User Service to include PUT
/profiles/:profileId/organization-follows/:followOrganizationIdendpoint - Authorization: Requires admin role or profile ownership
- Returns
204 No Contenton successful creation - Returns
409 Conflictif organization is already followed - Returns
404 Not Foundif profile or organization doesn't exist - See merge request nodeblocks/nodeblocks-backend-sdk!233
- Added
-
Delete Organization Follow: Added ability to delete organization follow relationships
- Added
deleteOrganizationFollowRoute- DELETE endpoint for removing organization follow relationships - Added
deleteOrganizationFollowFeature- Complete feature with validation and routing - Added
deleteOrganizationFollowSchema- Path parameter validation for organization follow deletion - Added
deleteOrganizationFollow- Block function for removing organization follow relationships - Added
OrganizationFollowNotFoundBlockError- Error for missing organization follow relationships - Updated User Service to include DELETE
/profiles/:profileId/organization-follows/:followOrganizationIdendpoint - Authorization: Requires admin role or profile ownership
- Returns
204 No Contenton successful deletion - Returns
404 Not Foundif profile, organization, or follow relationship doesn't exist - Existence validation: Returns 404 instead of silent success for missing relationships
- See merge request nodeblocks/nodeblocks-backend-sdk!236
- Added
-
Get Organization Followers: Added ability to retrieve paginated list of organization followers
- Added
getOrganizationFollowersRoute- GET endpoint for retrieving organization followers with pagination - Added
getOrganizationFollowersFeature- Complete feature with validation, pagination, and routing - Added
getOrganizationFollowersSchema- Path parameter validation for followers retrieval - Added
buildOrganizationFollowersByFollowOrganizationIdQuery- Block function for building MongoDB follower queries - Updated Organization Service to require
userscollection for follower data access - Authorization: Requires admin role or organization ownership
- Returns
200 OKwith paginated follower list and normalized avatar URLs - Supports pagination with query parameters (page, limit)
- Returns
404 Not Foundif organization doesn't exist - Reuses profile blocks (findProfiles, normalizeFollowers) for consistency
- See merge request nodeblocks/nodeblocks-backend-sdk!246
- Added
Product Like Management
-
Create Product Like: Added ability to create product like relationships (favoriting products)
- Added
createProductLikeRoute- PUT endpoint for creating product like relationships - Added
createProductLikeFeature- Complete feature with validation and routing - Added
createProductLikeSchema- Path parameter validation for product like creation - Added
createProductLike- Block function for creating product like relationships - Added
ProductAlreadyLikedBlockError- Error for duplicate product likes - Updated User Service to include PUT
/profiles/:profileId/product-likes/:likeProductIdendpoint - Updated User Service to require
productscollection for product validation - Authorization: Requires admin role or profile ownership
- Returns
201 Createdon successful creation - Returns
409 Conflictif product is already liked - Returns
404 Not Foundif profile or product doesn't exist - Duplicate prevention using MongoDB $ne operator
- See merge request nodeblocks/nodeblocks-backend-sdk!240
- Added
-
Delete Product Like: Added ability to delete product like relationships (unfavoriting products)
- Added
deleteProductLikeRoute- DELETE endpoint for removing product like relationships - Added
deleteProductLikeFeature- Complete feature with validation and routing - Added
deleteProductLikeSchema- Path parameter validation for product like deletion - Added
deleteProductLike- Block function for removing product like relationships - Added
ProductLikeNotFoundBlockError- Error for missing product like relationships - Updated User Service to include DELETE
/profiles/:profileId/product-likes/:likeProductIdendpoint - Authorization: Requires admin role or profile ownership
- Returns
204 No Contenton successful deletion - Returns
404 Not Foundif profile, product, or like relationship doesn't exist - Existence validation: Returns 404 instead of silent success for missing relationships
- See merge request nodeblocks/nodeblocks-backend-sdk!241
- Added
🐞 Fixed
Security
- Identity Service: Removed password field from identity endpoint responses for enhanced security
- Updated
GET /identities/:identityIdto exclude password from response - Updated
GET /identitiesto exclude password from response - Updated
PATCH /identities/:identityIdto exclude password from response - Password fields are now filtered out before sending responses to clients
- See merge request nodeblocks/nodeblocks-backend-sdk!254
- Updated
Blocks
- MongoDB: New MongoDB blocks module with database utility functions
findResources: Retrieves multiple documents from MongoDB collections with error handlingbuildWithoutMongoIdFindOptions: Creates projection options to exclude _id field from query results
- Identity:
buildIdentityIdFilter: Builds identity ID filter objects for database queries - Profile:
ProfileDbBlockError: Database operation error class for profile-related database failures - User:
findProfiles: Retrieves multiple profile documents from MongoDB with standardized error handling
Features
- User:
findProfilesByIdentityIdFeature: User profile retrieval by identity ID with schema validation and routing
Routes
- User:
findProfilesByIdentityIdRoute: GET/profiles/identities/:identityIdwith profile retrieval and avatar processing
Schemas
- Identity:
findByIdentityIdSchema: Identity retrieval by ID schema with path parameter and pagination validation
Services
- User: Added
findProfilesByIdentityIdFeatureto user service for profile retrieval by identity ID - Product: Added
findProductsByOrganizationIdFeatureto product service for organization-scoped product retrieval with pagination and image normalization - Product: Added
getProductLikersFeatureto product service for retrieving users who liked specific products with avatar normalization and admin authorization
Primitives
- Error: Added
ErrorConstructorandBlockErrorConstructortype definitions for consistent error handling
Chat
- Message Templates: New listing functionality for chat message templates
findChatMessageTemplates: Finds chat message templates matching a filter with database error handlingbuildFilterToGetChatMessageTemplatesByOrganizationId: Builds organization-specific filter for template queriesfindChatMessageTemplatesFeature: Complete feature for listing chat message templates with pagination and data normalizationfindChatMessageTemplatesForOrganizationFeature: Organization-scoped message template listing with role-based access controlfindChatMessageTemplatesRoute: GET/message-templatesroute with admin-only access controlfindChatMessageTemplatesForOrganizationRoute: GET/organizations/:organizationId/message-templatesroute with organization role validationfindChatMessageTemplatesSchema: Schema validation for pagination parametersfindChatMessageTemplatesForOrganizationSchema: Schema validation for organization-scoped template retrieval
- Chat Service: Added
findChatMessageTemplatesFeatureandfindChatMessageTemplatesForOrganizationFeatureto chat service for comprehensive message template management
Order Management
- Order Blocks: New order management module with database operations and error handling
OrderBlockError: Base error class for order-related operationsOrderDbBlockError: Database-specific error class for order operationsfindOrders: Retrieves orders with filtering and pagination from MongoDB collections
- Organization Integration: Organization-scoped order management
buildOrganizationIdFilter: Builds organization ID filter objects for database queriesfindByOrganizationIdSchema: Schema validation for organization resource retrieval with pagination
- Order Features: New organization-scoped order retrieval functionality
findOrdersByOrganizationIdFeature: Complete feature for organization-scoped order retrieval with role-based access controlfindOrdersByOrganizationIdRoute: GET/orders/organizations/:organizationIdroute with organization role validation
- Order Service: Enhanced with organization-scoped order retrieval
- Added
findOrdersByOrganizationIdFeatureto order service composition - New endpoint: GET
/orders/organizations/:organizationIdfor organization members (owner/admin/member roles) - Comprehensive role-based access control for multi-tenant order management
- Added
Development
- REPL: Added
ts-node-based REPL for improved TypeScript development experience - Rules: Added Test-Author Agent Prompt for automated testing guidance
Blocks
- Common:
normalizeRawDocument: Raw document normalization utility removing MongoDB_idfield for API responsesnormalizeDocuments: Normalizes an array of raw documents by removing MongoDB_idfields from each document
- Organization:
findChangeRequests: Retrieves change requests for a specific organization from databasenormalizeChangeRequest: Normalizes single change request with file URL enrichmentnormalizeChangeRequests: Normalizes array of change requests with file handling- Error Class:
OrganizationChangeRequestError: Change request operation failures
- Product:
createProductVariant: Creates product variant in MongoDB collection for existing productcreateProductVariantBulk: Creates multiple product variants in bulk within database collectionbuildFilterToGetProductVariantsByIds: Builds database filter to retrieve product variants by their IDs using MongoDB $in operatorfindProductVariants: Product variants retrieval with filter criteria from MongoDB collectionbuildFilterToGetProductVariantsByProductId: Builds database filter to retrieve existing product variants by product IDgetProductVariantById: Retrieves product variant by ID with optional product scopingupdateProductVariant: Updates product variant fields with optional constraintsdeleteProductVariant: Deletes product variant by ID from MongoDB collectiondeleteImagesOfProduct: Deletes all images associated with a product from file storage
- Chat:
generateChatChannelIconUploadUrl: Generates signed upload URLs for chat channel icon imagesnormalizeChatChannel: Normalizes chat channel data with icon file processing for API responses
- File Storage:
normalizeFile: Normalizes file data with signed download URL generation for API responses
- User:
deleteAvatar: Deletes user avatar files from storage system
main
-
Authentication:
- Renamed
normalizeIdentityWithoutPasswordtonormalizeIdentity - Updated return type from
objecttoResult<Record<string, unknown>, never> - Added
normalizeIdentitiesWithoutPasswordfunction for batch normalization - Enhanced security by ensuring password fields are never exposed in API responses
- Renamed
-
OAuth:
- Added email uniqueness validation during Google OAuth signup
- Returns
409 Conflicterror if email already exists during signup flow - Improved error messages for identity not found scenarios
- See merge request nodeblocks/nodeblocks-backend-sdk!258
- Updated
generateRedirectURL: Simplified OAuth redirect URL generation with onetime token parameter
-
Identity:
buildLockIdentityPayload: Creates standardized lock payload for identity securitybuildUnlockIdentityPayload: Creates standardized unlock payload for identity access restoration
Schemas
- Organization:
findChangeRequestsForOrganizationSchema: Change requests retrieval with pagination support
- Identity:
lockIdentitySchema: Identity locking request validation with path parameterunlockIdentitySchema: Identity unlocking request validation with path parameter
- Product:
createProductVariantBulkSchema: Product variant bulk creation schema with array validation and product associationcreateProductVariantSchema: Product variant creation with required title validationfindProductVariantsSchema: Product variants retrieval schema with pagination and product ID validationgetProductVariantSchema: Product variant retrieval with path parametersupdateProductVariantSchema: Product variant update with optional fieldsdeleteProductVariantSchema: Product variant deletion with path parameters
- Chat:
ChatChannelIcon: TypeScript type for chat channel icon metadata- Updated
chatChannelSchema: Added icon field to base channel schema - Updated
createChatChannelSchema: Made icon field required for channel creation - Updated
updateChatChannelSchema: Added icon field support for channel updates
Routes
- Organization:
findChangeRequestsForOrganizationRoute: GET/organizations/:organizationId/change-requestswith pagination and file URL enrichment
- Product:
createProductVariantBulkRoute: POST/product/:productId/variants/bulkfor bulk creating product variantscreateProductVariantRoute: POST/products/:productId/variantsfor variant creationfindProductVariantsRoute: GET/products/:productId/variantsfor listing product variants with paginationgetProductVariantRoute: GET/products/:productId/variants/:productVariantIdfor variant retrievalupdateProductVariantRoute: PATCH/products/:productId/variants/:productVariantIdfor variant updatesdeleteProductVariantRoute: DELETE/products/:productId/variants/:productVariantIdfor variant deletion
- Chat:
getChatChannelIconUploadUrlRoute: GET/channels/:channelId/icon-upload-urlfor generating signed upload URLs for channel icons
Features
- Organization:
findChangeRequestsForOrganizationFeature: Change requests retrieval with pagination and file URL enrichment
- Product:
createProductVariantBulkFeature: Product variants bulk creation with schema validation and routingcreateProductVariantFeature: Product variant creation with validation and normalizationfindProductVariantsFeature: Product variants retrieval with pagination and data normalizationgetProductVariantFeature: Product variant retrieval with validation and normalizationupdateProductVariantFeature: Product variant updates with partial field supportdeleteProductVariantFeature: Product variant deletion with validation
- Chat:
getChannelIconUploadUrlFeature: Chat channel icon upload URL generation with schema validation and routingupdateChatMessageTemplateFeature: Update existing chat message templates with partial data supportupdateChatMessageTemplate: Database block for updating chat message templates with proper validationdeleteChatMessageTemplateFeature: Delete chat message templates with authorization controldeleteChatMessageTemplate: Database block for deleting chat message templates with proper validation
- Identity:
lockIdentityFeature: Identity locking with admin authorization and security controlsunlockIdentityFeature: Identity unlocking with admin authorization for access restoration
🔄 Changed
Development
- REPL: Replaced Babel-based REPL with ts-node for better TypeScript support
- Dependencies: Removed Babel dependencies (
@babel/cli,@babel/core,@babel/node,@babel/plugin-proposal-pipeline-operator,@babel/preset-env) andbabel.config.json - Build: Updated package scripts to use ts-node instead of babel-node
Handlers
- Chat: Updated channel handlers (
updateChatChannel,deleteChatChannel, terminators) to support icon file cleanup and normalization
OAuth
- OAuth Callback Routes: Refactored all OAuth provider callback routes (Google, LINE, Twitter) to use simplified flow with one-time tokens
- Removed
oauthCallbackTokenBehaviorconfiguration option - Updated callback routes to generate and store one-time tokens consistently
- Simplified
generateRedirectURLutility to only handle onetime token redirects
- Removed
Services
- Authentication Service: Updated configuration to remove OAuth callback token behavior and set longer default onetime token expiration
- Removed
oauth.oauthCallbackTokenBehaviorconfiguration option - Updated
onetimeTokenExpireTimedefault from '2h' to '48h'
- Removed
- Identity Service: Enhanced with complete identity lifecycle management including lock/unlock functionality
- Added
lockIdentityFeatureandunlockIdentityFeaturefor account security management - Updated feature naming from plural to singular for consistency (e.g.,
getIdentityFeatures→getIdentityFeature)
- Added
Removed
- User Service: Lock/unlock functionality moved to Identity Service
- Removed
lockUser,unlockUser,lockUserTerminator,unlockUserTerminatorhandlers - Removed
lockUserRoute,unlockUserRouteroutes - Removed
lockUserSchema,unlockUserSchemaschemas - Removed
lockUserFeatures,unlockUserFeaturesfeatures - Migration: Use Identity Service endpoints
POST /identities/:identityId/lockandPOST /identities/:identityId/unlockinstead
- Removed
- Chat: Refactored message normalization functions
- Removed
normalizeAttachmentsOfChatMessage- functionality merged intonormalizeChatMessage - Removed
normalizeAttachmentsOfChatMessages- functionality merged intonormalizeChatMessages - Migration: Use updated
normalizeChatMessageandnormalizeChatMessagesfunctions with async attachment processing
- Removed
Blocks
- Product: Enhanced
createProductVariantBulkto acceptproductIdparameter for automatic product association - Product: Added
updateProductVariantBulkfor bulk updating multiple product variants in single database operation - Product: Added
deleteProductVariantBulkfor bulk deleting multiple product variants with validation - Product: Fixed null safety in
buildFilterToGetProductVariantsByIdswith optional chaining - Product: Added
findProductResourcesfor querying product collections with flexible filtering and thefindResourcesutility - Product: Added
buildProductLikersByLikeProductIdQueryfor building MongoDB filters to find users who liked specific products - Chat: Enhanced
normalizeChatMessageandnormalizeChatMessagesto include async attachment processing with signed URL generation - Chat: Updated
normalizeChatMessageStreamto work with new async normalization functions - Location: Added complete location block module with hierarchical relationship management:
LocationBlockError,LocationNotFoundBlockError,LocationUnexpectedDBErrorerror classesbuildAncestorsFromParentfor ancestor chain constructionbuildLocationToCreatefor location data normalizationgetLocationByIdfor location retrievalcreateLocationfor location persistence
- Location: Enhanced location block module with deletion support and hierarchy validation:
LocationConflictErrorfor hierarchy constraint conflictsbuildDescendantsFilterfor finding descendant locations in hierarchyassertNoDescendantLocationsfor validating no child locations existdeleteLocationfor location deletion with validationfindLocationsfor flexible location querying with automatic field projectionnormalizeLocationfor transforming internal MongoDB fields to API-friendly format
Routes
- Product: Updated
deleteProductRouteto include automatic image cleanup when products are deleted - Product: Updated
createProductVariantBulkRouteto acceptproductIdas path parameter instead of in request body - Product: Added
updateProductVariantBulkRoutefor PATCH/product/:productId/variants/bulkbulk update endpoint - Product: Added
deleteProductVariantBulkRoutefor POST/product/:productId/variants/bulk-deletebulk deletion endpoint - Product: Added
findProductsByOrganizationIdRoutefor GET/products/organizations/:organizationIdorganization-scoped product retrieval - Product: Added
getProductLikersRoutefor GET/products/:productId/likersproduct likers retrieval with avatar normalization - Location: Added
createLocationRoutefor POST/locationswith hierarchical parent support and ancestor building - Location: Added
getLocationRoutefor GET/locations/:locationIdwith public access and location lookup - Location: Added
deleteLocationRoutefor DELETE/locations/:locationIdwith hierarchy validation and admin authentication - Location: Added
findLocationsRoutefor GET/locationswith pagination support and public access - Location: Added
updateLocationRoutefor PATCH/locations/:locationIdwith admin authentication and partial updates
Schemas
- Product: Updated
createProductVariantBulkSchemato validateproductIdpath parameter and remove productId from individual variant items - Product: Added
updateProductVariantBulkSchemafor bulk product variant update validation - Product: Added
deleteProductVariantBulkSchemafor bulk product variant deletion validation - Product: Added
getProductLikersSchemafor product likers retrieval with product ID path parameter validation - Location: Added complete location schema module:
locationSchemabase schema with core location propertiescreateLocationSchemafor location creation validation with parent supportgetLocationSchemafor location retrieval validation with path parametersupdateLocationSchemafor location update validation with optional fieldsdeleteLocationSchemafor location deletion validation with path parametersfindLocationsSchemafor location search validation with pagination parameters
Features
- Product: Updated
createProductVariantBulkFeatureto use path parameter for product association - Product: Added
updateProductVariantBulkFeaturefor bulk product variant updates with validation and routing - Product: Added
deleteProductVariantBulkFeaturefor bulk product variant deletions with validation and routing - Product: Added
findProductsByOrganizationIdFeaturefor organization-scoped product retrieval with image normalization and pagination - Product: Added
getProductLikersFeaturefor retrieving users who liked specific products with avatar normalization and pagination - Location: Added
createLocationFeaturefor hierarchical location creation with parent-child relationships - Location: Added
getLocationFeaturefor location retrieval with schema validation and public routing - Location: Added
updateLocationFeaturefor location update with schema validation and admin routing - Location: Added
deleteLocationFeaturefor location deletion with schema validation and hierarchy validation routing - Location: Added
findLocationsFeaturefor location search with schema validation and pagination routing - User: Updated
deleteUserRouteto include automatic avatar cleanup when users are deleted
Services
Organization Service: Enhanced with change requests retrieval functionality- Added
findChangeRequestsForOrganizationFeaturefor retrieving organization change requests - Added
organizationChangeRequestscollection (optional) for change request storage
- Added
Location Service: Added new hierarchical location management service- Complete location CRUD with parent-child relationships and ancestor tracking
- Support for multiple location types (ORGANIZATION, REGION, CITY, BUILDING)
- Admin-only access control with comprehensive error handling
- Added GET
/organizations/:organizationId/change-requestsendpoint with pagination - Change requests include automatic certificate image URL generation
Product Service: Enhanced with complete product variant management- Added
createProductVariantFeaturefor creating product variants - Added
getProductVariantFeaturefor retrieving individual variants - Added
updateProductVariantFeaturefor partial variant updates - Added
deleteProductVariantFeaturefor variant deletion - Added
productVariantscollection (optional) for variant storage - Added POST
/products/:productId/variantsfor variant creation - Added GET
/products/:productId/variants/:productVariantIdfor variant retrieval - Added PATCH
/products/:productId/variants/:productVariantIdfor variant updates - Added DELETE
/products/:productId/variants/:productVariantIdfor variant deletion - Variants include automatic MongoDB
_idfield removal in responses
- Added
Blocks
- Product:
- Modified
createProductVariantto usecreateBaseEntityWithDelFlgfor consistent entity creation - Enhanced variant CRUD operations with proper error handling and validation
- Modified
2025-10-24
🐞 Fixed
Timestamp Consistency
- Added missing timestamps to database operations: Fixed inconsistency where
createdAtandupdatedAttimestamps were not automatically added/updated in all database write operations- Updated
createChatMessageAttachmentto includeupdatedAttimestamp when adding attachments to messages array - Updated
createProductImageto includeupdatedAttimestamp when adding images to products array - Updated
deleteOrganizationMemberto includeupdatedAttimestamp when removing members from organization - All create operations now consistently use
createBaseEntity()helper for automatic timestamp generation - All update operations now consistently use
updateBaseEntity()helper for automatic timestamp updates - Ensures data integrity and proper audit trail for all entity modifications
- See merge request nodeblocks/nodeblocks-backend-sdk!276
- Updated
🍱 Refactor
File Deletion Error Handling
- Refactored deleteFile error handling: Simplified error propagation by directly returning
FileStorageServiceErrorinstead of wrapping in module-specific errors- Updated Avatar Blocks:
deleteAvatarIfReplaced- Now returnsResult<T, FileStorageServiceError>instead ofAvatarBlockError
- Updated User Blocks:
deleteAvatar- Now returnsResult<true, FileStorageServiceError>instead ofUserBlockError
- Updated Organization Blocks:
- Removed
deleteLogoIfReplacedfunction (replaced by directdeleteFileusage in handlers) deleteLogoOfOwner- Now returnsResult<true, FileStorageServiceError>instead ofOrganizationBlockError
- Removed
- Updated Product Blocks:
deleteImagesOfProduct- Now returnsResult<true, FileStorageServiceError | ProductNotFoundBlockError | ProductUnexpectedDBError>and usesResult.combinefor parallel file deletion error handling
- Updated Chat Channel Handlers:
updateChatChannel- Refactored to useResulttypes andmapfor cleaner error compositiondeleteChatChannel- Refactored to useResulttypes andmapfor cleaner error composition
- Updated User Routes:
updateUserRoute- AddedFileStorageServiceErrorto error responses (500 status)
- Updated Product Routes:
deleteProductRoute- IncludesFileStorageServiceErrorin error responses (500 status)
- Rationale: Cleaner error propagation, better type safety, and more consistent error handling patterns across the SDK
- Benefits: Callers receive storage-specific errors directly without unnecessary wrapping, enabling better error handling decisions
- See merge request nodeblocks/nodeblocks-backend-sdk!279
- Updated Avatar Blocks:
2025-10-15
🍱 Refactor
Logger Parameter Removal
- Removed logger parameter from block functions: Systematic refactoring to remove logger parameter from block functions across the SDK
- Refactored User Blocks:
getUserById- Removed logger parameterdeleteAvatar- Removed logger parameter
- Refactored Profile Blocks:
normalizeFollowers- Removed logger parameter
- Refactored File Storage Blocks:
generateSignedUploadUrl- Removed logger parametergenerateSignedDownloadUrl- Removed logger parametergenerateSignedDeleteUrl- Removed logger parametergenerateSignedAvatarUploadUrl- Removed logger parametergenerateFileUploadUrl- Removed logger parameterdeleteFile- Removed logger parameternormalizeFile- Removed logger parameter
- Refactored Avatar Blocks:
normalizeAvatarOfOwner- Removed logger parameternormalizeAvatarsOfOwners- Removed logger parameterdeleteAvatarIfReplaced- Removed logger parameter
- Refactored Organization Blocks:
normalizeCertificateImage- Removed logger parameternormalizeCertificateImages- Removed logger parameternormalizeLogoOfOwner- Removed logger parameternormalizeLogosOfOwners- Removed logger parameternormalizeLogosOfPaginatedOwners- Removed logger parameterdeleteLogoIfReplaced- Removed logger parameter (function later removed in 2025-10-24)deleteLogoOfOwner- Removed logger parameternormalizeChangeRequest- Removed logger parameternormalizeChangeRequests- Removed logger parameter
- Refactored Product Blocks:
generateProductImageUploadUrl- Removed logger parametercreateProductImage- Removed logger parametergetProductById- Removed logger parametergetProductImageById- Removed logger parameterfindProducts- Removed logger parameternormalizeProductImage- Removed logger parameternormalizeImagesOfProduct- Removed logger parameternormalizeImagesOfProducts- Removed logger parameterdeleteProductImage- Removed logger parameterdeleteImagesOfProduct- Removed logger parameter
- Refactored Chat Blocks:
generateChatChannelIconUploadUrl- Removed logger parameternormalizeChatChannel- Removed logger parameterfindChatMessages- Removed logger parametercreateChatMessage- Removed logger parametergetChatMessageById- Removed logger parameternormalizeChatMessage- Removed logger parameternormalizeChatMessages- Removed logger parameternormalizeChatMessageAttachment- Removed logger parameternormalizeChatMessageStream- Removed logger parametergenerateChatMessageAttachmentUploadUrl- Removed logger parametercreateChatMessageAttachment- Removed logger parametergetChatMessageAttachmentById- Removed logger parameterdeleteChatMessageAttachment- Removed logger parameter
- Updated route compositions to remove
['logger']fromapplyPayloadArgscalls:- Updated Profile Routes
- Updated Organization Routes
- Rationale: Simplified function signatures by removing logger dependency; error handling now uses try-catch without explicit logging
- See merge request nodeblocks/nodeblocks-backend-sdk!d3bb0f2d
- Refactored User Blocks:
2025-10-10
2025-09-11
🎥 Demo Video
📹 NodeBlocks Backend SDK v0.6.0 Demo - Complete walkthrough of all new features and functionality
✨ Added
Blocks
- Chat:
createChatMessageTemplate: Create new chat message templates with organization access controlgetChatMessageTemplateById: Retrieve specific message template by ID with validationcreateChatChannelReadState: Create chat channel read state entities in the databaseupdateChatChannelReadState: Update existing chat channel read statesfindChatChannelReadStates: Find chat channel read states with filter criteriabuildChatChannelReadStateQuery: Build query objects for finding read states by channel and identitybuildLastReadMessageQuery: Build query objects for finding last read messagesbuildCreateChatChannelReadStatePayload: Build payload for creating read state entitiesbuildUpdateChatChannelReadStatePayload: Build payload for updating read state entities- Error Classes:
ChatMessageBlockError,ChatMessageDbError,ChatMessageUnauthorizedError,ChatMessageForbiddenError,ChatMessageNotFoundError,ChatMessageInvalidMessageError,ChatMessageUnknownError,ChatMessageBadRequestError,ChatChannelReadStateBlockError,ChatChannelReadStateNotFoundError,ChatChannelReadStateDatabaseError,ChatChannelReadStateUnknownError
- Chat:
createChatMessage: Creates new chat messages with attachments and automatic base entity generationgetChatMessageById: Retrieves chat messages by unique identifiernormalizeChatMessage: Normalizes single message by removing MongoDB _id field and processing attachments with signed URLsnormalizeChatMessages: Normalizes multiple messages by removing MongoDB _id fields and processing attachmentsnormalizeChatMessageAttachment: Normalizes attachment with signed download URLgenerateChatMessageAttachmentUploadUrl: Generates signed upload URLs for chat message attachments with security filteringcreateChatMessageAttachment: Adds attachments to existing messages with automatic base entity generationgetChatMessageAttachmentById: Retrieves specific attachments from messages by IDdeleteChatMessageAttachment: Deletes attachments from messages and removes files from storage- Error Classes:
ChatMessageNotFoundBlockError,ChatMessageUnexpectedDBError,ChatMessageAttachmentNotFoundBlockError
- Product:
getProductById: Retrieves a product by ID from the products collection with error handlingfindProducts: Retrieves products from database collection based on filter criterianormalizeProduct: Normalizes a single product by removing _id field from product entitynormalizeProducts: Normalizes multiple products by removing _id field from each product entitynormalizeProductImage: Normalizes a single product image by generating signed download URLnormalizeImagesOfProduct: Normalizes images for a single product with signed URLsnormalizeImagesOfProducts: Normalizes images for multiple products with signed URLs
- OAuth:
requestLineOAuth: Initiates LINE OAuth authentication flow with state token generationauthenticateLineOAuth: Authenticates LINE user by invoking provider callbackverifyLineOAuth: Verifies LINE OAuth profile and resolves or creates identity
- Utils:
BaseEntity: TypeScript type definition with id, createdAt, and updatedAt fields
Schemas
- Chat:
createChatMessageTemplateSchema: Validate template creation requestsgetChatMessageTemplateSchema: Validate template ID path parameters
Routes
- Chat:
createChatMessageTemplateRoute: POST/message-templates- Create message templatesgetChatMessageTemplateRoute: GET/message-templates/:messageTemplateId- Get template by ID
Features
- Chat:
createChatMessageTemplateFeature: Composed workflow for template creationgetChatMessageTemplateFeature: Composed workflow for template retrieval
Drivers
- OAuth:
createTwitterOAuthDriver: Configure Passport strategy for Twitter OAuthverifyTwitterCallback: Passport verify callback for Twitter OAuth
Validators
- Chat:
hasOrganizationAccessToMessageTemplate: Validate organization access to message templates
Utilities
- RxJS:
notFromEmitter: RxJS predicate to filter messages from specific emitter instancesmarkAsFromEmitter: Mark messages as originating from specific emitter instances
🔄 Changed
Services
Authentication Service: Added Twitter OAuth support and refresh token functionality- Added
twitterOAuthDriverparameter to service configuration - Added Twitter OAuth endpoints to route composition
- Enhanced refresh token system with soft delete functionality
- Updated datastore configuration to include
chatMessageTemplatescollection
- Added
Primitives
- Service Infrastructure:
- Enhanced
defServiceto support WebSocket server integration - Added WebSocket route handling with RxJS bridging for real-time communication
- Implemented WebSocket connection management with emitter-based message filtering
- Added support for
protocol: 'ws'routes alongside HTTP routes
- Enhanced
Route Definitions:
- WebSocket Routing:
- Added
withRoutesupport for WebSocket protocol routes - Enabled
protocol: 'ws'option for defining WebSocket endpoints - Integrated WebSocket handlers with the existing route composition system
- Added
Blocks
- Chat:
- Enhanced message template blocks with organization-based access control
- Added soft delete functionality for template management
- Improved validation and error handling for template operations
Drivers
- OAuth:
createGoogleOAuthDriver: Enhanced with multi-provider support- Added Twitter OAuth driver integration
- Improved session-based state management for OAuth flows
Validators
- Chat:
- Enhanced organization access validators for message templates
- Improved error handling and validation messages
🐞 Fixed
Services
Authentication Service:- Fixed refresh token route validation (removed isAuthenticated validator)
- Corrected configuration property names (
user.typeIds→identity.typeIds) - Fixed type definitions (
user?: string→regular?: string) - Updated all service quickstart examples with correct property names
Drivers
- File Storage:
- Fixed Google Cloud storage testing mock implementation
- Improved cross-platform compatibility for test environments
Blocks
- Organization:
- Fixed missing organization blocks export issue
- Improved module organization and exports
Configuration
- Fixed property name inconsistencies across all services:
user.typeIds→identity.typeIdsin configuration interfacesuser?: string→regular?: stringin type definitions- Updated all example configurations and documentation