# ๐Ÿ› ๏ธ Function-based Configuration Toolkit

When configuration files adopt the function form, MockM provides you with a super powerful util toolkit! It's like installing a turbocharger for your API Mock service.

# ๐ŸŽฏ Toolkit Overview

module.exports = (util) => {
  console.log('๐ŸŽ‰ Welcome to the MockM toolkit world!')
  
  // ๐Ÿš€ Server instance
  const { app } = util.server
  
  // ๐Ÿ“š Third-party libraries
  const { mockjs, axios, mime } = util.libObj
  
  // ๐Ÿ”ง Utility functions
  const tools = util.toolObj
  
  // ๐Ÿ’ผ Business functions
  const business = util.business
  
  // ๐ŸŒŸ API extensions
  const { side } = util
  
  return { /* your configuration */ }
}

# ๐Ÿš€ util.server - Server Core

# ๐ŸŒ Express Application Instance (util.server.app)

Direct access to the underlying Express application, giving you complete control:

module.exports = (util) => {
  const { app } = util.server
  
  // ๐ŸŽจ Custom routes
  app.get('/custom/hello', (req, res) => {
    res.json({ 
      message: '๐Ÿ‘‹ Hello from MockM!',
      timestamp: new Date().toISOString()
    })
  })
  
  // ๐Ÿ”’ Add authentication middleware
  app.use('/api/protected/*', (req, res, next) => {
    const token = req.headers.authorization
    if (!token) {
      return res.status(401).json({ error: '๐Ÿšซ Token required' })
    }
    next()
  })
  
  // ๐Ÿ“Š Custom status monitoring
  app.get('/status', (req, res) => {
    res.json({
      status: '๐ŸŸข running',
      uptime: process.uptime(),
      memory: process.memoryUsage(),
      version: require('../../package.json').version
    })
  })
  
  return {}
}

# ๐Ÿ“š util.libObj - Third-party Library Collection

# ๐ŸŽฒ MockJS - Data Generation Magic

๐Ÿ”— More Examples (opens new window)

module.exports = (util) => {
  const { mockjs } = util.libObj
  
  return {
    api: {
      // ๐Ÿ‘ฅ Generate user list
      'GET /api/users': mockjs.mock({
        'code': 200,
        'message': 'success',
        'data|10-20': [{
          'id|+1': 1,
          'name': '@cname',              // Chinese name
          'email': '@email',             // Email
          'avatar': '@image("200x200")', // Avatar
          'age|18-65': 1,               // Age
          'city': '@city',              // City
          'createTime': '@datetime'      // Create time
        }]
      }),
      
      // ๐Ÿ“Š Generate statistical data
      'GET /api/dashboard': mockjs.mock({
        'totalUsers|1000-9999': 1,
        'activeUsers|100-999': 1,
        'revenue|10000-99999.2': 1,
        'growth|0.1-0.5.1-2': 1,
        'chart|7': [{
          'date': '@date("MM-dd")',
          'value|100-1000': 1
        }]
      })
    }
  }
}
๐ŸŽจ MockJS Syntax Quick Reference

# ๐Ÿ“ String Templates

'name|min-max': 'string'  // Repeat string
'name|count': 'string'    // Repeat specified times

# ๐Ÿ”ข Number Templates

'name|+1': number         // Auto-increment number
'name|min-max': number    // Random integer
'name|min-max.dmin-dmax': number  // Random float

# ๐Ÿ“‹ Array Templates

'name|1': array          // Randomly select one element
'name|+1': array         // Select elements in order
'name|min-max': array    // Repeat array elements
'name|count': array      // Repeat specified times

# ๐ŸŽฏ Common Placeholders

  • ๐Ÿง‘ Names: @name (English) / @cname (Chinese)
  • ๐Ÿ“ง Contact: @email / @phone / @url
  • ๐Ÿ“ Address: @province / @city / @county
  • โฐ Time: @date / @time / @datetime / @now
  • ๐ŸŽจ Color: @color / @hex / @rgb
  • ๐Ÿ–ผ๏ธ Image: @image / @dataImage
  • ๐Ÿ“ Text: @sentence / @paragraph / @title

# ๐ŸŒ Axios - HTTP Request Tool

module.exports = (util) => {
  const { axios } = util.libObj
  
  // โš™๏ธ Global configuration
  axios.defaults.timeout = 5000
  axios.defaults.baseURL = 'https://api.example.com'
  
  // ๐Ÿ”ง Request interceptor
  axios.interceptors.request.use(config => {
    console.log('๐Ÿ“ค Sending request:', config.url)
    config.headers['X-Request-ID'] = Date.now()
    return config
  })
  
  // ๐Ÿ“จ Response interceptor
  axios.interceptors.response.use(
    response => {
      console.log('๐Ÿ“ฅ Received response:', response.status)
      return response
    },
    error => {
      console.error('โŒ Request failed:', error.message)
      return Promise.reject(error)
    }
  )
  
  return {
    api: {
      // ๐Ÿ”„ Proxy and enhance external API
      'GET /api/weather/:city': async (req, res) => {
        try {
          const { city } = req.params
          const response = await axios.get(`/weather?q=${city}`)
          
          res.json({
            code: 200,
            data: response.data,
            cached: false,
            timestamp: Date.now()
          })
        } catch (error) {
          res.status(500).json({
            code: 500,
            message: 'Weather service temporarily unavailable',
            error: error.message
          })
        }
      }
    }
  }
}

# ๐Ÿ“Ž MIME - File Type Recognition

module.exports = (util) => {
  const { mime } = util.libObj
  
  return {
    api: {
      // ๐Ÿ“ File upload handling
      'POST /api/upload': (req, res) => {
        const fileName = req.body.fileName
        const fileType = mime.getType(fileName)
        const extension = mime.getExtension(fileType)
        
        res.json({
          fileName,
          fileType,
          extension,
          isImage: fileType?.startsWith('image/'),
          isDocument: ['application/pdf', 'application/msword'].includes(fileType)
        })
      }
    }
  }
}

# ๐Ÿ”ง util.toolObj - Utility Collection

๐Ÿ”— Complete Source Code Reference (opens new window)

MockM provides rich utility functions to make your development more efficient:

module.exports = (util) => {
  const tools = util.toolObj
  
  return {
    api: {
      // ๐Ÿ”„ Array operation example
      'GET /api/array-demo': (req, res) => {
        const data = [1, 2, 3, 4, 5]
        res.json({
          original: data,
          processed: tools.array.shuffle(data),
          unique: tools.array.unique([1, 1, 2, 2, 3])
        })
      },
      
      // ๐Ÿ“ String processing example
      'GET /api/string-demo': (req, res) => {
        const text = 'hello world'
        res.json({
          original: text,
          camelCase: tools.string.toCamelCase(text),
          kebabCase: tools.string.toKebabCase(text),
          hash: tools.string.md5(text)
        })
      },
      
      // โฐ Time utility example
      'GET /api/time-demo': (req, res) => {
        res.json({
          now: tools.time.now(),
          format: tools.time.format(new Date(), 'YYYY-MM-DD HH:mm:ss'),
          relative: tools.time.relative(new Date(Date.now() - 3600000))
        })
      }
    }
  }
}

# ๐Ÿ› ๏ธ Tool Category Overview

Category Description Typical Use
๐Ÿ”„ array Array operations Deduplication, sorting, shuffling
๐Ÿ“ string String processing Format conversion, encryption, validation
๐Ÿ“ฆ npm Package management Dependency checking, version comparison
๐ŸŽฎ control Flow control Debounce, throttle, retry
๐Ÿ’พ cache Cache management Memory cache, persistence
๐ŸŽฒ generate Generators ID generation, random data
๐ŸŒ url URL processing Parsing, building, validation
๐Ÿ“ file File operations Read/write, upload, compression
๐Ÿ’ป cli Command line Parameter parsing, color output
๐Ÿ”ค hex Base conversion Hexadecimal processing
๐ŸŒŠ middleware Middleware Express middleware
๐ŸŒ httpClient HTTP client Request encapsulation
โšก fn Function utilities Functional programming
๐ŸŽฏ obj Object operations Deep copy, merge
๐Ÿ’ป os System info Platform detection
๐Ÿท๏ธ type Type detection Type checking
โฐ time Time processing Formatting, calculation

# ๐Ÿ’ผ util.business - Business Logic Assistant

๐Ÿ”— Complete Source Code Reference (opens new window)

module.exports = (util) => {
  const { wrapApiData, listToData, strReMatch } = util.business
  
  return {
    api: {
      // ๐Ÿ“ฆ Unified API response wrapper
      'GET /api/products': (req, res) => {
        const products = [
          { id: 1, name: 'Apple', price: 5.5 },
          { id: 2, name: 'Banana', price: 3.2 }
        ]
        
        res.json(wrapApiData(products, {
          code: 200,
          message: 'success',
          total: products.length
        }))
      },
      
      // ๐Ÿ—‚๏ธ Schema data conversion
      'GET /api/schema-demo': (req, res) => {
        const schema = [
          { key: 'name', type: 'string', example: 'John' },
          { key: 'age', type: 'number', example: 25 }
        ]
        
        res.json(listToData(schema))
      },
      
      // ๐Ÿ” Regex matching processing
      'GET /api/regex-demo': (req, res) => {
        const pattern = req.query.pattern || '/test/i'
        const regex = strReMatch(pattern)
        
        res.json({
          pattern,
          isRegex: !!regex,
          match: regex ? 'Test String'.match(regex) : null
        })
      }
    }
  }
}

# ๐ŸŒŸ util.side - API Extension Magic

Give your APIs superpowers! One interface, multiple aliases, easy solution:

module.exports = (util) => {
  const { side } = util
  
  return {
    api: {
      // ๐ŸŽฏ Basic alias usage
      '/api/users': side({
        alias: ['/api/members', 'POST /api/user-list'],
        action: [
          { id: 1, name: 'John' },
          { id: 2, name: 'Jane' }
        ]
      }),
      
      // ๐Ÿš€ Advanced feature combination
      '/api/products': side({
        alias: [
          '/api/goods',           // Goods alias
          '/api/items',           // Items alias  
          'POST /api/product-search' // Support different HTTP methods
        ],
        action: (req, res) => {
          res.json({
            message: '๐ŸŽ‰ This interface has multiple entry points!',
            method: req.method,
            path: req.path,
            timestamp: Date.now()
          })
        }
      }),
      
      // ๐Ÿ“š RESTful API quick creation
      '/api/articles': side({
        alias: [
          'GET /api/posts',        // Article list
          'GET /api/blogs',        // Blog list
          'POST /api/content'      // Content creation
        ],
        action: {
          'list|10': [{
            'id|+1': 1,
            'title': '@ctitle(5,10)',
            'content': '@cparagraph(3,5)',
            'author': '@cname',
            'createTime': '@datetime'
          }]
        }
      })
    }
  }
}

# ๐Ÿ’ก Power of Side Function

// ๐Ÿ”„ Traditional way - Repeated definitions
config = {
  api: {
    '/api/users': userData,
    '/api/members': userData,      // Duplicate!
    'POST /api/user-list': userData // Duplicate!
  }
}

// โœจ Side function - Define once, use multiple times
config = (util) => ({
  api: {
    '/api/users': util.side({
      alias: ['/api/members', 'POST /api/user-list'],
      action: userData
    })
  }
})

# ๐ŸŽฏ Practical Case: Building a Complete User System

module.exports = (util) => {
  const { mockjs, axios } = util.libObj
  const { wrapApiData } = util.business
  const { side } = util
  
  // ๐ŸŽฒ Mock user data
  const generateUsers = () => mockjs.mock({
    'list|50': [{
      'id|+1': 1,
      'username': '@word(3,10)',
      'name': '@cname',
      'email': '@email',
      'avatar': '@image("100x100")',
      'role|1': ['admin', 'user', 'guest'],
      'status|1': ['active', 'inactive'],
      'createTime': '@datetime',
      'loginCount|1-100': 1
    }]
  }).list
  
  return {
    api: {
      // ๐Ÿ‘ฅ User management API
      'GET /api/users': side({
        alias: ['/api/members', '/api/user-list'],
        action: (req, res) => {
          const { page = 1, size = 10, keyword = '' } = req.query
          let users = generateUsers()
          
          // ๐Ÿ” Keyword search
          if (keyword) {
            users = users.filter(user => 
              user.name.includes(keyword) || 
              user.username.includes(keyword)
            )
          }
          
          // ๐Ÿ“„ Pagination handling
          const start = (page - 1) * size
          const end = start + parseInt(size)
          const pageData = users.slice(start, end)
          
          res.json(wrapApiData({
            list: pageData,
            pagination: {
              current: parseInt(page),
              pageSize: parseInt(size),
              total: users.length,
              pages: Math.ceil(users.length / size)
            }
          }))
        }
      }),
      
      // ๐Ÿ‘ค User details
      'GET /api/users/:id': (req, res) => {
        const { id } = req.params
        const user = generateUsers().find(u => u.id == id)
        
        if (!user) {
          return res.status(404).json({
            code: 404,
            message: 'User not found'
          })
        }
        
        res.json(wrapApiData(user))
      },
      
      // ๐Ÿ” User authentication
      'POST /api/auth/login': side({
        alias: ['/api/login', '/api/signin'],
        action: (req, res) => {
          const { username, password } = req.body
          
          if (!username || !password) {
            return res.status(400).json({
              code: 400,
              message: 'Username and password cannot be empty'
            })
          }
          
          // ๐ŸŽญ Mock login verification
          const mockUser = {
            id: 1,
            username,
            name: mockjs.mock('@cname'),
            token: mockjs.mock('@guid'),
            role: 'user'
          }
          
          res.json(wrapApiData(mockUser, {
            message: 'Login successful'
          }))
        }
      })
    }
  }
}

# ๐Ÿš€ Advanced Techniques

# ๐Ÿ”„ Middleware Chain Processing

module.exports = (util) => {
  const { app } = util.server
  
  // ๐Ÿ“Š Request logging middleware
  app.use((req, res, next) => {
    console.log(`๐Ÿ“ฅ ${req.method} ${req.path}`)
    next()
  })
  
  // โฑ๏ธ Response time middleware
  app.use((req, res, next) => {
    const start = Date.now()
    res.on('finish', () => {
      console.log(`โฑ๏ธ ${req.path} took ${Date.now() - start}ms`)
    })
    next()
  })
  
  return {}
}

# ๐ŸŽฏ Dynamic Configuration Updates

module.exports = (util) => {
  const { toolObj } = util
  
  return {
    api: {
      // ๐Ÿ”„ Hot reload configuration
      'POST /api/config/reload': (req, res) => {
        // Configuration reload logic
        res.json({
          message: 'Configuration updated',
          timestamp: Date.now()
        })
      }
    }
  }
}

# ๐ŸŽ“ Best Practices

  1. ๐ŸŽจ Reasonable use of toolkit: Import as needed, avoid over-encapsulation
  2. ๐Ÿ”’ Security first: Validate input data, prevent injection attacks
  3. ๐Ÿ“Š Performance monitoring: Use utility functions to monitor API performance
  4. ๐Ÿงช Thorough testing: Use MockJS to generate various test data
  5. ๐Ÿ“ Clear documentation: Write clear comments for custom APIs

๐Ÿ’ก Pro Tip: The util toolkit upgrades your MockM configuration from simple data mocking to a fully functional development server!

Last Updated: 7/25/2025, 5:52:54 AM