Skip to content

Content Lifecycle Management

Overview

This feature governs the platform's core value proposition: content. It enables users to create, publish, and manage blog posts, providing a complete lifecycle from drafting to public visibility. To enhance organization and discoverability, content can be structured using hierarchical categories and descriptive tags. The system fosters community engagement by allowing users to add and manage comments on posts, facilitating discussions. It also provides robust search capabilities, allowing users to easily find relevant content across the entire platform. This comprehensive suite of tools ensures a rich and interactive experience for both content creators and consumers, forming the application's central functionality.

Feature Flow

Feature Flow Feature Flow API Gateway LayerService Layerposts.pyposts.pycomments.pycategories.pyservice.pyservice.pyservice.pyservice.pyUserposts.pycomments.pycategories.pytags.pyservice.pyDatabaseUserUserposts.pyposts.pycomments.pycomments.pycategories.pycategories.pytags.pytags.pyservice.pyservice.pyDatabaseDatabaseposts.pyposts.pycomments.pycategories.pyservice.pyservice.pyservice.pyservice.pycreatePost(postData)create_post(postData)INSERT INTO postsnewPost201 Createdalt[Content Organization]createCategory(categoryData)create_category(categoryData)INSERT INTO categoriesnewCategory201 Created[User Comments]createComment(commentData)create_comment(commentData)PostMustExistForCommentCreation checkINSERT INTO commentsnewComment201 Created[Content Discovery]searchPosts(query)search_posts(query)SELECT FROM postspostList200 OKBLOGR - Backend - Feature: Content Lifecycle Management    This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Feature Flow Feature Flow API Gateway LayerService Layerposts.pyposts.pycomments.pycategories.pyservice.pyservice.pyservice.pyservice.pyUserposts.pycomments.pycategories.pytags.pyservice.pyDatabaseUserUserposts.pyposts.pycomments.pycomments.pycategories.pycategories.pytags.pytags.pyservice.pyservice.pyDatabaseDatabaseposts.pyposts.pycomments.pycategories.pyservice.pyservice.pyservice.pyservice.pycreatePost(postData)create_post(postData)INSERT INTO postsnewPost201 Createdalt[Content Organization]createCategory(categoryData)create_category(categoryData)INSERT INTO categoriesnewCategory201 Created[User Comments]createComment(commentData)create_comment(commentData)PostMustExistForCommentCreation checkINSERT INTO commentsnewComment201 Created[Content Discovery]searchPosts(query)search_posts(query)SELECT FROM postspostList200 OKBLOGR - Backend - Feature: Content Lifecycle Management    This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Use Cases

Use Case Trigger Outcome Description Layers
Post Creation & Management API call to /api/v1/posts A blog post is created, updated, retrieved, or deleted from the system. Enables authenticated users to create new blog posts, update existing ones, or delete them. This use case governs the entire lifecycle of primary content, enforcing authorship and data validation. API Gateway Layer
Service Layer
Repository Layer
Content Organization (Categories & Tags) API call to /api/v1/categories or /api/v1/tags A category or tag is created, retrieved, or deleted, and associated with posts. Allows administrators or authenticated users to manage the taxonomies for organizing content. This includes creating new categories and tags, which can then be assigned to posts for improved navigation. API Gateway Layer
Service Layer
Repository Layer
User Comments & Interaction API call to /api/v1/comments A user comment is created, updated, or deleted on a specific post. Facilitates user engagement by allowing authenticated users to add comments to posts. It also enables authors to manage their own comments, enforcing rules like authorship and post existence. API Gateway Layer
Service Layer
Repository Layer
Content Discovery & Search API call to /api/v1/posts/search/{query} A paginated list of posts matching the search criteria is returned. Provides functionality for users to search for posts based on keywords. The system queries post titles and content, returning a list of relevant, published posts to aid content discovery. API Gateway Layer
Service Layer
Repository Layer

Post Creation & Management

Use Case - Post Creation & Management BLOGR - Backend - Feature: Content Lifecycle Management Use Case - Post Creation & Management Request HandlingReceive API request to create/update postRaise 401 Unauthorized errornoUser is authenticated?yesValidation & AuthorizationValidate input data against PostCreate/PostUpdate schemaRaise 422 Unprocessable Entity errornoData is valid?yesPostAuthorAuthorization enforcedRaise 403 Forbidden errornoIs user authorized to modify post?yesProcessingSlugGeneration appliedCall PostService to process requestMandatoryPostContent enforcedPersist Post entity to databaseResponseReturn PostResponse with 200/201 status   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Use Case - Post Creation & Management BLOGR - Backend - Feature: Content Lifecycle Management Use Case - Post Creation & Management Request HandlingReceive API request to create/update postRaise 401 Unauthorized errornoUser is authenticated?yesValidation & AuthorizationValidate input data against PostCreate/PostUpdate schemaRaise 422 Unprocessable Entity errornoData is valid?yesPostAuthorAuthorization enforcedRaise 403 Forbidden errornoIs user authorized to modify post?yesProcessingSlugGeneration appliedCall PostService to process requestMandatoryPostContent enforcedPersist Post entity to databaseResponseReturn PostResponse with 200/201 status   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Content Organization (Categories & Tags)

Use Case - Content Organization (Categories & Tags) BLOGR - Backend - Feature: Content Lifecycle Management Use Case - Content Organization (Categories & Tags) Request HandlingReceive API request to create Category/TagRaise 401 Unauthorized errornoUser is authenticated?yesValidationValidate input against CategoryCreate/TagCreate schemaRaise 422 Unprocessable Entity errornoData is valid?yesProcessingUniqueCategoryIdentifier orUniqueTagIdentifier enforcedCall CategoryService/TagService to create entityPersist Category/Tag to databaseHandle per error_strategy (rollback_and_raise)Rollback database transactionRaise 500 Internal Server ErrornoCreation successful?yesResponseReturn new Category/Tag with 201 status   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Use Case - Content Organization (Categories & Tags) BLOGR - Backend - Feature: Content Lifecycle Management Use Case - Content Organization (Categories & Tags) Request HandlingReceive API request to create Category/TagRaise 401 Unauthorized errornoUser is authenticated?yesValidationValidate input against CategoryCreate/TagCreate schemaRaise 422 Unprocessable Entity errornoData is valid?yesProcessingUniqueCategoryIdentifier orUniqueTagIdentifier enforcedCall CategoryService/TagService to create entityPersist Category/Tag to databaseHandle per error_strategy (rollback_and_raise)Rollback database transactionRaise 500 Internal Server ErrornoCreation successful?yesResponseReturn new Category/Tag with 201 status   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

User Comments & Interaction

Use Case - User Comments & Interaction BLOGR - Backend - Feature: Content Lifecycle Management Use Case - User Comments & Interaction Request HandlingReceive API request to create commentRaise 401 Unauthorized errornoUser is authenticated?yesValidationPostMustExistForCommentCreation enforcedRaise 404 Not Found errornoAssociated post exists?yesValidate input against CommentCreate schemaProcessingMandatoryCommentContent enforcedCall CommentService to create commentPersist Comment entity to databaseHandle per error_strategy (rollback_and_raise)Rollback database transactionRaise 500 Internal Server ErrornoCreation successful?yesResponseReturn new Comment with 201 status   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Use Case - User Comments & Interaction BLOGR - Backend - Feature: Content Lifecycle Management Use Case - User Comments & Interaction Request HandlingReceive API request to create commentRaise 401 Unauthorized errornoUser is authenticated?yesValidationPostMustExistForCommentCreation enforcedRaise 404 Not Found errornoAssociated post exists?yesValidate input against CommentCreate schemaProcessingMandatoryCommentContent enforcedCall CommentService to create commentPersist Comment entity to databaseHandle per error_strategy (rollback_and_raise)Rollback database transactionRaise 500 Internal Server ErrornoCreation successful?yesResponseReturn new Comment with 201 status   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Use Case - Content Discovery & Search BLOGR - Backend - Feature: Content Lifecycle Management Use Case - Content Discovery & Search Request HandlingReceive API search request with queryValidate pagination parametersValidPaginationParameters enforcedRaise 422 Unprocessable Entity errornoParameters valid?yesProcessingCall PostService.search_posts with queryPublishedPostsOnly rule appliedto filter resultsQuery database for posts matching queryResponseReturn paginated list of PostResponse objects   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Use Case - Content Discovery & Search BLOGR - Backend - Feature: Content Lifecycle Management Use Case - Content Discovery & Search Request HandlingReceive API search request with queryValidate pagination parametersValidPaginationParameters enforcedRaise 422 Unprocessable Entity errornoParameters valid?yesProcessingCall PostService.search_posts with queryPublishedPostsOnly rule appliedto filter resultsQuery database for posts matching queryResponseReturn paginated list of PostResponse objects   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Architecture

Architecture BLOGR - Backend - Feature: Content Lifecycle Management Architecture API Gateway LayerService LayerRepository LayerExternal Systemsposts.pycomments.pycategories.pytags.pyservice.pymodels.pyDatabaseAuth ServiceLogging Systemdelegates logicdelegates logicdelegates logicdelegates logicuses modelspersists datamaps to schemaauthenticates userauthenticates userrecords events   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Architecture BLOGR - Backend - Feature: Content Lifecycle Management Architecture API Gateway LayerService LayerRepository LayerExternal Systemsposts.pycomments.pycategories.pytags.pyservice.pymodels.pyDatabaseAuth ServiceLogging Systemdelegates logicdelegates logicdelegates logicdelegates logicuses modelspersists datamaps to schemaauthenticates userauthenticates userrecords events   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Components

File Layer Role Responsibility
categories.py API Gateway Layer Manages category API endpoints Defines RESTful endpoints for creating, retrieving, and deleting content categories. It handles request validation, user authentication, and orchestrates calls to the service layer for category management logic.
comments.py API Gateway Layer Manages comment API endpoints Provides API endpoints for the entire comment lifecycle on posts. It enables users to create, view, update, and delete comments, while enforcing authorization and data integrity rules.
posts.py API Gateway Layer Manages post API endpoints Defines the public interface for all post-related actions, including creation, search, and updates. It validates incoming data, authorizes users, and delegates business logic to the post service.
tags.py API Gateway Layer Manages tag API endpoints Exposes RESTful endpoints for creating, listing, and deleting content tags. It ensures users are authenticated for these operations and orchestrates calls to the tag service for processing.
service.py Service Layer Centralizes content business logic Encapsulates the core business logic for managing posts, comments, categories, and tags. It orchestrates data operations, enforces rules like soft deletion, and generates slugs for content entities.
models.py Repository Layer Defines content data models Contains the SQLAlchemy ORM models for all content-related entities like Post, Comment, Category, and Tag. It defines their database schema, relationships, and data integrity constraints.

Business Rules

Business Rules BLOGR - Backend - Feature: Content Lifecycle Management Business Rules Content Lifecycle Management RulesPostMandatoryPostContentPostExistenceRequiredPostAuthorAuthorizationPostViewCountIncrementPublishedPostsOnlyPostPublishingControlCommentMandatoryCommentContentCommentAuthorMustMatchCurrentUserPostMustExistForCommentCreationCommentMustExistForOperationsCommentApprovalCategoryCategoryNotFoundUniqueCategoryIdentifierTagUniqueTagIdentifierTagMustExistUserUniqueUserIdentifierUserExistenceRequiredAuthenticatedUserRequiredGeneralValidPaginationParametersSoftDeletionPolicySlugGeneration   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Business Rules BLOGR - Backend - Feature: Content Lifecycle Management Business Rules Content Lifecycle Management RulesPostMandatoryPostContentPostExistenceRequiredPostAuthorAuthorizationPostViewCountIncrementPublishedPostsOnlyPostPublishingControlCommentMandatoryCommentContentCommentAuthorMustMatchCurrentUserPostMustExistForCommentCreationCommentMustExistForOperationsCommentApprovalCategoryCategoryNotFoundUniqueCategoryIdentifierTagUniqueTagIdentifierTagMustExistUserUniqueUserIdentifierUserExistenceRequiredAuthenticatedUserRequiredGeneralValidPaginationParametersSoftDeletionPolicySlugGeneration   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Rule Description Entities
MandatoryPostContent Requires that every `Post` must have a `title`, a unique `slug`, `content`, and an `author_id`. This rule ensures that all published posts contain essential information and proper attribution. Post
PostExistenceRequired This rule ensures that any operation targeting a specific post, such as retrieval, update, or deletion, can only proceed if the post actually exists in the system's database. Post
PostAuthorAuthorization This rule enforces that only the original author of a post is permitted to perform update or delete operations on that specific post, preventing unauthorized modifications effectively. Post
User
PostViewCountIncrement This rule specifies that every successful retrieval of a post by its ID must result in an increment of that post's associated view count metric, reflecting engagement. Post
PublishedPostsOnly This rule ensures that when listing all posts, only those explicitly marked as `published` are returned to the requesting client, filtering out drafts or private content effectively. Post
MandatoryCommentContent Stipulates that every `Comment` must contain `content`, be associated with a `post_id`, and have an `author_id`. This ensures all comments are meaningful, contextual, and attributable to a user. Comment
CommentAuthorMustMatchCurrentUser This rule enforces that a user can only update or delete comments they have personally authored. It prevents unauthorized modification or removal of other users' content. Comment
User
PostMustExistForCommentCreation This rule ensures that a new comment can only be created if the associated post actually exists in the system. It prevents orphaned comments and maintains data integrity. Comment
Post
CommentMustExistForOperations This rule dictates that any operation (retrieval, update, deletion) on a comment requires the comment to exist. It prevents actions on non-existent resources, ensuring valid targets. Comment
UniqueCategoryIdentifier Enforces that each `Category` must possess a unique `name` and `slug`. This rule prevents naming conflicts and ensures distinct identification for content categorization within the platform. Category
CategoryNotFound When a request specifies a `category_id` that does not exist in the database, the system responds with a 404 HTTP status. This rule ensures that operations target valid categories. Category
UniqueTagIdentifier Mandates that every `Tag` must have a unique `name` and `slug`. This ensures distinct identification for content tags, preventing ambiguity and maintaining consistent content organization. Tag
TagMustExist A `Tag` entity must exist in the system to be retrieved or deleted by its unique identifier. This prevents operations on non-existent resources and ensures data integrity. Tag
SoftDeletionPolicy Ensures entities like `User`, `Post`, `Category`, `Tag`, `Comment` are marked as deleted rather than permanently removed. This preserves historical data and allows recovery. User
Post
Category
Tag
Comment
SlugGeneration Automatically creates URL-friendly slugs for posts, categories, and tags from their names. This rule ensures content has readable and unique web addresses for better discovery and user experience. Post
Category
Tag
ValidPaginationParameters Pagination parameters `skip` and `limit` must adhere to specific constraints: `skip` must be non-negative, and `limit` must be between 1 and 500. This rule ensures efficient data retrieval. Category
Tag
Post
AuthenticatedUserRequired Any operation requiring user context, such as creating or deleting content, mandates a valid, authenticated `User`. This ensures secure access and accountability for all content-related actions. User
Tag
Category
Post
Comment

Domain Model

Domain Model BLOGR - Backend - Feature: Content Lifecycle Management Domain Model Content Management Context«aggregate_root»Posttitle: Stringcontent: Textis_published: Booleanview_count: Integerincrement_view_count()«entity»Commentcontent: Textis_approved: Booleanapprove()«entity»Categoryname: Stringslug: String«entity»Tagname: Stringslug: String«entity»Userusername: Stringemail: Stringcontains1*belongs to*1is tagged with**authored by*1authored by*1   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Domain Model BLOGR - Backend - Feature: Content Lifecycle Management Domain Model Content Management Context«aggregate_root»Posttitle: Stringcontent: Textis_published: Booleanview_count: Integerincrement_view_count()«entity»Commentcontent: Textis_approved: Booleanapprove()«entity»Categoryname: Stringslug: String«entity»Tagname: Stringslug: String«entity»Userusername: Stringemail: Stringcontains1*belongs to*1is tagged with**authored by*1authored by*1   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
Entity Type Description
Post aggregate_root The central content entity representing a blog article. It aggregates comments, is classified by a category and tags, and is authored by a user, forming a complete content unit.
Comment entity Represents user-generated feedback or discussion on a specific post. It must be linked to a parent post and an author, forming the basis for community interaction and engagement.
Category entity A classification label used for organizing posts into broad, hierarchical subjects. It helps users navigate and discover content by topic, providing structure to the blog's information architecture.
Tag entity A keyword or descriptive term used to label and group posts across different categories. It enables flexible, many-to-many content organization and aids in granular search and discovery.
User entity Represents an individual who interacts with content. Within this feature, a user acts as an author for posts and comments, establishing ownership and enabling authorization for content management.

State Lifecycle

State Lifecycle BLOGR - Backend - Feature: Content Lifecycle Management State Lifecycle createddeleteddelete_tag   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.
State Lifecycle BLOGR - Backend - Feature: Content Lifecycle Management State Lifecycle createddeleteddelete_tag   This diagram is for illustrative purposes only and may not capture all details.Refer to the original codebase for complete understanding.

Integration Points

System Type Usage
Database database Provides persistent storage for all content-related entities, including posts, comments, categories, and tags. It ensures data integrity and enables retrieval, updates, and transactional operations for content management.
Auth Service auth_service Authenticates users performing content operations. It validates tokens to identify the current user, enabling authorization checks to ensure only authors can manage their own posts and comments.
Logging System other Records significant events and errors related to content lifecycle operations. This provides crucial visibility for monitoring system health, debugging issues with post creation, and auditing content modifications.

Glossary

Term Definition
approve comment Changes a comment's status to visible, making it publicly accessible after moderation, ensuring content quality.
Author The specific user account responsible for creating a particular comment or post, establishing ownership and identity.
Category A broad classification for organizing `Post`s, helping users navigate content by subject matter, identified by a unique name and slug.
Comment A user-generated textual response or feedback associated with a specific post. It represents direct interaction with content.
is_approved A boolean flag indicating whether a `Comment` has been reviewed and deemed suitable for public display, controlling content moderation.
is_published A boolean flag indicating whether a `Post` is publicly visible on the platform, controlling its availability to readers.
Pagination The mechanism used to retrieve a subset of a larger collection of `Post` entities, defined by `skip` and `limit` parameters for efficient data fetching.
Post A primary content item within the application, such as an article or discussion topic, to which comments are attached.
Published A boolean state indicating whether a `Post` is publicly visible and accessible, or if it remains in a draft status for editing.
replies Refers to `Comment`s that are nested under another `Comment`, forming a hierarchical conversation structure within a post's discussion.
Search The functionality allowing users to discover `Post` entities by matching a provided `search_query` against their content or metadata for relevance.
slug A URL-friendly, unique string identifier derived from a title or name, used for clean web addresses and content referencing.
soft delete Marks an entity as inactive or removed without physically deleting its database record, preserving historical data.
Tag A keyword or term used to describe and group `Post`s, offering granular content classification and discoverability beyond categories.
User Represents an individual registered with the system, capable of authoring posts and comments, identified by unique email and username.
ViewCount A numerical metric associated with each `Post`, representing the total number of times it has been accessed or displayed to users.
view_count An integer metric tracking the number of times a `Post` has been accessed or viewed by users, indicating its popularity.

FAQs

Why are PostService, UserService, CategoryService, and TagService used instead of direct database interactions in the routes?

Using dedicated service layers abstracts business logic from the API, promoting separation of concerns, reusability, and easier testing of core functionalities for posts, users, categories, and tags.

Why are Pydantic schemas used for request and response models for content like posts and comments?

Pydantic schemas provide automatic data validation for incoming requests and serialization for outgoing responses, ensuring data integrity, clear API contracts, and reducing boilerplate code for all content entities.

Why are slug fields used for Post, Category, and Tag models?

The slug fields provide human-readable, URL-friendly identifiers for content, categories, and tags. They ensure unique, persistent web addresses, improving SEO and user experience by making URLs descriptive and clean.

What is the purpose of is_published and published_at fields in the Post model?

These fields manage the publication status and timing of a Post. is_published controls visibility, while published_at records the exact publication timestamp, enabling scheduled releases and content lifecycle management.

Why does the Post model use cascade="all, delete-orphan" for its comments relationship?

This cascade setting ensures that when a Post is deleted, all associated Comments are automatically removed from the database. It maintains data consistency by preventing orphaned comments and simplifies content management operations.

How does the system handle deleted entities like posts or comments?

The system employs a soft deletion strategy by setting a deleted_at timestamp. This preserves historical data and relationships, allowing for potential recovery while logically removing entities from active queries.