Skip to main content
Version: 0.9.0 (Latest)

Changelog

2025-11-07

🔄 Changed

⚠️ Breaking Changes

  • Chat Channels: createChatChannelSchema no longer requires icon field - channels can be created without specifying an icon (previously required)

Blocks

Schemas

Routes

  • Product: createProductRoute and createProductBatchRoute: Updated to use simplified normalization functions without image processing
  • Chat: Removed ProductBlockError and ChatMessageBlockError from 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 deletedAt timestamp 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 deletedAt field

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) and String(identityId) for consistent ID handling
  • Product Operations: Batch operations now use productIds.map(String) for $in queries
  • 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/:followProfileId endpoint
    • Authorization: Requires admin role or profile ownership
    • Returns 204 No Content on successful deletion
    • Returns 404 Not Found if profile or follow relationship doesn't exist
    • See merge request nodeblocks/nodeblocks-backend-sdk!261
  • 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/followers endpoint
    • Authorization: Requires admin role or profile ownership
    • Returns 200 OK with paginated follower list and normalized avatar URLs
    • Supports pagination with query parameters (page, limit)
    • Returns 404 Not Found if profile doesn't exist
    • See merge request nodeblocks/nodeblocks-backend-sdk!232
  • Create Organization Follow: Added ability to create organization follow relationships

  • 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/:followOrganizationId endpoint
    • Authorization: Requires admin role or profile ownership
    • Returns 204 No Content on successful deletion
    • Returns 404 Not Found if 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
  • 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 users collection for follower data access
    • Authorization: Requires admin role or organization ownership
    • Returns 200 OK with paginated follower list and normalized avatar URLs
    • Supports pagination with query parameters (page, limit)
    • Returns 404 Not Found if organization doesn't exist
    • Reuses profile blocks (findProfiles, normalizeFollowers) for consistency
    • See merge request nodeblocks/nodeblocks-backend-sdk!246

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/:likeProductId endpoint
    • Updated User Service to require products collection for product validation
    • Authorization: Requires admin role or profile ownership
    • Returns 201 Created on successful creation
    • Returns 409 Conflict if product is already liked
    • Returns 404 Not Found if profile or product doesn't exist
    • Duplicate prevention using MongoDB $ne operator
    • See merge request nodeblocks/nodeblocks-backend-sdk!240
  • 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/:likeProductId endpoint
    • Authorization: Requires admin role or profile ownership
    • Returns 204 No Content on successful deletion
    • Returns 404 Not Found if 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

🐞 Fixed

Security

  • Identity Service: Removed password field from identity endpoint responses for enhanced security

Blocks

  • MongoDB: New MongoDB blocks module with database utility functions
  • 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

Routes

Schemas

  • Identity: findByIdentityIdSchema: Identity retrieval by ID schema with path parameter and pagination validation

Services

  • User: Added findProfilesByIdentityIdFeature to user service for profile retrieval by identity ID
  • Product: Added findProductsByOrganizationIdFeature to product service for organization-scoped product retrieval with pagination and image normalization
  • Product: Added getProductLikersFeature to product service for retrieving users who liked specific products with avatar normalization and admin authorization

Primitives

  • Error: Added ErrorConstructor and BlockErrorConstructor type definitions for consistent error handling

Chat

Order Management

  • Order Blocks: New order management module with database operations and error handling
    • OrderBlockError: Base error class for order-related operations
    • OrderDbBlockError: Database-specific error class for order operations
    • findOrders: Retrieves orders with filtering and pagination from MongoDB collections
  • Organization Integration: Organization-scoped order management
  • Order Features: New organization-scoped order retrieval functionality
  • Order Service: Enhanced with organization-scoped order retrieval
    • Added findOrdersByOrganizationIdFeature to order service composition
    • New endpoint: GET /orders/organizations/:organizationId for organization members (owner/admin/member roles)
    • Comprehensive role-based access control for multi-tenant order management

Development

  • REPL: Added ts-node-based REPL for improved TypeScript development experience
  • Rules: Added Test-Author Agent Prompt for automated testing guidance

Blocks

main

  • Authentication:

    • Renamed normalizeIdentityWithoutPassword to normalizeIdentity
    • Updated return type from object to Result<Record<string, unknown>, never>
    • Added normalizeIdentitiesWithoutPassword function for batch normalization
    • Enhanced security by ensuring password fields are never exposed in API responses
  • OAuth:

    • Added email uniqueness validation during Google OAuth signup
    • Returns 409 Conflict error 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:

Schemas

Routes

Features

🔄 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) and babel.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 oauthCallbackTokenBehavior configuration option
    • Updated callback routes to generate and store one-time tokens consistently
    • Simplified generateRedirectURL utility to only handle onetime token redirects

Services

  • Authentication Service: Updated configuration to remove OAuth callback token behavior and set longer default onetime token expiration
    • Removed oauth.oauthCallbackTokenBehavior configuration option
    • Updated onetimeTokenExpireTime default from '2h' to '48h'
  • Identity Service: Enhanced with complete identity lifecycle management including lock/unlock functionality
    • Added lockIdentityFeature and unlockIdentityFeature for account security management
    • Updated feature naming from plural to singular for consistency (e.g., getIdentityFeaturesgetIdentityFeature)

Removed

  • User Service: Lock/unlock functionality moved to Identity Service
    • Removed lockUser, unlockUser, lockUserTerminator, unlockUserTerminator handlers
    • Removed lockUserRoute, unlockUserRoute routes
    • Removed lockUserSchema, unlockUserSchema schemas
    • Removed lockUserFeatures, unlockUserFeatures features
    • Migration: Use Identity Service endpoints POST /identities/:identityId/lock and POST /identities/:identityId/unlock instead
  • Chat: Refactored message normalization functions
    • Removed normalizeAttachmentsOfChatMessage - functionality merged into normalizeChatMessage
    • Removed normalizeAttachmentsOfChatMessages - functionality merged into normalizeChatMessages
    • Migration: Use updated normalizeChatMessage and normalizeChatMessages functions with async attachment processing

Blocks

Routes

Schemas

Features

Services

  • Organization Service: Enhanced with change requests retrieval functionality
    • Added findChangeRequestsForOrganizationFeature for retrieving organization change requests
    • Added organizationChangeRequests collection (optional) for change request storage
  • 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-requests endpoint with pagination
    • Change requests include automatic certificate image URL generation
  • Product Service: Enhanced with complete product variant management
    • Added createProductVariantFeature for creating product variants
    • Added getProductVariantFeature for retrieving individual variants
    • Added updateProductVariantFeature for partial variant updates
    • Added deleteProductVariantFeature for variant deletion
    • Added productVariants collection (optional) for variant storage
    • Added POST /products/:productId/variants for variant creation
    • Added GET /products/:productId/variants/:productVariantId for variant retrieval
    • Added PATCH /products/:productId/variants/:productVariantId for variant updates
    • Added DELETE /products/:productId/variants/:productVariantId for variant deletion
    • Variants include automatic MongoDB _id field removal in responses

Blocks

  • Product:
    • Modified createProductVariant to use createBaseEntityWithDelFlg for consistent entity creation
    • Enhanced variant CRUD operations with proper error handling and validation

2025-10-24

🐞 Fixed

Timestamp Consistency

  • Added missing timestamps to database operations: Fixed inconsistency where createdAt and updatedAt timestamps were not automatically added/updated in all database write operations
    • Updated createChatMessageAttachment to include updatedAt timestamp when adding attachments to messages array
    • Updated createProductImage to include updatedAt timestamp when adding images to products array
    • Updated deleteOrganizationMember to include updatedAt timestamp 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

🍱 Refactor

File Deletion Error Handling

  • Refactored deleteFile error handling: Simplified error propagation by directly returning FileStorageServiceError instead of wrapping in module-specific errors
    • Updated Avatar Blocks:
    • Updated User Blocks:
      • deleteAvatar - Now returns Result<true, FileStorageServiceError> instead of UserBlockError
    • Updated Organization Blocks:
      • Removed deleteLogoIfReplaced function (replaced by direct deleteFile usage in handlers)
      • deleteLogoOfOwner - Now returns Result<true, FileStorageServiceError> instead of OrganizationBlockError
    • Updated Product Blocks:
      • deleteImagesOfProduct - Now returns Result<true, FileStorageServiceError | ProductNotFoundBlockError | ProductUnexpectedDBError> and uses Result.combine for parallel file deletion error handling
    • Updated Chat Channel Handlers:
      • updateChatChannel - Refactored to use Result types and map for cleaner error composition
      • deleteChatChannel - Refactored to use Result types and map for cleaner error composition
    • Updated User Routes:
      • updateUserRoute - Added FileStorageServiceError to error responses (500 status)
    • Updated Product Routes:
      • deleteProductRoute - Includes FileStorageServiceError in 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

2025-10-15

🍱 Refactor

Logger Parameter Removal


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

Schemas

Routes

Features

Drivers

Validators

Utilities

  • RxJS:
    • notFromEmitter: RxJS predicate to filter messages from specific emitter instances
    • markAsFromEmitter: Mark messages as originating from specific emitter instances

🔄 Changed

Services

  • Authentication Service: Added Twitter OAuth support and refresh token functionality
    • Added twitterOAuthDriver parameter to service configuration
    • Added Twitter OAuth endpoints to route composition
    • Enhanced refresh token system with soft delete functionality
    • Updated datastore configuration to include chatMessageTemplates collection

Primitives

  • Service Infrastructure:
    • Enhanced defService to 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

Route Definitions:

  • WebSocket Routing:
    • Added withRoute support for WebSocket protocol routes
    • Enabled protocol: 'ws' option for defining WebSocket endpoints
    • Integrated WebSocket handlers with the existing route composition system

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.typeIdsidentity.typeIds)
    • Fixed type definitions (user?: stringregular?: 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.typeIdsidentity.typeIds in configuration interfaces
    • user?: stringregular?: string in type definitions
    • Updated all example configurations and documentation