Skip to main content
Version: 🚧 Canary

📂 Category Service

Testing Status

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

MethodPathDescriptionAuth Required
POST/categoriesCreate a new category✅ Admin
GET/categories/:categoryIdRetrieve a category by ID
GET/categoriesList all categories
PATCH/categories/:categoryIdUpdate a category✅ Admin
DELETE/categories/:categoryIdDelete a category✅ Admin

Status Management Operations

MethodPathDescriptionAuth Required
POST/categories/:categoryId/enableEnable a category (set status to 'active')✅ Admin
POST/categories/:categoryId/disableDisable 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

FieldTypeAuto-GeneratedRequiredDescription
namestringCategory name
descriptionstringCategory description
statusstringCategory status ('active', 'inactive', etc.)
parentstringParent category ID for hierarchical structure
createdAtdatetimeCreation timestamp
idstringUnique identifier (UUID)
updatedAtdatetimeLast 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:

FieldTypeRequiredDescription
namestringCategory name
descriptionstringCategory description
statusstringCategory status
parentstringParent category ID (for hierarchical structure)

Response Body:

FieldTypeDescription
namestringCategory name
descriptionstringCategory description
statusstringCategory status
parentstringParent category ID (if applicable)
createdAtstringCreation timestamp
idstringUnique category identifier
updatedAtstringLast 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:

ParameterTypeRequiredDescription
categoryIdstringUnique category identifier

Response Body:

FieldTypeDescription
namestringCategory name
descriptionstringCategory description
statusstringCategory status
parentstringParent category ID (if applicable)
createdAtstringCreation timestamp
idstringUnique category identifier
updatedAtstringLast 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:

ParameterTypeRequiredDescription
namestringFilter by category name
descriptionstringFilter by description
parentstringFilter by parent category ID
statusstringFilter by status
pagenumberPage number for pagination
limitnumberNumber of items per page

Response Body:

FieldTypeDescription
namestringCategory name
descriptionstringCategory description
statusstringCategory status
parentstringParent category ID (if applicable)
createdAtstringCreation timestamp
idstringUnique category identifier
updatedAtstringLast 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:

ParameterTypeRequiredDescription
categoryIdstringUnique category identifier

Request Body (all fields optional):

FieldTypeRequiredDescription
namestringCategory name
descriptionstringCategory description
parentstringParent category ID

⚠️ Important: The status field is NOT allowed in update requests. Use the dedicated enable/disable endpoints for status changes.

Response Body:

FieldTypeDescription
namestringUpdated category name
descriptionstringUpdated category description
statusstringCategory status (unchanged)
parentstringUpdated parent category ID (if applicable)
createdAtstringCreation timestamp
idstringUnique category identifier
updatedAtstringLast 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:

ParameterTypeRequiredDescription
categoryIdstringUnique category identifier

Response Body:

FieldTypeDescription
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:

ParameterTypeRequiredDescription
categoryIdstringUnique category identifier

Response Body:

FieldTypeDescription
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:

ParameterTypeRequiredDescription
categoryIdstringUnique category identifier

Response Body:

FieldTypeDescription
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

StatusError MessageDescription
400Validation ErrorInvalid request body format or missing required fields
400request body must have required property 'name'Missing name field in request body
400request body must have required property 'description'Missing description field in request body
400request body must have required property 'status'Missing status field in request body
400request body must NOT have additional propertiesRequest contains unsupported fields
400Failed to create categoryDatabase insert operation failed to return an inserted ID
400Failed to update categoryUpdate operation doesn't modify any data (no changes detected)
400Failed to delete categoryDatabase deletion operation failed
401Authentication failedMissing or invalid authentication token
401token could not be verifiedMissing or invalid authorization token
401Token fails security checkToken security validation failed
403User is not authorized to access this resourceUser lacks required permissions (admin access)
404Category does not existCategory doesn't exist for the requested operation
500Failed to create categoryDatabase connection issues or unexpected failures during creation
500Failed to get categoryDatabase connection issues or unexpected failures during retrieval
500Failed to find categoriesDatabase connection issues, invalid filter syntax, or unexpected failures during listing
500Failed to update categoryDatabase connection issues or unexpected failures during update
500Failed to delete categoryDatabase 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'"
]
}
}