💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
### 创建 Controller MVC 模型中,控制器是用户请求的逻辑处理部分。比如:将用户相关的操作都放在`news.js`里,每一个操作就是里面一个 Action。 项目中的 controller 需要继承`think.Controller`类,这样能使用一些内置的方法。当然项目中可以创建一些通用的基类,然后实际的 controller 都继承自这个基类。 项目创建时会自动创建了一个名为`base.js`的基类,其他 controller 继承该类即可。 ### 创建News控制器 创建文件 /src/controller/api/portal/news.js 输入以下内容 ~~~ const Base = require("../../base.js"); import Mock from "mockjs"; module.exports = class extends Base { async getListAction(map = { page: 1, pageSize: 10 }) { let { page, pageSize } = map; let mockOptions = { count: 200, totalPages: 20, pageSize: pageSize, currentPage: page, "data|20": [ { "id|+1": 1, // 属性 id 是一个自增数,起始值为 1,每次增 1 title: "@ctitle(10,30)", cover: "@image('300x200', '#50B347')", create_at: "@date()", abstract: "@cparagraph(3,50)", }, ], }; let data = await Mock.mock(mockOptions); return this.success(data); } async getDetailAction(id) { //模拟一段Markdown文本,实际从该数据库中读取或者从文件中读取 let markdown = await Mock.mock({ description: "@cparagraph(100)", }); const html = think.service("marked").markdownToHtml(markdown.description); let mockOptions = { id: 1, // 属性 id 是一个自增数,起始值为 1,每次增 1 title: "异步处理", create_at: "@date()", cover: "@image('1024x200', '#50B347')", abstract: "@cparagraph(100)", description: html, author: "@cname()", "category_label|1": ["团队动态", "行业报告"], }; let data = await Mock.mock(mockOptions); return this.success(data); } }; ~~~ ### 能力提升 1、实现从数据库中读取新闻列表和新闻详情 ``` module.exports = class extends think.Controller { __before() { } // http://127.0.0.1:8360/api/portal/news/getDetail?id=1 async getDetailAction() { let id = this.get('id'); let map = { id }; let field = "id,title,author,cover_image,abstract,description,create_at"; let data = await this.model("portal_news").field(field).where(map).find(); think.logger.debug(data); return this.success(data); } // http://127.0.0.1:8360/api/portal/news/getList async getListAction() { let id = this.get('id'); let page = this.get('page') || 1; let pageSize = this.get('pageSize') || 10; let map = {}; let field = "id,title,author,cover_image,abstract,description,create_at"; //SELECT `id`,`title`,`author`,`cover_image`,`abstract`,`description`,`create_at` FROM `think_portal_news` WHERE ( `id` = '1' ) ORDER BY sort desc LIMIT 0,10 let data = await this.model("portal_news").field(field).where(map).order("sort desc").page(page, pageSize).countSelect(); think.logger.debug(data); return this.success(data); } }; ```