🏢 Organization Service
The Organization Service provides a complete REST API for managing organization entities with CRUD operations. It's built using the Nodeblocks functional composition approach and integrates seamlessly with MongoDB.
🚀 Quickstart
import express from 'express';
import { MongoClient } from 'mongodb';
import { middlewares, services } from '@nodeblocks/backend-sdk';
const { nodeBlocksErrorMiddleware } = middlewares;
const { organizationService } = services;
const client = new MongoClient('mongodb://localhost:27017').db('dev');
express()
.use(
organizationService(
{
organizations: client.collection('organizations'),
identity: client.collection('identity'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
user: {
typeIds: {
admin: '100',
guest: '000',
user: '001',
},
},
organization: {
roles: {
admin: '100',
member: '001',
owner: '010',
},
},
}
)
)
.use(nodeBlocksErrorMiddleware())
.listen(8089, () => console.log('Server running'));
📋 Endpoint Summary
Basic CRUD Operations
Method | Path | Description | Authorization |
---|---|---|---|
POST | /organizations | Create a new organization | Bearer token required (admin only) |
GET | /organizations/:organizationId | Retrieve an organization by ID | Bearer token required (admin/organization access) |
GET | /organizations | List/filter organizations | Bearer token required (admin only) |
PATCH | /organizations/:organizationId | Update an organization | Bearer token required (admin/owner access) |
DELETE | /organizations/:organizationId | Delete an organization | Bearer token required (admin/owner access) |
User Management Operations
Method | Path | Description | Authorization |
---|---|---|---|
GET | /organizations/:organizationId/users | List users in an organization | Bearer token required (admin/organization access) |
PATCH | /organizations/:organizationId/users | Add/update users in an organization | Bearer token required (admin/organization access) |
DELETE | /organizations/:organizationId/users/:userId | Remove user from organization | Bearer token required (admin/organization access) |
GET | /organizations/:organizationId/users/:userId/role | Get user's role in organization | Bearer token required (admin/organization access) |
GET | /users/:userId/organizations | Find organizations for a user | Bearer token required (admin/self access) |
🗄️ Entity Schema
The organization entity combines base fields (auto-generated) with organization-specific data:
{
"id": "string",
"createdAt": "string (datetime)",
"updatedAt": "string (datetime)",
"name": "string",
"description": "string",
"contact_email": "string",
"contact_phone": "string",
"address": "object",
"users": "array"
}
Field Details
Field | Type | Auto-Generated | Required | Description |
---|---|---|---|---|
id | string | ✅ | ✅ | Unique identifier (UUID) |
createdAt | datetime | ✅ | ✅ | Creation timestamp |
updatedAt | datetime | ✅ | ✅ | Last modification timestamp |
name | string | ❌ | ✅ | Organization name (minimum 1 character) |
description | string | ❌ | ✅ | Organization description |
contact_email | string | ❌ | ✅ | Contact email address (email format) |
contact_phone | string | ❌ | ❌ | Contact phone number |
address | object | ❌ | ❌ | Address object (free-form JSON) |
users | array | ❌ | ❌ | Array of identities with roles ({id: string, role: string} ) |
📝 Note: Auto-generated fields are set by the service and should not be included in create/update requests.
🔐 Authentication Headers
For all endpoints, include the following headers:
Authorization: Bearer <access_token>
x-nb-fingerprint: <device_fingerprint>
⚠️ Important: The
x-nb-fingerprint
header is required for all authenticated requests if fingerprint was specified during authorization. Without it, requests will return 401 Unauthorized.
🔧 API Endpoints
1. Create Organization
Creates a new organization with the provided information.
Request:
- Method:
POST
- Path:
/organizations
- Headers:
Content-Type: application/json
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin only)
Request Body:
Field | Type | Required | Description |
---|---|---|---|
name | string | ✅ | Organization name (minimum 1 character) |
description | string | ✅ | Organization description |
contact_email | string | ✅ | Contact email address |
ownerId | string | ✅ | Organization owner user ID |
contact_phone | string | ❌ | Contact phone number |
address | object | ❌ | Address object (free-form JSON) |
Response Body:
Field | Type | Description |
---|---|---|
id | string | Unique organization identifier |
name | string | Organization name |
description | string | Organization description |
contact_email | string | Contact email address |
contact_phone | string | Contact phone number |
address | object | Address object (free-form JSON) |
users | array | Array of objects containing user ID and role: {id: string, role: string} |
createdAt | string | Creation timestamp |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Enforced automatically (name, description, contact_email, ownerId required)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedvalidateResourceAccess(['admin'], getBearerTokenInfo)
- Requires identity to have admin access
Example Request:
curl -X POST {{host}}/organizations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"name": "ACME Corp",
"description": "Leading provider of rocket skates",
"contact_email": "info@acme.test",
"ownerId": "user-id",
"contact_phone": "+1-202-555-0199",
"address": {
"street": "1 Road Runner Way",
"city": "Desert",
"country": "US"
}
}'
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": "7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2",
"name": "ACME Corp",
"description": "Leading provider of rocket skates",
"contact_email": "info@acme.test",
"contact_phone": "+1-202-555-0199",
"address": {
"street": "1 Road Runner Way",
"city": "Desert",
"country": "US"
},
"users": [
{
"id": "owner-id",
"role": "owner"
}
],
"createdAt": "2024-05-28T09:41:22.552Z",
"updatedAt": "2024-05-28T09:41:22.552Z"
}
Error Responses:
When request body is missing required fields:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'name'",
"request body must have required property 'description'",
"request body must have required property 'contact_email'",
"request body must have required property 'ownerId'"
]
}
}
When no authorization token is provided:
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": {
"message": "token could not be verified"
}
}
When database insert operation fails to return an inserted ID:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Failed to create organization"
}
}
When an unexpected error occurs (database connection issues, etc.):
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to create organization"
}
}
2. Get Organization by ID
Retrieves a specific organization by their unique ID.
Request:
- Method:
GET
- Path:
/organizations/:organizationId
- Headers:
Authorization: Bearer <access-token>
- Authorization: Bearer token required (admin/organization access)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
organizationId | string | ✅ | Unique organization identifier |
Response Body:
Field | Type | Description |
---|---|---|
id | string | Unique organization identifier |
name | string | Organization name |
description | string | Organization description |
contact_email | string | Contact email address |
contact_phone | string | Contact phone number |
address | object | Address object (free-form JSON) |
users | array | Array of objects containing user ID and role: {id: string, role: string} |
createdAt | string | Creation timestamp |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: None
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedsome(validateResourceAccess(['admin'], getBearerTokenInfo), validateOrganizationAccess(['owner', 'admin', 'member'], getBearerTokenInfo))
- Requires either admin access to all resources OR organization membership (owner/admin/member role)
Example Request:
curl {{host}}/organizations/7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": "7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2",
"name": "ACME Corp",
"description": "Leading provider of rocket skates",
"contact_email": "info@acme.test",
"contact_phone": "+1-202-555-0199",
"address": {
"street": "1 Road Runner Way",
"city": "Desert",
"country": "US"
},
"users": [
{
"id": "owner-id",
"role": "owner"
}
],
"createdAt": "2024-05-28T09:41:22.552Z",
"updatedAt": "2024-05-28T09:41:22.552Z"
}
Error Responses:
When no organization exists with the provided ID:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Organization not found"
}
}
When an unexpected error occurs (database connection issues, etc.):
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to get organization"
}
}
3. List Organizations
Retrieves a list of organizations with optional filtering and pagination.
Request:
- Method:
GET
- Path:
/organizations
- Authorization: None
Query Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
name | string | ❌ | Filter organizations by name (minimum 1 character) |
description | string | ❌ | Filter organizations by description |
contact_email | string | ❌ | Filter organizations by contact email (email format) |
contact_phone | string | ❌ | Filter organizations by contact phone |
page | number | ❌ | Page number |
limit | number | ❌ | Items per page |
Response Body:
Field | Type | Description |
---|---|---|
id | string | Unique organization identifier |
name | string | Organization name |
description | string | Organization description |
contact_email | string | Contact email address |
contact_phone | string | Contact phone number |
address | object | Address object (free-form JSON) |
users | array | Array of objects containing user ID and role: {id: string, role: string} |
createdAt | string | Creation timestamp |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Query parameter validation for name (min length 1), contact_email (email format), and pagination parameters (integers with min/max constraints)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedvalidateResourceAccess(['admin'], getBearerTokenInfo)
- Requires admin access
Example Requests:
List all organizations:
curl {{host}}/organizations
Filter by name:
curl "{{host}}/organizations?name=ACME Corp"
Filter by contact email:
curl "{{host}}/organizations?contact_email=info@acme.test"
Filter by description:
curl "{{host}}/organizations?description=rocket skates"
Filter by contact phone:
curl "{{host}}/organizations?contact_phone=+1-202-555-0199"
Combine filters:
curl "{{host}}/organizations?name=ACME&contact_email=info@acme.test&page=1&limit=20"
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
[
{
"id": "7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2",
"name": "ACME Corp",
"description": "Leading provider of rocket skates",
"contact_email": "info@acme.test",
"contact_phone": "+1-202-555-0199",
"address": {
"street": "1 Road Runner Way",
"city": "Desert",
"country": "US"
},
"users": [
{
"id": "owner-id",
"role": "owner"
}
],
"createdAt": "2024-05-28T09:41:22.552Z",
"updatedAt": "2024-05-28T09:41:22.552Z"
},
{
"id": "8fec096b-1bc7-5bfe-c827-3600e8fe2790",
"name": "Wayne Enterprises",
"description": "Gotham's premier technology company",
"contact_email": "contact@wayneenterprises.com",
"users": [
{
"id": "owner-id",
"role": "owner"
}
],
"createdAt": "2024-05-29T10:15:33.441Z",
"updatedAt": "2024-05-29T10:15:33.441Z"
}
]
Error Responses:
When an unexpected error occurs (database connection issues, invalid filter syntax, etc.):
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to find organizations"
}
}
4. Update Organization
Updates an existing organization with partial data.
Request:
- Method:
PATCH
- Path:
/organizations/:organizationId
- Headers:
Content-Type: application/json
- Authorization: None
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
organizationId | string | ✅ | Unique organization identifier |
Response Body:
Field | Type | Description |
---|---|---|
id | string | Unique organization identifier |
name | string | Updated organization name |
description | string | Updated organization description |
contact_email | string | Updated contact email address |
contact_phone | string | Updated contact phone number |
address | object | Updated address object (free-form JSON) |
createdAt | string | Creation timestamp |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Enforced automatically (partial updates, all fields optional)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedsome(validateResourceAccess(['admin'], getBearerTokenInfo), validateOrganizationAccess(['owner'], getBearerTokenInfo))
- Requires either admin access OR organization owner role
Example Request:
curl -X PATCH {{host}}/organizations/7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2 \
-H "Content-Type: application/json" \
-d '{"description": "Updated description for ACME Corp"}'
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": "7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2",
"name": "ACME Corp",
"description": "Updated description for ACME Corp",
"contact_email": "info@acme.test",
"contact_phone": "+1-202-555-0199",
"address": {
"street": "1 Road Runner Way",
"city": "Desert",
"country": "US"
},
"users": [
{
"id": "owner-id",
"role": "owner"
}
],
"createdAt": "2024-05-28T09:41:22.552Z",
"updatedAt": "2024-05-28T14:22:15.789Z"
}
Error Responses:
When request body is missing or empty:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Request body is required"
}
}
When no organization exists with the provided ID:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Organization not found"
}
}
When the update operation doesn't modify any data (no changes detected):
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Failed to update organization"
}
}
When an unexpected error occurs (database connection issues, etc.):
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to update organization"
}
}
5. Delete Organization
Permanently deletes an organization from the system.
Request:
- Method:
DELETE
- Path:
/organizations/:organizationId
- Authorization: None
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
organizationId | string | ✅ | Unique organization identifier |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Delete endpoint returns no response body on success |
Validation:
- Schema Validation: None
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedsome(validateResourceAccess(['admin'], getBearerTokenInfo), validateOrganizationAccess(['owner'], getBearerTokenInfo))
- Requires either admin access OR organization owner role
Example Request:
curl -X DELETE {{host}}/organizations/7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2
Success Response:
HTTP/1.1 204 No Content
Error Responses:
When no organization exists with the provided ID:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Organization not found"
}
}
When an unexpected error occurs (database connection issues, etc.):
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to delete organization"
}
}
👥 User Management Endpoints
6. List Organization Users
Retrieves a list of users associated with an organization.
Request:
- Method:
GET
- Path:
/organizations/:organizationId/users
- Headers:
Authorization: Bearer <access-token>
- Authorization: Bearer token required (admin/organization access)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
organizationId | string | ✅ | Unique organization identifier |
Validation:
- Schema Validation: None (GET request)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedsome(validateResourceAccess(['admin'], getBearerTokenInfo), validateOrganizationAccess(['owner', 'admin'], getBearerTokenInfo))
- Requires either admin access to all resources OR organization(owner/admin role in the organization
Example Request:
curl {{host}}/organizations/7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2/users
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"count": 2,
"total": 2,
"value": [
{
"id": "user123",
"role": "admin"
},
{
"id": "392157b1-dc7a-4935-a6f9-a2d333b910ea",
"role": "owner"
}
]
}
7. Add/Update Organization Users
Adds new users to an organization or updates existing user roles. Uses upsert logic - if user exists, updates their role; if not, adds them.
Request:
- Method:
PATCH
- Path:
/organizations/:organizationId/users
- Headers:
Content-Type: application/json
,Authorization: Bearer <access-token>
- Authorization: Bearer token required (admin/organization access)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
organizationId | string | ✅ | Unique organization identifier |
Request Body: Array of user objects to add/update:
Field | Type | Required | Description |
---|---|---|---|
id | string | ✅ | User identifier |
role | string | ✅ | User role in the organization |
Validation:
- Schema Validation: Enforced automatically (array with required id and role fields)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedsome(validateResourceAccess(['admin'], getBearerTokenInfo), validateOrganizationAccess(['owner', 'admin'], getBearerTokenInfo))
- Requires either admin access to all resources OR organization(owner/admin role in the organization
Example Request:
curl -X PATCH {{host}}/organizations/7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2/users \
-H "Content-Type: application/json" \
-d '[
{"id": "user123", "role": "admin"},
{"id": "user456", "role": "member"}
]'
Success Response:
HTTP/1.1 204 No Content
Error Responses:
When request body is missing or empty:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Request body non-empty array required"
}
}
When organization doesn't exist:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Organization not found"
}
}
When database operation fails:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to upsert organization users"
}
}
8. Remove User from Organization
Removes a specific user from an organization.
Request:
- Method:
DELETE
- Path:
/organizations/:organizationId/users/:userId
- Headers:
Authorization: Bearer <access-token>
- Authorization: Bearer token required (admin/organization access)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
organizationId | string | ✅ | Unique organization identifier |
userId | string | ✅ | Unique user identifier |
Validation:
- Schema Validation: None (DELETE request)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedsome(validateResourceAccess(['admin'], getBearerTokenInfo), validateOrganizationAccess(['owner', 'admin'], getBearerTokenInfo))
- Requires either admin access to all resources OR organization(owner/admin role in the organization
Example Request:
curl -X DELETE {{host}}/organizations/7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2/users/user123
Success Response:
HTTP/1.1 204 No Content
Error Responses:
When organization doesn't exist:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Organization not found"
}
}
When user is not in the organization:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Failed to remove user from organization"
}
}
When database operation fails:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to delete organization user"
}
}
9. Get User Role in Organization
Retrieves the role of a specific user within an organization.
Request:
- Method:
GET
- Path:
/organizations/:organizationId/users/:userId/role
- Headers:
Authorization: Bearer <access-token>
- Authorization: Bearer token required (admin/organization access)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
organizationId | string | ✅ | Unique organization identifier |
userId | string | ✅ | Unique user identifier |
Validation:
- Schema Validation: None (GET request)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedsome(validateResourceAccess(['admin'], getBearerTokenInfo), validateOrganizationAccess(['owner', 'admin'], getBearerTokenInfo))
- Requires either admin access to all resources OR organization(owner/admin role in the organization
Example Request:
curl {{host}}/organizations/7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2/users/user123/role
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"role": "admin"
}
Error Responses:
When organization or user doesn't exist:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Organization not found"
}
}
When database operation fails:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to get organization user role"
}
}
10. Check User Existence in Organization
Checks whether a specific user exists within an organization.
Request:
- Method:
GET
- Path:
/organizations/:organizationId/users/checkExistence
- Headers:
Authorization: Bearer <access-token>
- Authorization: Bearer token required (admin/organization access)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
organizationId | string | ✅ | Unique organization identifier |
Query Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
userId | string | ✅ | Unique user identifier to check |
Validation:
- Schema Validation: None (GET request)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedsome(validateResourceAccess(['admin'], getBearerTokenInfo), validateOrganizationAccess(['owner', 'admin'], getBearerTokenInfo))
- Requires either admin access to all resources OR organization(owner/admin role in the organization
Example Request:
curl "{{host}}/organizations/7edfb95f-0ab6-4adc-a6e1-2a86a2f1e6d2/users/checkExistence?userId=user123"
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"isUserInOrganization": true
}
Error Responses:
When organization doesn't exist:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Organization not found"
}
}
When database operation fails:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to check organization user existence"
}
}
11. Find Organizations for User
Retrieves all organizations that a specific user belongs to.
Request:
- Method:
GET
- Path:
/users/:userId/organizations
- Headers:
Authorization: Bearer <access-token>
- Authorization: Bearer token required (admin/self access)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
userId | string | ✅ | Unique user identifier |
Validation:
- Schema Validation: None (GET request)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Ensures valid authentication token is providedvalidateResourceAccess(['admin', 'self'], getBearerTokenInfo)
- Requires identity to either have admin access OR be self
Example Request:
curl {{host}}/users/user123/organizations
Expected Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"count": 2,
"total": 2,
"value": [
{
"_id": "6855002017588a44493de839",
"name": "ACME Corp",
"description": "Leading provider of rocket skates",
"contact_email": "info@acme.test",
"contact_phone": "+1-202-555-0199",
"address": {
"street": "1 Road Runner Way",
"city": "Desert",
"country": "US"
},
"createdAt": "2025-06-20T06:30:56.508Z",
"id": "2cc0b337-beed-48b3-8fe5-7c15d441d919",
"updatedAt": "2025-06-25T05:20:25.205Z",
"users": [
{
"id": "user123",
"role": "admin"
},
{
"id": "user456",
"role": "member"
}
]
},
{
"_id": "6864b903000ae2c60e16477d",
"name": "ACME Corp",
"description": "Leading provider of rocket skates",
"contact_email": "info@acme.test",
"contact_phone": "+1-202-555-0199",
"address": {
"street": "1 Road Runner Way",
"city": "Desert",
"country": "US"
},
"createdAt": "2025-07-02T04:43:47.170Z",
"id": "427348ec-e553-4e3f-99a3-0c84d49b252b",
"updatedAt": "2025-07-02T04:44:05.920Z",
"users": [
{
"id": "user123",
"role": "admin"
},
{
"id": "user456",
"role": "member"
}
]
}
]
}
If User Does Not Exist:
HTTP/1.1 200 OK
Content-Type: application/json
{
"count": 0,
"total": 0,
"value": []
}
⚙️ Configuration Options
Service Configuration
interface OrganizationServiceConfiguration {
authSecrets: {
authEncSecret: string; // JWT encryption secret
authSignSecret: string; // JWT signing secret
};
user?: {
typeIds?: {
admin: string; // Admin user type identifier
guest: string; // Guest user type identifier
user: string; // Regular user type identifier
};
};
organization?: {
roles?: {
admin: string; // Admin role identifier
member: string; // Member role identifier
owner: string; // Owner role identifier
};
};
}
Configuration Details
The organization service configuration is organized into logical groups for security, user type management, and organization role management.
🔐 Security Settings
authSecrets
- JWT token security secrets
- Type:
{ authEncSecret: string; authSignSecret: string }
- Description: Secret keys for JWT encryption and signing (used for token validation)
- Required: Yes (for production)
- Child Properties:
authEncSecret
: Secret key for JWT payload encryptionauthSignSecret
: Secret key for JWT signature verification
👥 User Type Settings
user.typeIds
- User type identifier configuration
- Type:
{ admin?: string; guest?: string; user?: string }
- Description: Custom user type identifiers for role-based access control
- Default:
undefined
(uses default type validation) - Child Properties:
admin
: Admin user type identifier- Type:
string
- Description: Custom identifier for admin users
- Use Case: Role-based access control for administrative operations
- Example:
"admin"
,"administrator"
,"superuser"
- Type:
guest
: Guest user type identifier- Type:
string
- Description: Custom identifier for guest users
- Use Case: Limited access for unauthenticated or temporary users
- Example:
"guest"
,"visitor"
,"anonymous"
- Type:
user
: Regular user type identifier- Type:
string
- Description: Custom identifier for regular users
- Use Case: Standard user access permissions
- Example:
"user"
,"member"
,"customer"
- Type:
🏢 Organization Role Settings
organization.roles
- Organization role identifier configuration
- Type:
{ admin?: string; member?: string; owner?: string }
- Description: Custom organization role identifiers for user management within organizations
- Default:
undefined
(uses default role validation) - Child Properties:
admin
: Admin role identifier- Type:
string
- Description: Custom identifier for organization admin role
- Use Case: Administrative permissions within organizations
- Example:
"admin"
,"administrator"
,"manager"
- Type:
member
: Member role identifier- Type:
string
- Description: Custom identifier for organization member role
- Use Case: Standard member permissions within organizations
- Example:
"member"
,"user"
,"employee"
- Type:
owner
: Owner role identifier- Type:
string
- Description: Custom identifier for organization owner role
- Use Case: Full control permissions within organizations
- Example:
"owner"
,"founder"
,"creator"
- Type:
Example Configuration
const organizationConfig = {
authSecrets: {
authEncSecret: process.env.AUTH_ENC_SECRET || 'your-enc-secret',
authSignSecret: process.env.AUTH_SIGN_SECRET || 'your-sign-secret'
},
user: {
typeIds: {
admin: '100',
guest: '000',
user: '001'
}
},
organization: {
roles: {
admin: '100',
member: '001',
owner: '010'
}
}
};
🚨 Error Handling
All organization service errors return JSON format with appropriate HTTP status codes:
Common Error Codes
Status | Error Message | Description |
---|---|---|
400 | Validation Error | Invalid request body format or missing required fields |
400 | Request body is required | Missing request body for PATCH operations |
400 | Request body non-empty array required | Missing or empty array for user management operations |
400 | Failed to create organization | Database insert operation failed to return an inserted ID |
400 | Failed to update organization | Update operation doesn't modify any data (no changes detected) |
400 | Failed to remove user from organization | User is not in the organization or removal failed |
401 | token could not be verified | Missing or invalid authorization token |
403 | User is not authorized to access this resource | User lacks required permissions (admin/organization access) |
404 | Organization not found | Organization doesn't exist for the requested operation |
500 | Failed to create organization | Database connection issues or unexpected failures during creation |
500 | Failed to get organization | Database connection issues or unexpected failures during retrieval |
500 | Failed to find organizations | Database connection issues, invalid filter syntax, or unexpected failures during listing |
500 | Failed to update organization | Database connection issues or unexpected failures during update |
500 | Failed to delete organization | Database connection issues or unexpected failures during deletion |
500 | Failed to upsert organization users | Database connection issues or unexpected failures during user management |
500 | Failed to delete organization user | Database connection issues or unexpected failures during user removal |
500 | Failed to get organization user role | Database connection issues or unexpected failures during role retrieval |
500 | Failed to check organization user existence | Database connection issues or unexpected failures during existence check |
500 | Cannot read properties of undefined (reading 'organizations') | Handler implementation bug in find organizations for user endpoint |
Error Response Format
{
"error": {
"message": "Error message description",
"data": ["Additional error details"]
}
}
Validation Errors include additional details:
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'name'",
"request body must have required property 'description'",
"request body must have required property 'contact_email'",
"request body must have required property 'ownerId'"
]
}
}
🔗 Related Documentation
- User Service - User management operations
- Authentication Service - Authentication and authorization
- Error Handling - Understanding error patterns
- Schema Component - Data validation concepts
- Custom Service Tutorial - Build your own services