📂 Category Service
The Category Service provides a complete REST API for managing hierarchical categories with status control. It's designed to handle product categories, content classification, and organizational structures using the Nodeblocks functional composition approach and MongoDB integration.
🚀 Quickstart
import express from 'express';
import { middlewares, services, drivers } from '@nodeblocks/backend-sdk';
const { nodeBlocksErrorMiddleware } = middlewares;
const { categoryService } = services;
const { getMongoClient } = drivers;
const client = getMongoClient('mongodb://localhost:27017', 'dev');
express()
.use(
categoryService(
{
categories: client.collection('categories'),
identities: client.collection('identities'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
identity: {
typeIds: {
admin: '100',
guest: '000',
regular: '001',
},
},
}
)
)
.use(nodeBlocksErrorMiddleware())
.listen(8089, () => console.log('Server running'));
📋 Endpoint Summary
Category Operations
Method | Path | Description | Auth Required |
---|---|---|---|
POST | /categories | Create a new category | ✅ Admin |
GET | /categories/:categoryId | Retrieve a category by ID | ❌ |
GET | /categories | List all categories | ❌ |
PATCH | /categories/:categoryId | Update a category | ✅ Admin |
DELETE | /categories/:categoryId | Delete a category | ✅ Admin |
Status Management Operations
Method | Path | Description | Auth Required |
---|---|---|---|
POST | /categories/:categoryId/enable | Enable a category (set status to 'active') | ✅ Admin |
POST | /categories/:categoryId/disable | Disable a category (set status to 'inactive') | ✅ Admin |
🗄️ Entity Schema
The category entity combines base fields (auto-generated) with category-specific data:
{
"name": "string",
"description": "string",
"status": "string",
"parent": "string",
"createdAt": "string (datetime)",
"id": "string",
"updatedAt": "string (datetime)"
}
Field Details
Field | Type | Auto-Generated | Required | Description |
---|---|---|---|---|
name | string | ❌ | ✅ | Category name |
description | string | ❌ | ✅ | Category description |
status | string | ❌ | ✅ | Category status ('active', 'inactive', etc.) |
parent | string | ❌ | ❌ | Parent category ID for hierarchical structure |
createdAt | datetime | ✅ | ✅ | Creation timestamp |
id | string | ✅ | ✅ | Unique identifier (UUID) |
updatedAt | datetime | ✅ | ✅ | Last modification timestamp |
📝 Note: Auto-generated fields are set by the service and should not be included in create/update requests. The
parent
field enables hierarchical category structures.
🔐 Authentication Headers
For protected endpoints, include the following headers:
Authorization: Bearer <admin_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 Category
Creates a new category with the provided information.
Request:
- Method:
POST
- Path:
/categories
- Headers:
Content-Type: application/json
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin)
Request Body:
Field | Type | Required | Description |
---|---|---|---|
name | string | ✅ | Category name |
description | string | ✅ | Category description |
status | string | ✅ | Category status |
parent | string | ❌ | Parent category ID (for hierarchical structure) |
Response Body:
Field | Type | Description |
---|---|---|
name | string | Category name |
description | string | Category description |
status | string | Category status |
parent | string | Parent category ID (if applicable) |
createdAt | string | Creation timestamp |
id | string | Unique category identifier |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Enforced automatically (name, description, status required)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
Example Request:
curl -X POST http://localhost:8089/categories \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <admin_token>" \
-H "x-nb-fingerprint: <device-fingerprint>" \
-d '{
"name": "Electronics",
"description": "Electronic devices and accessories",
"status": "active"
}'
Example Request (with parent):
curl -X POST http://localhost:8089/categories \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <admin_token>" \
-H "x-nb-fingerprint: <device-fingerprint>" \
-d '{
"name": "Smartphones",
"description": "Mobile phones and accessories",
"status": "active",
"parent": "682f4a3e-e37e-4480-bc36-dda085e7ce26"
}'
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"name": "Electronics",
"description": "Electronic devices and accessories",
"status": "active",
"createdAt": "2025-07-07T07:45:59.013Z",
"id": "682f4a3e-e37e-4480-bc36-dda085e7ce26",
"updatedAt": "2025-07-07T07:45:59.013Z"
}
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 'description'",
"request body must have required property 'status'"
]
}
}
When authentication fails:
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": {
"message": "Token fails security check"
}
}
2. Get Category by ID
Retrieves a specific category by its unique ID.
Request:
- Method:
GET
- Path:
/categories/:categoryId
- Authorization: None required
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
categoryId | string | ✅ | Unique category identifier |
Response Body:
Field | Type | Description |
---|---|---|
name | string | Category name |
description | string | Category description |
status | string | Category status |
parent | string | Parent category ID (if applicable) |
createdAt | string | Creation timestamp |
id | string | Unique category identifier |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Path parameter validation for categoryId
- Route Validators:
- Validates category exists
Example Request:
curl http://localhost:8089/categories/682f4a3e-e37e-4480-bc36-dda085e7ce26
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"name": "Electronics",
"description": "Electronic devices and accessories",
"status": "active",
"createdAt": "2025-07-07T07:45:59.013Z",
"id": "682f4a3e-e37e-4480-bc36-dda085e7ce26",
"updatedAt": "2025-07-07T07:45:59.013Z"
}
Error Responses:
When no category exists with the provided ID:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Category does not exist"
}
}
3. List Categories
Retrieves a list of all categories.
Request:
- Method:
GET
- Path:
/categories
- Authorization: None required
Query Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
name | string | ❌ | Filter by category name |
description | string | ❌ | Filter by description |
parent | string | ❌ | Filter by parent category ID |
status | string | ❌ | Filter by status |
page | number | ❌ | Page number for pagination |
limit | number | ❌ | Number of items per page |
Response Body:
Field | Type | Description |
---|---|---|
name | string | Category name |
description | string | Category description |
status | string | Category status |
parent | string | Parent category ID (if applicable) |
createdAt | string | Creation timestamp |
id | string | Unique category identifier |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Query parameter validation for name, description, parent, status, and pagination (page, limit)
- Route Validators: None
Example Requests:
List all categories:
curl http://localhost:8089/categories
Filter by status:
curl "http://localhost:8089/categories?status=active"
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
[
{
"name": "Electronics",
"description": "Electronic devices and accessories",
"status": "active",
"createdAt": "2025-07-07T07:45:59.013Z",
"id": "682f4a3e-e37e-4480-bc36-dda085e7ce26",
"updatedAt": "2025-07-07T07:45:59.013Z"
},
{
"name": "Smartphones",
"description": "Mobile phones and accessories",
"status": "active",
"parent": "682f4a3e-e37e-4480-bc36-dda085e7ce26",
"createdAt": "2025-07-07T07:46:17.133Z",
"id": "4260c15e-7791-4f09-a846-b6ffa3a73101",
"updatedAt": "2025-07-07T07:46:17.133Z"
}
]
4. Update Category
Updates an existing category with partial data.
Request:
- Method:
PATCH
- Path:
/categories/:categoryId
- Headers:
Content-Type: application/json
- Authorization: Required (Admin)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
categoryId | string | ✅ | Unique category identifier |
Request Body (all fields optional):
Field | Type | Required | Description |
---|---|---|---|
name | string | ❌ | Category name |
description | string | ❌ | Category description |
parent | string | ❌ | Parent category ID |
⚠️ Important: The
status
field is NOT allowed in update requests. Use the dedicated enable/disable endpoints for status changes.
Response Body:
Field | Type | Description |
---|---|---|
name | string | Updated category name |
description | string | Updated category description |
status | string | Category status (unchanged) |
parent | string | Updated parent category ID (if applicable) |
createdAt | string | Creation timestamp |
id | string | Unique category identifier |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Enforced automatically (partial updates, limited fields allowed)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
- Validates category exists
Example Request:
curl -X PATCH http://localhost:8089/categories/682f4a3e-e37e-4480-bc36-dda085e7ce26 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <admin_token>" \
-d '{"description": "Updated electronic devices and accessories"}'
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"name": "Electronics",
"description": "Updated electronic devices and accessories",
"status": "active",
"createdAt": "2025-07-07T07:45:59.013Z",
"id": "682f4a3e-e37e-4480-bc36-dda085e7ce26",
"updatedAt": "2025-07-07T07:46:50.017Z"
}
Error Responses:
When no category exists with the provided ID:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Category does not exist"
}
}
When request body contains disallowed fields:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"request body must NOT have additional properties"
]
}
}
5. Delete Category
Permanently deletes a category from the system.
Request:
- Method:
DELETE
- Path:
/categories/:categoryId
- Authorization: Required (Admin)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
categoryId | string | ✅ | Unique category identifier |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Delete endpoint returns no response body on success |
Validation:
- Schema Validation: Path parameter validation for categoryId
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
- Validates category exists
Example Request:
curl -X DELETE http://localhost:8089/categories/682f4a3e-e37e-4480-bc36-dda085e7ce26 \
-H "Authorization: Bearer <admin_token>"
Success Response:
HTTP/1.1 204 No Content
Error Responses:
When no category exists with the provided ID:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Category does not exist"
}
}
🔄 Status Management Operations
The Category Service provides dedicated endpoints for managing category status.
6. Enable Category
Sets a category's status to 'active'.
Request:
- Method:
POST
- Path:
/categories/:categoryId/enable
- Authorization: Required (Admin)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
categoryId | string | ✅ | Unique category identifier |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Enable endpoint returns no response body on success |
Validation:
- Schema Validation: Path parameter validation for categoryId
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
- Validates category exists
Example Request:
curl -X POST http://localhost:8089/categories/682f4a3e-e37e-4480-bc36-dda085e7ce26/enable \
-H "Authorization: Bearer <admin_token>"
Success Response:
HTTP/1.1 204 No Content
7. Disable Category
Sets a category's status to 'inactive'.
Request:
- Method:
POST
- Path:
/categories/:categoryId/disable
- Authorization: Required (Admin)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
categoryId | string | ✅ | Unique category identifier |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Disable endpoint returns no response body on success |
Validation:
- Schema Validation: Path parameter validation for categoryId
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
- Validates category exists
Example Request:
curl -X POST http://localhost:8089/categories/682f4a3e-e37e-4480-bc36-dda085e7ce26/disable \
-H "Authorization: Bearer <admin_token>"
Success Response:
HTTP/1.1 204 No Content
🚨 Error Handling
All category 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 must have required property 'name' | Missing name field in request body |
400 | request body must have required property 'description' | Missing description field in request body |
400 | request body must have required property 'status' | Missing status field in request body |
400 | request body must NOT have additional properties | Request contains unsupported fields |
400 | Failed to create category | Database insert operation failed to return an inserted ID |
400 | Failed to update category | Update operation doesn't modify any data (no changes detected) |
400 | Failed to delete category | Database deletion operation failed |
401 | Authentication failed | Missing or invalid authentication token |
401 | token could not be verified | Missing or invalid authorization token |
401 | Token fails security check | Token security validation failed |
403 | User is not authorized to access this resource | User lacks required permissions (admin access) |
404 | Category does not exist | Category doesn't exist for the requested operation |
500 | Failed to create category | Database connection issues or unexpected failures during creation |
500 | Failed to get category | Database connection issues or unexpected failures during retrieval |
500 | Failed to find categories | Database connection issues, invalid filter syntax, or unexpected failures during listing |
500 | Failed to update category | Database connection issues or unexpected failures during update |
500 | Failed to delete category | Database connection issues or unexpected failures during deletion |
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 'description'",
"request body must have required property 'status'"
]
}
}
🔗 Related Documentation
- Product Service - Product management operations
- Attribute Service - Attribute management operations
- User Service - User management operations
- Organization Service - Organization management operations
- Authentication Service - Authentication and authorization
- Error Handling - Understanding error patterns
- Schema Component - Data validation concepts
- Custom Service Tutorial - Build your own services