### Start with Custom Config File Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Use the --config_file argument to specify a custom configuration file path when starting the application. ```bash node core.js --config_file ./custom-config.yml ``` -------------------------------- ### Starting Redis Server Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Commands to start the Redis server locally or using Docker. ```bash redis-server # 或使用 Docker docker run -d -p 6379:6379 redis ``` -------------------------------- ### Start in Development Mode Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Use the --dev argument to start the application in development mode. ```bash node core.js --dev ``` -------------------------------- ### Query Records Examples Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/database-and-models.md Provides examples for querying records from the HitokotoModel, including by primary key, by specific conditions with limits, and for counting records. ```javascript // 按 ID 查询 const record = await HitokotoModel.findByPk(1) // 按条件查询 const records = await HitokotoModel.findAll({ where: { type: 'anime' }, limit: 10, offset: 0 }) // 统计记录数 const count = await HitokotoModel.count({ where: { type: 'anime' } }) ``` -------------------------------- ### GET Request with Query String Parameters Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/route-and-controller.md Demonstrates how to define a GET route that accepts query string parameters. These parameters are accessible through `ctx.query`. ```javascript router.get('/api/search', async (ctx) => { const { keyword, limit } = ctx.query ctx.body = { keyword, limit } }) ``` -------------------------------- ### Database Configuration Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Shows the expected structure for database connection settings in the configuration file. ```yaml # config.yml mysql: host: 'localhost' port: 3306 username: 'root' password: 'password' database: 'hitokoto' ``` -------------------------------- ### Basic GET Request Route Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/route-and-controller.md A simple example of defining a GET route that returns a JSON object. This is the most basic way to set up an API endpoint. ```javascript router.get('/api/data', async (ctx) => { ctx.body = { data: 'value' } }) ``` -------------------------------- ### db Constructor Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/database-and-models.md Instantiate the db class and register a specific model like 'hitokoto'. ```javascript const db = require('./src/db') // 创建实例并注册 hitokoto 模型 const hitokotoModel = new db('hitokoto') ``` -------------------------------- ### GET Request with Route Parameters Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/route-and-controller.md Shows how to define a GET route that accepts parameters in the URL path. Route parameters are accessed via `ctx.params`. ```javascript router.get('/api/user/:id', async (ctx) => { const { id } = ctx.params ctx.body = { id, name: 'user' } }) ``` -------------------------------- ### db.connect() Usage Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/database-and-models.md Establish a database connection using the static connect method and retrieve the Sequelize instance. ```javascript const db = require('./src/db') const sequelize = await db.connect() console.log('Database connected:', sequelize.getDatabaseName()) ``` -------------------------------- ### Create Record Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/database-and-models.md Demonstrates how to create a new record in the 'hitokoto_sentence' table using the registered HitokotoModel. ```javascript const db = require('./src/db') const HitokotoModel = await db.registerModel('hitokoto') const hitokoto = await HitokotoModel.create({ hitokoto: '一言内容', type: 'anime', from: '来源', creator: 'user123', owner: 'owner123', uuid: 'uuid-string', created_at: new Date().toISOString() }) ``` -------------------------------- ### YAML Configuration - Minimal Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Example of a minimal YAML configuration file for the logger, relying on all default settings. ```yaml # config.yml # 使用所有默认日志配置 ``` -------------------------------- ### Server Port Configuration Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Shows how to configure the server host and port in a YAML configuration file. It also illustrates how to run multiple instances on different ports for deployment. ```yaml # config.yml server: host: '0.0.0.0' port: 8000 ``` ```yaml # 实例 1 server: port: 8000 # 实例 2 server: port: 8001 # 使用反向代理(如 Nginx)均衡负载 ``` -------------------------------- ### JSON Log Format Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md An example of how log messages are formatted when JSON logging is enabled. This format includes timestamp, level, and the message content. ```json { "timestamp": "2024-06-08T10:00:00.000Z", "level": "info", "message": "Server started" } ``` -------------------------------- ### db.get() Usage Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/database-and-models.md Retrieve the current instance of the database management class. Ensures the database connection is established. ```javascript const db = require('./src/db') const dbInstance = db.get() ``` -------------------------------- ### Combine Custom Config and Development Mode Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md You can combine the --config_file and --dev arguments to start with a custom configuration in development mode. ```bash node core.js --config_file ./dev-config.yml --dev ``` -------------------------------- ### Production Environment Configuration Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md This YAML configuration is recommended for production environments, covering server, Redis, database, and telemetry settings. ```yaml name: 'hitokoto' url: 'https://your-domain.com' api_name: 'production-server-01' server: host: '0.0.0.0' port: 8000 compress_body: true redis: host: 'redis-prod.example.com' port: 6379 password: 'strong_password_here' database: 0 sentences_ab_switcher: a: 1 b: 2 workers: 0 # 自动设置 extensions: netease: true requests: enabled: true hosts: - your-domain.com telemetry: performance: true error: true usage: true debug: false database: mysql mysql: host: 'mysql-prod.example.com' port: 3306 username: 'hitokoto' password: 'strong_db_password' database: 'hitokoto_sentences' ``` -------------------------------- ### Redis Connection Refused Log Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Example log output when the application cannot connect to the Redis server. ```text [cache] Redis Connection error: Error: connect ECONNREFUSED 127.0.0.1:6379 ``` -------------------------------- ### Database Connection Failed Log Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Example log output when the application fails to establish a connection to the database. ```text [db] Database Connection failed: Error: connect ECONNREFUSED 127.0.0.1:3306 ``` -------------------------------- ### YAML Configuration - Custom Log Path Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Example of a YAML configuration file specifying a custom path for log files. ```yaml # config.yml log_path: '/var/log/hitokoto/api.log' ``` -------------------------------- ### Start HTTP Worker Pool Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Asynchronously starts the HTTP worker process pool. It creates a specified number of worker processes based on configuration, automatically adjusting to CPU core count if 'workers' is set to 0. Establishes inter-process communication between workers. ```javascript async function startWorkersPool(): Promise ``` ``` ```javascript const { startWorkersPool } = require('./src/http/primary') await startWorkersPool() console.log('HTTP Worker pool started') ``` -------------------------------- ### JSONP Request and Response Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Illustrates how to make a JSONP request using the 'callback' query parameter and the corresponding JavaScript function call response. ```http GET /?callback=myFunction ``` ```javascript myFunction({...}) ``` -------------------------------- ### Cache Key Generation Patterns Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Examples of generating cache keys using a standard format with prefixes like 'hitokoto:' and 'requests:'. Shows how to incorporate dynamic values like UUIDs and timestamps. ```javascript // 标准格式 const key = `hitokoto:sentence:${uuid}` const key = `hitokoto:bundle:${type}` const key = `requests:count:${timestamp}` // 前缀约定 const cacheKey = `cache:${key}` // Cache.set/get 自动添加 ``` -------------------------------- ### YAML Configuration - Enable JSON Logging Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Example of a YAML configuration file to enable JSON logging and disable colorized console output. ```yaml # config.yml json_logging: true log-colorize: false ``` -------------------------------- ### Get Resource Summary Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves a summary of a resource by its ID. ```APIDOC ## GET /nm/summary/:id ### Description Retrieves a summary of a resource by its ID. ### Method GET ### Endpoint /nm/summary/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the resource. ### Response #### Success Response (200) - **data** (object) - Contains the resource summary. #### Response Example ```json { "example": "{\"summary\":\"A brief summary...\"}" } ``` ``` -------------------------------- ### Get Lyric Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves the lyrics for a song by its ID. ```APIDOC ## GET /nm/lyric/:id ### Description Retrieves the lyrics for a song by its ID. ### Method GET ### Endpoint /nm/lyric/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the song. ### Response #### Success Response (200) - **data** (object) - Contains the song lyrics. #### Response Example ```json { "example": "{\"lyric\":\"Lyrics text...\"}" } ``` ``` -------------------------------- ### Worker Process Lifecycle: Startup Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Illustrates the sequence of events when a worker process starts, from being forked by the master process to loading its code, initializing the Koa application, and reporting readiness. ```text 主进程 ↓ cluster.fork() 创建 Worker ↓ Worker 进程启动 ↓ 加载 src/http/worker.js ↓ 创建 Koa 应用 ↓ 监听 HTTP 端口 ↓ 发送 'online' 消息给主进程 ``` -------------------------------- ### Get Album Information Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves information about a music album by its ID. ```APIDOC ## GET /nm/album/:id ### Description Retrieves information about a music album by its ID. ### Method GET ### Endpoint /nm/album/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the album. ### Response #### Success Response (200) - **data** (object) - Contains the album information. #### Response Example ```json { "example": "{\"id\":789,\"name\":\"Album Name\", ...}" } ``` ``` -------------------------------- ### Koa Router Loading Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Shows how to load routes into a Koa application. It involves creating a Route instance, getting the router, and then using it with the Koa app. ```javascript const Route = require('./src/route') const route = new Route() const router = await route.routes() app.use(router.routes()) ``` -------------------------------- ### Example Hitokoto Object Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/types.md A typical JavaScript object representing a 'hitokoto' entry as received from the API. ```javascript const hitokoto = { hitokoto: "我们必须拥抱变化,但不能背弃我们的价值观。", from: "杭州", from_who: "史蒂夫·乔布斯", creator: "hitokoto_user", creator_uid: "12345", reviewer: 1, uuid: "550e8400-e29b-41d4-a716-446655440000", created_at: "2023-01-15T08:30:00Z" } ``` -------------------------------- ### Get Music Details Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Fetches details for a single song or multiple songs by their IDs. ```APIDOC ## GET /nm/detail/:id ### Description Fetches details for a single song or multiple songs by their IDs. For multiple songs, provide a comma-separated list of IDs. ### Method GET ### Endpoint /nm/detail/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the song or a comma-separated list of song IDs. ### Request Example ```json { "example": "GET https://v1.hitokoto.cn/nm/detail/1234567" } ``` ### Response #### Success Response (200) - **data** (object) - Contains the song details. #### Response Example ```json { "example": "{\"id\":1234567,\"name\":\"Song Title\", ...}" } ``` ``` -------------------------------- ### Get Artist Information Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves information about a music artist by their ID. ```APIDOC ## GET /nm/artist/:id ### Description Retrieves information about a music artist by their ID. ### Method GET ### Endpoint /nm/artist/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the artist. ### Response #### Success Response (200) - **data** (object) - Contains the artist information. #### Response Example ```json { "example": "{\"id\":456,\"name\":\"Artist Name\", ...}" } ``` ``` -------------------------------- ### Extension Feature Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Enable or disable optional API extensions. For example, setting 'netease' to true enables the Netease Cloud Music API. ```yaml extensions: netease: true ``` -------------------------------- ### Performance Monitoring Log Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Shows how to log the duration of an operation to monitor performance. This involves recording the start time, executing the operation, and logging the elapsed time. ```javascript const start = Date.now() const result = await expensiveOperation() const duration = Date.now() - start logger.info(`[module] Operation took ${duration}ms`) ``` -------------------------------- ### Get Playlist Details Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves the details of a music playlist by its ID. ```APIDOC ## GET /nm/playlist/:id ### Description Retrieves the details of a music playlist by its ID. ### Method GET ### Endpoint /nm/playlist/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the playlist. ### Response #### Success Response (200) - **data** (object) - Contains the playlist details. #### Response Example ```json { "example": "{\"id\":123,\"name\":\"Playlist Name\", ...}" } ``` ``` -------------------------------- ### Broadcast Message to All Workers Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Manages a pool of Worker processes and handles inter-process communication. This example shows how to broadcast a message to all workers. ```javascript const { WorkersBridge } = require('./src/http/primary') // 向所有 Worker 广播消息 WorkersBridge.broadcast({ type: 'UPDATE', data: {...} }) // 访问 Worker 进程列表 const workers = WorkersBridge.workers.workers ``` -------------------------------- ### Inter-Process Communication Example: Master Broadcast Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Demonstrates how the master process can broadcast a 'RELOAD_DATA' message to all worker processes, instructing them to reload their configurations. ```javascript const { WorkersBridge } = require('./src/http/primary') // 通知 Worker 重新加载配置 WorkersBridge.broadcast({ type: 'RELOAD_DATA', data: { source: 'database' } }) ``` -------------------------------- ### Get Radio Program Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves a radio program by its RID. ```APIDOC ## GET /nm/dj/:rid ### Description Retrieves a radio program by its RID. ### Method GET ### Endpoint /nm/dj/:rid ### Parameters #### Path Parameters - **rid** (string) - Required - The RID of the radio program. ### Response #### Success Response (200) - **data** (object) - Contains the radio program details. #### Response Example ```json { "example": "{\"id\":101,\"name\":\"Radio Program Name\", ...}" } ``` ``` -------------------------------- ### Get Music Comments Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves comments for a song by its ID. ```APIDOC ## GET /nm/comment/music/:id ### Description Retrieves comments for a song by its ID. ### Method GET ### Endpoint /nm/comment/music/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the song. ### Response #### Success Response (200) - **data** (array) - Contains a list of comments. #### Response Example ```json { "example": "{\"comments\":[{\"user\":\"User Name\", \"content\":\"Comment text\"}, ...] }" } ``` ``` -------------------------------- ### Get Cover Image Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves a cover image by its ID and optional height. ```APIDOC ## GET /nm/picture/:id/:height? ### Description Retrieves a cover image by its ID and optional height. ### Method GET ### Endpoint /nm/picture/:id/:height? ### Parameters #### Path Parameters - **id** (string) - Required - The ID associated with the image. - **height** (integer) - Optional - The desired height of the image. ### Response #### Success Response (200) - **data** (object) - Contains the image URL. #### Response Example ```json { "example": "{\"url\":\"http://example.com/image.jpg\"}" } ``` ``` -------------------------------- ### Get Song Playback URL Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves the playback URL for a song by its ID. ```APIDOC ## GET /nm/url/:id ### Description Retrieves the playback URL for a song by its ID. ### Method GET ### Endpoint /nm/url/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the song. ### Response #### Success Response (200) - **data** (object) - Contains the song playback URL. #### Response Example ```json { "example": "{\"url\":\"http://example.com/song.mp3\"}" } ``` ``` -------------------------------- ### db.registerModel() Usage Example Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/database-and-models.md Register a data model by its name, which corresponds to a definition file in src/models/databases/. The method returns the Sequelize Model instance. ```javascript const db = require('./src/db') const HitokotoModel = await db.registerModel('hitokoto') // 现在可以使用 db.hitokoto 进行数据库操作 ``` -------------------------------- ### Get Hitokoto Sentences and Data Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Use the sentencesABSwitcher extension to retrieve sentences, category lists, or raw data from different Redis databases based on A/B state. ```javascript const AB = require('./src/extensions/sentencesABSwitcher') // 获取句子 const sentence = await AB.get('hitokoto:sentence:uuid-123') // 获取分类列表 const categories = await AB.get('hitokoto:bundle:categories') // 获取原始字符串 const raw = await AB.get('hitokoto:data', false) ``` -------------------------------- ### Get MV Information Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves information about a music video (MV) by its MVID. ```APIDOC ## GET /nm/mv/:mvid ### Description Retrieves information about a music video (MV) by its MVID. ### Method GET ### Endpoint /nm/mv/:mvid ### Parameters #### Path Parameters - **mvid** (string) - Required - The MVID of the music video. ### Response #### Success Response (200) - **data** (object) - Contains the MV information. #### Response Example ```json { "example": "{\"id\":100,\"name\":\"MV Title\", ...}" } ``` ``` -------------------------------- ### Restart API Service Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Manually restart the API service using pkill to terminate the process and then Node.js to start it again. Ensure you are in the correct directory. ```bash # 重启 Redis docker restart redis # 重启 API 服务 pkill -f 'node core' node core.js & ``` -------------------------------- ### Get Radio Program Details Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves detailed information about a radio program by its RID. ```APIDOC ## GET /nm/dj/detail/:rid ### Description Retrieves detailed information about a radio program by its RID. ### Method GET ### Endpoint /nm/dj/detail/:rid ### Parameters #### Path Parameters - **rid** (string) - Required - The RID of the radio program. ### Response #### Success Response (200) - **data** (object) - Contains the detailed radio program information. #### Response Example ```json { "example": "{\"id\":101,\"name\":\"Radio Program Name\", \"description\":\"Detailed description...\"}" } ``` ``` -------------------------------- ### Get Server Status (Dev Mode) Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Returns detailed server status information (memory, CPU, load, etc.). This endpoint is only available in dev mode. ```APIDOC ## GET /test ### Description Returns detailed server status information (memory, CPU, load, etc.). This endpoint is only available in dev mode. ### Method GET ### Endpoint /test ### Response #### Success Response (200) - **data** (object) - Contains detailed server status information. #### Response Example ```json { "example": "{\"memory\":\"100MB\", \"cpu\":\"20%\", ...}" } ``` ``` -------------------------------- ### Get MV Playback URL Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves the playback URL for a music video (MV) by its MVID. ```APIDOC ## GET /nm/mv/url/:mvid ### Description Retrieves the playback URL for a music video (MV) by its MVID. ### Method GET ### Endpoint /nm/mv/url/:mvid ### Parameters #### Path Parameters - **mvid** (string) - Required - The MVID of the music video. ### Response #### Success Response (200) - **data** (object) - Contains the MV playback URL. #### Response Example ```json { "example": "{\"url\":\"http://example.com/mv.mp4\"}" } ``` ``` -------------------------------- ### Netease Cloud Music API Error Response Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Example of an error response when the Netease Cloud Music API itself encounters an issue. ```json { "status": 500, "message": "网易云音乐 API 返回错误", "data": { "code": -1, "message": "服务器错误" }, "ts": 1717931460000 } ``` -------------------------------- ### Performance Timing Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Measure the execution time of an asynchronous operation. Records the start time, executes the operation, and calculates the duration in milliseconds. ```javascript const start = Date.now() const result = await expensiveOperation() const duration = Date.now() - start logger.info(`Operation took ${duration}ms`) ``` -------------------------------- ### Redis Connection Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Defines constant configuration for Redis connections, including host, port, password, and database. It uses nconf to get settings or defaults to common local values. ```javascript const ConnectionConfig = { host: nconf.get('redis:host') || '127.0.0.1', port: nconf.get('redis:port') || 6379, password: nconf.get('redis:password') || '', db: nconf.get('redis:database') || 0 } ``` -------------------------------- ### Get Radio Program Item Detail Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Retrieves detailed information about a specific radio program item by its ID. ```APIDOC ## GET /nm/dj/program/detail/:id ### Description Retrieves detailed information about a specific radio program item by its ID. ### Method GET ### Endpoint /nm/dj/program/detail/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the radio program item. ### Response #### Success Response (200) - **data** (object) - Contains the detailed radio program item information. #### Response Example ```json { "example": "{\"id\":102,\"title\":\"Program Item Title\", ...}" } ``` ``` -------------------------------- ### Asynchronous Data Processing in Controller Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/route-and-controller.md Example of an asynchronous controller function that validates parameters before processing the request. It demonstrates how to access route parameters, query strings, and request bodies. ```javascript // src/controllers/netease/search.js const { ValidateParams } = require('../../utils/response') module.exports = async (ctx) => { const params = Object.assign({}, ctx.params, ctx.query, ctx.request.body) // 验证参数 if (!(await ValidateParams(params, schema, ctx))) { return } // 处理请求 // ... ctx.status = 200 ctx.body = data } ``` -------------------------------- ### Inter-Process Communication Example: Worker Status Report Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Shows how a worker process can send its status, including request and error counts, to the master process using `process.send()`. The master process listens for 'WORKER_STATUS' messages. ```javascript // 在 Worker 进程中 process.send({ type: 'WORKER_STATUS', data: { workerId: process.pid, requestCount: 1000, errorCount: 5 } }) // 主进程接收 worker.on('message', (msg) => { if (msg.type === 'WORKER_STATUS') { logger.info(`Worker ${msg.data.workerId}: ${msg.data.requestCount} requests`) } }) ``` -------------------------------- ### Initialize Logging System Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Shows how to initialize and configure the Winston logging system using the asynchronous SetupLogger() function. This function reads configuration, creates log directories, and sets up console and file transports. ```javascript const { SetupLogger, logger } = require('./src/logger') async function initializeLogging() { await SetupLogger() logger.info('Logging system initialized') } initializeLogging() ``` -------------------------------- ### Error Handling within a Controller Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/route-and-controller.md Example of implementing error handling directly within a controller using a try-catch block. This allows for specific error responses to be sent. ```javascript module.exports = async (ctx) => { try { const data = await someAsyncOperation() ctx.body = { success: true, data } } catch (err) { ctx.status = 500 ctx.body = { status: 500, message: 'Internal Server Error', ts: Date.now() } } } ``` -------------------------------- ### Health Check Endpoint JSON Response Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Example JSON response from the '/ping' endpoint, indicating the API's current operational status. ```json { "status": 200, "message": "ok", "data": {}, "ts": 1717931460000 } ``` -------------------------------- ### File Transport Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Configuration properties for the file output transport. This setup logs only 'error' level messages to a file, with automatic log rotation based on size and a limit on the number of retained files. ```javascript { filename: logFile, level: 'error', handleExceptions: false, maxsize: 5242880, // 单个日志文件最大 5MB maxFiles: 10 // 最多保留 10 个日志文件 } ``` -------------------------------- ### Get Current Log Level Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Determines the appropriate log level based on the runtime environment. In development mode, it returns 'verbose' to log all messages, while in production, it returns 'info' to log only informational messages and above. ```javascript const level = getCurrentLevel() console.log('Log level:', level) // 开发模式: 'verbose' // 生产环境: 'info' ``` -------------------------------- ### Get Active Redis Client Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Retrieve the currently active ioredis client instance associated with the active A/B state. This client can be used for direct Redis operations. ```javascript const AB = require('./src/extensions/sentencesABSwitcher') const client = AB.getClient() // 执行 Redis 命令 const keys = await client.keys('hitokoto:*') ``` -------------------------------- ### Get Data from AB Switcher Cache Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Retrieves data from the active database using a Redis key. Optionally parses the retrieved data as JSON. This method is part of the ABSwitcher class for managing sentence data. ```javascript static async get(key: string, parse: boolean = true): Promise // ... implementation details ... ``` -------------------------------- ### Enable Development Mode Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Set the DEV environment variable to true to enable development mode. ```bash export DEV=true ``` -------------------------------- ### Logger Instance Usage Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Demonstrates how to use the global Winston logger instance to log messages at different severity levels. Ensure SetupLogger() is called before using these methods. ```javascript const { logger } = require('./src/logger') logger.verbose('[module] detailed information') logger.info('[module] general information') logger.warn('[module] warning message') logger.error('[module] error occurred') ``` -------------------------------- ### Basic Logging Usage Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Demonstrates basic logging practices for different message types: verbose, info, warn, and error. It's recommended to use specific module prefixes for better organization. ```javascript const { logger } = require('./src/logger') logger.verbose('[mymodule] Starting operation') logger.info('[mymodule] Operation completed') logger.warn('[mymodule] Something unexpected happened') logger.error('[mymodule] Operation failed: ' + err.stack) ``` -------------------------------- ### Worker Process Startup Flow Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Outlines the sequence of operations performed when a worker process initializes, including loading configuration, setting up the Koa application, and binding to the HTTP port. ```javascript // Worker 进程启动时执行 1. 加载配置 2. 初始化日志 3. 创建 Koa 应用 4. 加载中间件 5. 加载路由 6. 监听 HTTP 端口 7. 向主进程报告就绪 ``` -------------------------------- ### Environment Variable Overrides Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Demonstrates how to override configuration settings using environment variables. Use '.' as a separator and ensure variable names are lowercase. ```bash # 覆盖服务器端口 export SERVER.PORT=3000 # 覆盖 Redis 主机 export REDIS.HOST=redis.example.com # 覆盖 Netease 扩展 export EXTENSIONS.NETEASE=false ``` -------------------------------- ### Loading Middleware in Route Constructor Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/route-and-controller.md Demonstrates how middleware is loaded and assigned within the Route constructor, based on configuration. Middleware is expected in a specific format. ```javascript const Middleware = require('./middleware').fetch(!!nconf.get('dev')) Middleware.forEach((v) => { if (v && v[0] && v[1]) { this.middleware[v[0]] = v[1] } }) ``` ```javascript [ ['middlewareName', middlewareFunction], ['cors', koaCors()], ['logger', loggerMiddleware()], ] ``` -------------------------------- ### Fetch NetEase Cloud Music Details (JavaScript) Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Demonstrates fetching single or multiple song details from the NetEase Cloud Music API using JavaScript's 'fetch' function. ```javascript // 单个歌曲 fetch('https://v1.hitokoto.cn/nm/detail/1234567') .then(res => res.json()) .then(data => console.log(data)) // 多个歌曲 fetch('https://v1.hitokoto.cn/nm/detail/1234567,1234568,1234569') .then(res => res.json()) .then(data => console.log(data)) ``` -------------------------------- ### HTTP Server Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Configure the host, port, and compression for the HTTP server. Defaults to listening on 127.0.0.1:8000 with GZIP compression enabled. ```yaml server: host: '127.0.0.1' port: 8000 compress_body: true ``` ```yaml server: host: '0.0.0.0' port: 3000 compress_body: true ``` -------------------------------- ### Koa Middleware Loading Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Demonstrates how to load middleware for a Koa application by requiring a middleware registration module and calling its register function. ```javascript const { register } = require('./src/middleware') register(app, isDev) // 按顺序加载所有中间件 ``` -------------------------------- ### Error Logging with Stack Trace Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Illustrates how to log errors, including their stack traces, within a try-catch block. This is crucial for debugging and understanding the source of failures. ```javascript try { await riskyOperation() } catch (err) { logger.error(`[module] Operation failed: ${err.stack}`) } ``` -------------------------------- ### Enabling Netease Cloud Music Extension Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Configuration snippet to enable the Netease Cloud Music API extension by setting 'extensions.netease' to true in the config file. ```yaml # config.yml extensions: netease: true ``` -------------------------------- ### MySQL Database Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Configure the MySQL database connection, including host, port, username, password, and database name. Defaults to MySQL. ```yaml database: mysql mysql: host: 'db.example.com' port: 3306 username: 'hitokoto_user' password: 'secure_password' database: 'hitokoto_db' ``` -------------------------------- ### Worker Count Configuration: Manual Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Manually sets the number of worker processes to a specific value, for example, 4, by configuring the 'workers' parameter. ```yaml workers: 4 # 启动 4 个 Worker 进程 ``` -------------------------------- ### Commander CLI Argument Parsing Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Set up command-line argument parsing using Commander. Define options like `--config_file` and `--dev` to handle different execution environments. ```javascript const program = new (require('commander').Command)() program.option('--config_file ') program.option('--dev') program.parse(process.argv) ``` -------------------------------- ### ABSwitcher.get() Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Retrieves data from the active database using a specified key, with an option to parse the data as JSON. ```APIDOC ## Class: ABSwitcher ### Method: get() ### Description Retrieves data from the active database based on a given key. ### Parameters #### Path Parameters - **key** (string) - Required - The Redis key name. - **parse** (boolean) - Optional - Defaults to `true`. Whether to parse the retrieved data as JSON. ### Returns - **Promise** - The cached data. ``` -------------------------------- ### Check Log Directory Permissions Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Verify that the log directory has the necessary write permissions. This is a common step for troubleshooting issues where log files are not being created. ```bash ls -ld ./data/logs/ # 应该有写入权限 ``` -------------------------------- ### Applying Middleware to Specific Routes Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/route-and-controller.md Shows how to apply middleware to a specific route by listing middleware functions before the controller handler in the route definition. ```javascript router.get( '/protected', middleware.auth, controller.protected.handler ) ``` -------------------------------- ### Integrate Sentry for Error Tracking Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md This snippet shows how to integrate Sentry for capturing uncaught exceptions within the Hitokoto API. Ensure Sentry and CaptureUncaughtException are correctly imported from './src/tracing'. ```javascript const { Sentry, CaptureUncaughtException } = require('./src/tracing') const nconf = require('nconf') if (nconf.get('telemetry:error')) { try { // 业务逻辑 } catch (err) { Sentry.captureException(err) logger.error('[module] Error: ' + err.stack) } } ``` -------------------------------- ### Sentence AB Switcher Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Configure the database numbers for the A/B sentence switching mechanism, allowing for zero-downtime updates. Database 'a' is active, 'b' is standby. ```yaml sentences_ab_switcher: a: 1 b: 2 ``` -------------------------------- ### Checking Sentence Data in Redis Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Commands to list keys in Redis and verify if sentence data has been loaded. ```bash redis-cli > KEYS hitokoto:* # 应列出多个键 ``` -------------------------------- ### Correct Route Order for Specificity Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/route-and-controller.md Illustrates the correct order for defining routes in Koa-router to ensure specificity. More specific routes should be defined before more general ones. ```javascript // ✓ 正确顺序 router.get('/nm/detail/:id', handler1) router.get('/nm/:category', handler2) router.get('/nm', handler3) // ✗ 错误顺序(第一个会匹配所有) router.get('/nm', handler3) router.get('/nm/:category', handler2) router.get('/nm/detail/:id', handler1) ``` -------------------------------- ### Redis Connection Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Set up connection details for the Redis server, including host, port, password, and database number. Defaults to localhost:6379 with no password. ```yaml redis: host: '127.0.0.1' port: 6379 password: '' database: 0 ``` ```yaml redis: host: 'redis.example.com' port: 6380 password: 'your_secure_password' database: 1 ``` -------------------------------- ### YAML Configuration Loading Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Load YAML configuration files into JavaScript objects using the `js-yaml` library. Reads the file content and parses it. ```javascript const yaml = require('js-yaml') const config = yaml.load(fs.readFileSync('config.yml', 'utf8')) ``` -------------------------------- ### Check Log Level Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Inspect the current log level configuration to ensure it's set appropriately for debugging. This command helps diagnose why logs might not be appearing. ```bash echo "日志级别: $(node -e "const nconf = require('nconf'); console.log(nconf.get('dev'))")" ``` -------------------------------- ### Check Disk Space and File Permissions for Log Rotation Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/logger.md Verify available disk space and file permissions for the log directory and specific log files. This is crucial for troubleshooting log rotation issues. ```bash df -h ./data/logs/ ls -la ./data/logs/hitokoto_error.log* ``` -------------------------------- ### Test Redis Connection Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Use redis-cli to test the connection to your Redis server. Ensure the host and port are correctly configured. ```bash redis-cli -h 127.0.0.1 -p 6379 ping ``` -------------------------------- ### Koa Application Basic Settings Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Configures basic settings for a Koa application, including maximum request body size limits and enabling proxy trust to correctly handle forwarded headers. ```javascript const Koa = require('koa') const app = new Koa() // 最大请求体大小(继承自 bodyparser) app.request.jsonLimit = '10mb' app.request.formLimit = '10mb' // 代理信任 app.proxy = true // 信任 X-Forwarded-For 头 ``` -------------------------------- ### Checking Redis Connection Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Command to verify if the Redis server is running and accessible. ```bash redis-cli ping # 应返回 PONG ``` -------------------------------- ### recoverAB() Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Recovers the database state for the AB Switcher by reading A/B status information from cache and updating the active database pointer. ```APIDOC ## Function: recoverAB() ### Description Recovers the AB Switcher's database state, typically used during service restarts or recovery to synchronize status. ### Returns - **Promise** ### Usage - Reads A/B status information from cache. - Updates the active database pointer for the AB Switcher. ### Example ```javascript const utils = require('./src/utils') await utils.recoverAB() ``` ``` -------------------------------- ### db Class - Sequelize Instance Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/database-and-models.md The global Sequelize instance is initialized to null and managed by the db class. ```javascript static sequelize: Sequelize | null ``` -------------------------------- ### Lodash Utility Functions Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Demonstrates the use of Lodash functions like `compact` for removing falsy values from an array. Requires importing specific functions. ```javascript const { compact, curry } = require('lodash') const arr = [1, false, null, 'string', undefined, 42] const compacted = compact(arr) // [1, 'string', 42] ``` -------------------------------- ### Redirect to NetEase Cloud Music Page Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/endpoints.md Redirects to the official NetEase Cloud Music page for a song by its ID. ```APIDOC ## GET /nm/redirect/music/:id ### Description Redirects to the official NetEase Cloud Music page for a song by its ID. ### Method GET ### Endpoint /nm/redirect/music/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the song. ### Response #### Success Response (302) - Redirects to the NetEase Cloud Music URL. ### Response Example ```json { "example": "Redirects to: https://music.163.com/#/song?id=1234567" } ``` ``` -------------------------------- ### Memory Information Structure Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/types.md Details memory usage on the server, including total, free, and process usage in MB. ```javascript { total: number, free: number, usage: number } ``` -------------------------------- ### Conditional Route Registration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/route-and-controller.md Illustrates how to conditionally register a route based on application configuration. This allows features to be enabled or disabled dynamically. ```javascript if (nconf.get('feature:enabled')) { router.get('/feature', controller.feature.handler) } ``` -------------------------------- ### Configure Redis Password Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Update your config.yml to include the correct Redis password if authentication is required. If no password is set, use an empty string. ```yaml redis: password: 'your_correct_password' ``` ```yaml redis: password: '' ``` -------------------------------- ### Request Statistics Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Configure request statistics, including enabling the feature and specifying hosts to monitor. Statistics are stored in Redis. ```yaml requests: enabled: true hosts: - v1.hitokoto.cn - api.hitokoto.cn - sslapi.hitokoto.cn - international.v1.hitokoto.cn - api.a632079.me ``` -------------------------------- ### ConnectionConfig Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Constants for Redis connection configuration, including host, port, password, and database. ```APIDOC ## Object: ConnectionConfig ### Description Constants for Redis connection configuration. ### Properties - **host** (string) - The Redis host. Defaults to '127.0.0.1'. - **port** (number) - The Redis port. Defaults to 6379. - **password** (string) - The Redis password. Defaults to ''. - **db** (number) - The Redis database number. Defaults to 0. ``` -------------------------------- ### enableGracefullyShutdown() Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Enables a graceful shutdown mechanism by registering a listener for the process 'beforeExit' event, allowing unfinished tasks to complete. ```APIDOC ## Function: enableGracefullyShutdown() ### Description Enables a graceful shutdown mechanism for the process. ### Returns - **void** ### Usage - Registers a listener for the process `beforeExit` event. - Allows the process to complete unfinished tasks when a shutdown signal is received. ``` -------------------------------- ### Netease Cloud Music Song Object Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/types.md Represents a song object from Netease Cloud Music, including ID, name, artists, album, and duration. ```javascript { id: number, name: string, artists: Array<{ id: number, name: string, picUrl?: string }>, album: { id: number, name: string, picUrl?: string }, duration: number, publicTime: number, noCopyrightRcmd?: any, fee: number, sqMusic?: { bitrate: number, dfsId: number, extension: string, playTime: number, size: number, sr: number }, hMusic?: any, lMusic?: any, bMusic?: any } ``` -------------------------------- ### Restart Redis Service Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Use Docker to restart the Redis service if it becomes unresponsive or encounters connection issues. ```bash docker restart redis ``` -------------------------------- ### Fixing Parameter Length Validation Error Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Demonstrates correct and incorrect usage of min_length and max_length parameters for the Hitokoto API. ```javascript // 错误的请求 fetch('/?min_length=100&max_length=50') // ❌ // 正确的请求 fetch('/?min_length=50&max_length=100') // ✓ ``` -------------------------------- ### Worker Resource Management: Memory Monitoring Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Provides a code snippet for monitoring the memory usage of a worker process, specifically logging the heap usage in megabytes. ```javascript // 监控内存 const memUsage = process.memoryUsage() console.log('Heap used:', memUsage.heapUsed / 1024 / 1024, 'MB') ``` -------------------------------- ### Client Error Response - Parameter Validation Failure (400) Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/errors.md Returned when request parameters do not meet validation rules. Includes details about which parameters failed validation. ```json { "status": 400, "message": "请求参数错误", "data": { "raw_data": {...}, "details": [ { "message": "\"keyword\" must be a string", "path": ["keyword"], "type": "string.base", "context": { "label": "keyword", "value": null, "key": "keyword" } } ] }, "ts": 1717931460000 } ``` -------------------------------- ### Host Statistics Structure Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/types.md Details request statistics for a specific host, including total requests and distribution over time. ```javascript { total: number, past_minute: number, past_hour: number, past_day: number, day_map: number[] } ``` -------------------------------- ### Worker Count Configuration: Auto (Recommended) Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/http-server.md Configures the number of worker processes to automatically match the system's CPU core count by setting 'workers' to 0 in the configuration. ```yaml workers: 0 # 自动根据 CPU 核心数启动 Worker ``` ``` -------------------------------- ### Hitokoto Model Options Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/database-and-models.md Specifies model options including disabling timestamps, freezing the table name, and setting the table name to 'hitokoto_sentence'. ```javascript { timestamps: false, freezeTableName: true, tableName: 'hitokoto_sentence' } ``` -------------------------------- ### Enable Graceful Shutdown Mechanism Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/api-reference/utilities.md Enables a graceful shutdown mechanism by registering a listener for the process 'beforeExit' event. This allows the process to complete unfinished tasks when a shutdown signal is received. ```javascript function enableGracefullyShutdown(): void // ... implementation details ... ``` -------------------------------- ### Worker Process Configuration Source: https://github.com/hitokoto-osc/hitokoto-api/blob/master/_autodocs/configuration.md Specify the number of HTTP worker processes. Setting to 0 automatically adjusts based on CPU cores. ```yaml workers: 4 ``` ```yaml workers: 0 ```