Architecture

Overall Architecture

Deep Understanding of NextJS Base System Architecture

Architecture Diagram · Core Modules · Design Philosophy


🎯 Architecture Overview

NextJS Base adopts a layered architecture design, dividing the system into clear layers with explicit responsibilities, reducing coupling.

Core Features

FeatureDescription
Configuration-DrivenUI and behavior driven by fieldsConfig configuration
Convention over ConfigurationAutomatic permission and routing handling through naming conventions
Layered DecouplingClear separation of presentation, business, and data layers
AutomationAutomatic permission checks, logging, data validation

🏗️ Architecture Diagram

┌─────────────────────────────────────────────────────────────────────┐
│                    Presentation Layer                                │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐  │
│  │   SmartCrudPage  │  │    SmartForm     │  │   Custom Pages   │  │
│  │  Universal Table │  │  Universal Form  │  │  Custom Pages     │  │
│  └────────┬─────────┘  └────────┬─────────┘  └────────┬─────────┘  │
│           │                     │                     │             │
│           └─────────────────────┼─────────────────────┘             │
│                                 │                                    │
│                      ┌──────────▼──────────┐                        │
│                      │    fieldsConfig     │                        │
│                      │  Field Config Hub   │                        │
│                      └──────────┬──────────┘                        │
│                                 │                                    │
└─────────────────────────────────┼────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│                         Business Layer                              │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌──────────────────────────────────────────────────────────────┐   │
│  │                      Server Actions                           │   │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐          │   │
│  │  │ sysGetList  │  │ sysCreate   │  │ sysUpdate   │   ...    │   │
│  │  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘          │   │
│  │         └────────────────┼────────────────┘                  │   │
│  └──────────────────────────┼───────────────────────────────────┘   │
│                             │                                        │
│                  ┌──────────▼──────────┐                            │
│                  │     wrapAction      │                            │
│                  │   ┌─────────────┐   │                            │
│                  │   │ Auth Check  │   │                            │
│                  │   │ Permission  │   │                            │
│                  │   │ Logging     │   │                            │
│                  │   └─────────────┘   │                            │
│                  └──────────┬──────────┘                            │
│                             │                                        │
│                  ┌──────────▼──────────┐                            │
│                  │  createCrudActions  │                            │
│                  │   CRUD Factory      │                            │
│                  └──────────┬──────────┘                            │
│                             │                                        │
└─────────────────────────────┼────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│                      Data Access Layer                              │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌──────────────────────────────────────────────────────────────┐   │
│  │                         BaseDAO                               │   │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐          │   │
│  │  │Field Filter │  │Validation   │  │Hook Execute │          │   │
│  │  │Search Build │  │Soft Delete │  │Data Transform│          │   │
│  │  └─────────────┘  └─────────────┘  └─────────────┘          │   │
│  └──────────────────────────┬───────────────────────────────────┘   │
│                             │                                        │
│                  ┌──────────▼──────────┐                            │
│                  │    Prisma Client    │                            │
│                  │   ORM Database      │                            │
│                  └──────────┬──────────┘                            │
│                             │                                        │
└─────────────────────────────┼────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│                         Storage Layer                                │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐  │
│  │   PostgreSQL     │  │  Cloud Storage   │  │     Redis        │  │
│  │  Relational DB   │  │ R2/S3/OSS/Qiniu  │  │  Cache (Optional)│  │
│  └──────────────────┘  └──────────────────┘  └──────────────────┘  │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

📦 Core Modules

1. SmartCrudPage - Universal Table

Configuration-driven data table component, one component implements complete CRUD functionality

<SmartCrudPage
  title="Data Management"
  fieldsConfig={fieldsConfig}    // Field Configuration
  actions={actions}              // Server Actions
  enableCreate={true}            // Enable Create
  enableEdit={true}              // Enable Edit
  enableDelete={true}            // Enable Delete
/>

Core Features:

  • 📋 Data List (pagination, sorting, filtering)
  • 🔍 Advanced Search (multiple search modes)
  • ➕ Create Record (auto-generated form)
  • ✏️ Edit Record (auto-filled form)
  • 🗑️ Delete Record (confirmation popup)
  • 👁️ View Details (drawer display)

2. fieldsConfig - Field Configuration

Unified field configuration that drives table, form, search, and details

const fieldsConfig = [
  {
    key: 'name',           // Field Name
    title: 'Name',          // Display Name
    type: 'text',          // Field Type
    table: { ... },        // Table Configuration
    form: { ... },         // Form Configuration
    search: { ... },       // Search Configuration
  }
]

Supported Types:

TypeDescriptionTableFormSearch
textText
textareaMulti-line Text
numberNumber
selectDropdown
switchSwitch
dateDate
datetimeDateTime
tree-selectTree Select
imageImage
markdownMarkdown

3. wrapAction - Action Wrapper

Action wrapper that automatically handles authentication, authorization, and logging

export const sysGetRoleListAction = wrapAction(
  'sysGetRoleList',      // Action Name (determines permission level)
  async (params, ctx) => {
    // ctx contains userId, user, isAdmin
    return await dao.getList(params)
  }
)

Automatic Handling:

FeatureDescription
Authentication CheckAutomatically checks login status based on prefix
Permission Verificationsys prefix automatically checks RBAC permissions
LoggingAutomatically records operation logs
Error HandlingUnified error response format

4. createCrudActions - CRUD Factory

Quickly create standard CRUD Actions

const { getList, create, update, delete: del } = createCrudActions({
  modelName: 'role',
  fields: {
    creatable: ['name', 'remark'],
    updatable: ['name', 'remark'],
    searchable: ['name'],
  },
  validation: { ... },
  hooks: { ... },
})

Generated Actions:

  • sysGet{Resource}ListAction - Get List
  • sysGet{Resource}DetailAction - Get Detail
  • sysCreate{Resource}Action - Create Record
  • sysUpdate{Resource}Action - Update Record
  • sysDelete{Resource}Action - Delete Record
  • sysBatchUpdate{Resource}Action - Batch Update
  • sysBatchDelete{Resource}Action - Batch Delete

5. BaseDAO - Data Access Object

Universal data access layer that encapsulates Prisma operations

const dao = new BaseDAO({
  modelName: 'role',
  primaryKey: 'id',
  softDelete: true,
  fields: { ... },
  validation: { ... },
  hooks: { ... },
})

Core Features:

MethodDescription
getList()Paginated query, search, sorting
getDetail()Single query, relation loading
create()Create record, validation, Hooks
update()Update record, field filtering
delete()Delete/Soft Delete
batchUpdate()Batch Update
batchDelete()Batch Delete

💡 Design Philosophy

1. Configuration over Code

Traditional approach requires writing lots of repetitive code:

// ❌ Traditional Approach - Need to write table columns, form fields, search config separately
const columns = [...]
const formFields = [...]
const searchFields = [...]

NextJS Base uses unified configuration:

// ✅ Configuration-Driven - One configuration drives all UI
const fieldsConfig = [
  {
    key: 'name',
    title: 'Name',
    type: 'text',
    table: { width: 200 },
    form: { required: true },
    search: { enabled: true },
  }
]

2. Convention over Configuration

Automatic permission handling through naming conventions:

// Action name determines permission level
sysGetRoleList    // sys prefix → requires admin permission + RBAC check
authGetUserInfo   // auth prefix → requires login
pubGetConfig      // pub prefix → public access

3. Layered Decoupling

Each layer only focuses on its own responsibilities:

LayerResponsibilityDoesn't Care About
PresentationUI Rendering, User InteractionHow data is fetched
BusinessBusiness Logic, Permission ControlHow data is stored
DataData Access, ValidationHow data is displayed

4. Extensibility

Each module can be extended:

// Extend CRUD Actions
const { getList, create, ...rest } = createCrudActions(config)

// Add Custom Action
export const customAction = wrapAction('sysCustomAction', async (params) => {
  // Custom logic
})