🚀 Organization Features
Organization features provide complete, pre-composed functionality for organization management operations in Nodeblocks applications. These features combine schemas, routes, and handlers to create ready-to-use API endpoints for organization CRUD operations, user management, and membership handling.
🎯 Overview
Organization features are designed to:
- Provide complete organization management with full CRUD operations
- Support user membership and role management within organizations
- Include validation and routing for secure organization operations
- Support filtering and pagination for organization and user listings
- Handle organization-user relationships and access control
📋 Feature Structure
Each organization feature follows a consistent composition pattern:
- Schema: Validates organization input data and parameters
- Route: Provides HTTP endpoint with organization handlers
- Composition: Combines schema and route using
composefunction
🔧 Available Organization Features
createOrganizationFeature
Organization creation feature with schema validation and routing.
Purpose: Handles organization creation with complete validation
Composition:
- Schema:
createOrganizationSchema- validates name, description, contact_email, and optional fields - Route:
createOrganizationRoute- POST/organizationswith creation handler
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.createOrganizationFeature, [{ dataStores: db }])));
API Endpoint: POST /api/organizations
getOrganizationFeatures
Organization retrieval feature for getting individual organization data.
Purpose: Fetches organization information with proper validation
Composition:
- Schema:
getOrganizationSchema- validates path parameters - Route:
getOrganizationRoute- GET/organizations/:organizationIdwith retrieval handler
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.getOrganizationFeatures, [{ dataStores: db }])));
API Endpoint: GET /api/organizations/:organizationId
findOrganizationsFeatures
Organization search feature with filtering and pagination.
Purpose: Provides organization listing with search capabilities
Composition:
- Schema:
findOrganizationsSchema- validates query parameters for filtering - Route:
findOrganizationsRoute- GET/organizationswith search and pagination
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.findOrganizationsFeatures, [{ dataStores: db }])));
API Endpoint: GET /api/organizations
editOrganizationFeatures
Organization update feature with schema validation and routing.
Purpose: Modifies organization information with proper validation
Composition:
- Schema:
updateOrganizationSchema- validates partial organization properties - Route:
updateOrganizationRoute- PATCH/organizations/:organizationIdwith update handler
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.editOrganizationFeatures, [{ dataStores: db }])));
API Endpoint: PATCH /api/organizations/:organizationId
deleteOrganizationFeatures
Organization deletion feature with routing.
Purpose: Removes organizations with access control and cleanup
Composition:
- Schema:
deleteOrganizationSchema- validates path parameters - Route:
deleteOrganizationRoute- DELETE/organizations/:organizationIdwith deletion handler
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.deleteOrganizationFeatures, [{ dataStores: db }])));
API Endpoint: DELETE /api/organizations/:organizationId
getOrganizationMemberFeatures
Organization member role retrieval feature for getting member roles within organizations.
Purpose: Retrieves member roles within specific organizations
Composition:
- Schema:
getOrganizationMemberRoleSchema- validates path parameters - Route:
getOrganizationMemberRoleRoute- GET/organizations/:organizationId/members/:identityId/rolewith role retrieval handler
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.getOrganizationMemberFeatures, [{ dataStores: db }])));
API Endpoint: GET /api/organizations/:organizationId/members/:identityId/role
checkOrganizationMemberExistenceFeatures
Organization member existence check feature for validating member membership.
Purpose: Validates member membership in organizations
Composition:
- Schema:
checkOrganizationMemberExistenceSchema- validates path and query parameters - Route:
checkOrganizationMemberExistenceRoute- GET/organizations/:organizationId/members/check-existence
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.checkOrganizationMemberExistenceFeatures, [{ dataStores: db }])));
API Endpoint: GET /api/organizations/:organizationId/members/check-existence
findOrganizationMembersFeatures
Organization members search feature with filtering and pagination.
Purpose: Provides organization member listing with search capabilities
Composition:
- Schema:
findOrganizationMembersSchema- validates query parameters for filtering - Route:
findOrganizationMembersRoute- GET/organizations/:organizationId/memberswith search and pagination
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.findOrganizationMembersFeatures, [{ dataStores: db }])));
API Endpoint: GET /api/organizations/:organizationId/members
findOrganizationsForMemberFeatures
Organizations for member search feature for finding organizations by identity ID.
Purpose: Finds organizations associated with a specific member (identity), with optional role filtering and inherited roles
Composition:
- Schema:
findOrganizationsForMemberSchema- validates path and optional query parameters - Route:
findOrganizationsForMemberRoute- GET/organizations/members/:identityId
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.findOrganizationsForMemberFeatures, [{ dataStores: db }])));
API Endpoint: GET /api/organizations/members/:identityId
editOrganizationMembersFeatures
Organization member management feature with schema validation for upserting members.
Purpose: Manages member membership and roles within organizations
Composition:
- Schema:
upsertOrganizationMembersSchema- validates array of member objects with id and role - Route:
upsertOrganizationMembersRoute- PATCH/organizations/:organizationId/memberswith upsert handler
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.editOrganizationMembersFeatures, [{ dataStores: db }])));
API Endpoint: PATCH /api/organizations/:organizationId/members
deleteOrganizationMemberFeatures
Organization member deletion feature with routing.
Purpose: Removes members from organizations with proper cleanup
Composition:
- Schema:
deleteOrganizationMemberSchema- validates path parameters - Route:
deleteOrganizationMemberRoute- DELETE/organizations/:organizationId/members/:identityId
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.deleteOrganizationMemberFeatures, [{ dataStores: db }])));
API Endpoint: DELETE /api/organizations/:organizationId/members/:identityId
findOrganizationDescendantsFeatures
Retrieves descendant organizations for a given organization.
Purpose: Lists all descendants with pagination support
Composition:
- Schema:
findOrganizationDescendantsSchema- validates organizationId and optional depth - Route:
findOrganizationDescendantsRoute- GET/organizations/:organizationId/descendants
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With database configuration
app.use('/api', defService(partial(features.findOrganizationDescendantsFeatures, [{ dataStores: db }])));
API Endpoint: GET /api/organizations/:organizationId/descendants
getCertificateUploadUrlFeature
Organization certificate upload URL generation feature with schema validation and routing.
Purpose: Provides secure signed URLs for certificate file uploads
Composition:
- Schema:
getCertificateUploadUrlSchema- validates content type and file size for certificate uploads - Route:
getCertificateUploadUrlRoute- GET/organizations/:organizationId/certificate-upload-urlwith signed URL generation
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With file storage service in configuration:
app.use('/api', defService(partial(features.getCertificateUploadUrlFeature, [{ configuration: { fileStorageDriver } }])));
API Endpoint: GET /api/organizations/:organizationId/certificate-upload-url?contentType=application/pdf&contentLength=102400
Key Features:
- Automatic UUID object ID generation
- Support for PDF and image formats (PDF, GIF, JPEG, PNG)
- File size validation (max 10MB)
- Owner-only access control
createChangeRequestFeature
Organization change request creation feature with schema validation and routing.
Purpose: Handles organization change requests with validation, audit tracking, and automatic status updates
Composition:
- Schema:
createChangeRequestSchema- validates organizationId path and JSON body fields (name, address lines, typeId, certificateImage, certifiedQualifications) - Route:
createChangeRequestRoute- POST/organizations/:organizationId/change-requestswith creation handler
Usage:
import { features } from '@nodeblocks/backend-sdk';
// Direct usage with DB and auth secrets:
app.use('/api', defService(partial(features.createChangeRequestFeature, [{
dataStores: {
organizations: db.collection('organizations'),
organizationChangeRequests: db.collection('organizationChangeRequests'),
onetimetokens: db.collection('onetimetokens')
},
configuration: { authSecrets }
}])));
API Endpoint: POST /api/organizations/:organizationId/change-requests
Request Body:
{
"name": "Updated Organization Name",
"addressLine1": "123 Main Street",
"certificateImage": {
"objectId": "uuid-here",
"type": "application/pdf"
},
"certifiedQualifications": [
{
"name": "ISO 9001",
"status": "approved",
"value": "2024"
}
]
}
Response: 204 No Content - Empty response body on success
Key Features:
- Automatic organization name uniqueness validation
- Token-based identity extraction for authorship tracking
- Automatic audit status update to
waiting_for_review - Certificate image upload support with objectId references
- Certified qualifications tracking with structured data
- Comprehensive error handling with specific error classes
- Owner-only access control
Error Responses:
400 Bad Request- Invalid input, duplicate name, or validation failure401 Unauthorized- Authentication failed500 Internal Server Error- Database or processing errors
Workflow:
- Validates organization exists and user has owner role
- Checks organization name uniqueness if name change requested
- Extracts identity from access token
- Creates change request record with all submitted fields
- Updates organization audit status to
waiting_for_review - Returns 204 No Content on success
findChangeRequestsForOrganizationFeature
Organization change requests retrieval feature with schema validation and routing.
Purpose: Retrieves and normalizes organization change requests with pagination and file URL enrichment
Composition:
- Schema:
findChangeRequestsForOrganizationSchema- validates organization ID and pagination parameters - Route:
findChangeRequestsForOrganizationRoute- GET/organizations/:organizationId/change-requestswith retrieval and normalization handler
Usage:
import { features } from '@nodeblocks/backend-sdk';
// Direct usage:
app.use('/api', defService(features.findChangeRequestsForOrganizationFeature));
// With database and file storage (handlers need dataStores and fileStorageDriver):
app.use('/api', defService(partial(features.findChangeRequestsForOrganizationFeature, [{
dataStores: {
organizationChangeRequests: db.collection('organizationChangeRequests')
},
configuration: {
fileStorageDriver
}
}])));
API Endpoint: GET /api/organizations/:organizationId/change-requests
Query Parameters:
{
page?: number; // optional - pagination page (default: 1)
limit?: number; // optional - pagination limit (default: 10, max: 50)
}
Response: 200 OK - Returns paginated change requests with normalized data
Response Format:
{
"data": [
{
"id": "string",
"organizationId": "string",
"identityId": "string",
"name": "string",
"certificateImage": {
"objectId": "string",
"type": "string"
},
"certificateImageUrl": "string",
"createdAt": "string",
"updatedAt": "string"
}
],
"metadata": {
"pagination": {
"page": 1,
"limit": 10,
"total": 25,
"totalPages": 3,
"hasNext": true,
"hasPrev": false
}
}
}
Key Features:
- Pagination support with configurable page size and navigation metadata
- Automatic MongoDB
_idfield removal from responses - Signed download URL generation for certificate images
- Graceful fallback when URL generation fails (returns change request without URL)
- Access control for organization owners and admins only
- Comprehensive error handling with specific error classes
Authorization:
- Requires authentication
- Accessible by admins or organization owners
- Validates organization membership and roles
Error Responses:
401 Unauthorized- Authentication failed403 Forbidden- User lacks admin privileges or organization ownership500 Internal Server Error- Database query failures or file URL generation errors
Use Cases:
- Reviewing pending organization change requests
- Auditing change request history
- Admin oversight of organization modifications
- Client applications displaying change request lists
updateOrganizationAsAdminFeature
Organization admin update feature with schema validation and routing.
Purpose: Provides admin-only organization updates with extended field access and audit status validation
Composition:
- Schema:
updateOrganizationAsAdminSchema- validates admin-only and common fields for partial updates - Route:
updateOrganizationAsAdminRoute- PATCH/admin/organizations/:organizationId/with admin-only update handler
Usage:
import { features } from '@nodeblocks/backend-sdk';
// Direct usage:
app.use('/api', defService(features.updateOrganizationAsAdminFeature));
// With database (handlers need dataStores):
app.use('/api', defService(partial(features.updateOrganizationAsAdminFeature, [{
dataStores: {
organizations: db.collection('organizations')
},
configuration: {
fileStorageDriver
}
}])));
API Endpoint: PATCH /api/admin/organizations/:organizationId/
Request Body:
{
"name": "Updated Organization Name",
"auditStatus": "approved",
"certificateImage": {
"objectId": "uuid-here",
"type": "application/pdf"
},
"certifiedQualifications": [
{
"name": "ISO 9001:2015",
"status": "approved",
"value": "2024"
}
]
}
Response: 200 OK - Returns updated organization with normalized logo URL
Key Features:
- Admin-only access control (requires admin identity type)
- Extended field access including:
- Organization name changes
- Address updates
- Certificate image management
- Certified qualifications tracking
- Logo management
- Type ID updates
- Audit status updates
- Audit status validation (only 'approved' or 'rejected' allowed)
- Automatic logo URL normalization in response
- All common fields available (contact info, description, branch name)
- Flexible partial updates (all fields optional)
- Comprehensive error handling with specific error classes
Authorization:
- Requires admin identity type
- More permissive than regular update route
- Allows updating fields restricted from organization owners
Use Cases:
- Approving or rejecting change requests via
auditStatus - Administrative organization data corrections
- Updating certificate images and qualifications
- Managing organization type classifications
- Direct name changes without change request workflow
Error Responses:
400 Bad Request- Invalid audit status or validation failure401 Unauthorized- Authentication failed403 Forbidden- Non-admin user attempted admin update404 Not Found- Organization not found500 Internal Server Error- Database or processing errors
getLogoUploadUrlFeature
Organization logo upload URL generation feature with schema validation and routing.
Purpose: Generates a pre-signed URL to upload an organization logo.
Composition:
- Schema:
getSignedImageUploadUrlSchema- validates content type and file size for image uploads - Route:
getLogoUploadUrlRoute- GET/organizations/:organizationId/logo-upload-urlwith signed URL generation
Usage:
import { features } from '@nodeblocks/backend-sdk';
// With file storage service in configuration:
app.use(
'/api',
defService(partial(features.getLogoUploadUrlFeature, [{ configuration: { fileStorageDriver } }]))
);
API Endpoint: GET /api/organizations/:organizationId/logo-upload-url
getOrganizationFollowersFeature
Organization followers retrieval feature with schema validation, pagination, and routing.
Purpose: Provides complete organization followers retrieval functionality with validation, pagination, and avatar normalization.
Composition:
- Schema:
getOrganizationFollowersSchema- validates organization followers retrieval request path parameters - Route:
getOrganizationFollowersRoute- GET/organizations/:organizationId/followerswith followers retrieval and pagination
Usage:
import { features } from '@nodeblocks/backend-sdk';
import { defService, partial, compose } from '@nodeblocks/backend-sdk/primitives';
const { getOrganizationFollowersFeature } = features;
// Direct usage:
app.use('/api', defService(getOrganizationFollowersFeature));
// With database configuration:
app.use('/api', defService(
partial(getOrganizationFollowersFeature, [
{ dataStores: { organizations: db.collection('organizations'), users: db.collection('users') } }
])
));
API Endpoint: GET /api/organizations/:organizationId/followers
Response (200 OK):
{
"data": [
{
"id": "user-123",
"name": "John Doe",
"avatar": {
"url": "https://storage.example.com/avatars/avatar123.png",
"type": "image/png"
}
}
],
"metadata": {
"pagination": {
"page": 1,
"limit": 20,
"total": 50,
"totalPages": 3
}
}
}
Key Features:
- Pagination Support: Efficient handling of large follower lists with customizable page size
- Avatar Normalization: Automatic conversion of storage references to accessible URLs
- Authentication & Authorization: Restricts to authenticated users (admins or organization owners)
- Comprehensive Validation: Ensures organization exists and validates request structure
- Detailed Error Handling: Provides clear error responses for various failure scenarios
- Reuses Profile Blocks: Leverages existing findProfiles and normalizeFollowers for consistency
Authorization:
- Requires authentication (
isAuthenticated) - Accessible by admins or organization owners (
some(checkIdentityType(['admin']), hasOrgRole(['owner'])))
Validation Rules:
- Path parameter
organizationIdis required - Organization must exist in the database
- Optional query parameters:
pageandlimitfor pagination control
Error Responses:
400 Bad Request: Invalid request parameters401 Unauthorized: Authentication failed403 Forbidden: Insufficient permissions (not admin or organization owner)404 Not Found: Organization doesn't exist500 Internal Server Error: Database or file storage operation failed
Handler Process:
- Authentication & Authorization: Validates user credentials and organization ownership permissions
- Organization Validation: Ensures the organization exists
- Query Building: Builds MongoDB filter for organization followers
- Followers Retrieval: Finds profiles with pagination using findProfiles
- Avatar Normalization: Converts avatar objectIds to accessible URLs
- Response Formatting: Combines follower data with pagination metadata
- Response: Returns 200 OK with paginated, normalized follower list
Use Cases:
- Organization Analytics: Track follower counts and growth
- Membership Management: View and analyze organization subscribers
- Content Distribution: Support follower-based content delivery
- Community Features: Build organization-centric social features
Data Flow:
- Input: Organization ID (path parameter) and optional pagination params (query)
- Validation: Authentication, authorization, and organization existence checks
- Database Operation: MongoDB query using $elemMatch to find followers
- Avatar Processing: Batch normalization of avatar URLs via file storage driver
- Response Processing: Pagination metadata and normalized follower data formatting
- Output: 200 OK with paginated, normalized follower list
Performance Notes:
- Uses MongoDB $elemMatch operator for efficient follower queries
- Pagination support for scalable retrieval of large follower lists
- Batch avatar URL normalization for multiple followers
- Minimal response payload with only essential follower data (id, name, avatar)
- Efficient MongoDB queries with indexed lookups
Integration Patterns:
- Combines with organization service for complete organization management
- Integrates with file storage driver for avatar URL generation
- Works with pagination middleware for scalable follower lists
- Reuses profile blocks (findProfiles, normalizeFollowers) for consistency across features
- Supports real-time follower count updates and analytics