编写搜索 Controller 用于搜索种子信息
资源站、下载站这类站点,搜索基本就是主入口。不管是种子、文章还是商品,用户进来第一件事往往是「赶紧找到想要的东西」。下面借着 Egg.js,把一个 搜索 Controller 从头到尾怎么写讲清楚,包括:
- 查询参数的标准化处理
- 调用搜索 Service 获取匹配结果
- 二次查询业务数据(种子信息)
- 搜索关键词高亮与 XSS 安全处理
- 分页导航与页面渲染
不多说,直接看代码。
搜索 Controller 代码实现
该 Controller 位于 app/controller/search.js ,核心职责是 协调搜索逻辑与页面渲染 ,而不是直接处理复杂业务。
/* eslint-disable prefer-const */
'use strict';
const Controller = require('egg').Controller;
module.exports = class extends Controller {
async index() {
const query = this.ctx.query;
query.page = Number(query.page || 1) || 1;
query.rows = Number(query.rows || 10) || 10;
query.word = this.ctx.service.search.filterWord(query.word) || '';
if (Number(query.type) === 0) query.type = '';
let result = { matches: [], words: [], total: 0, time: 0 };
if (query.word) result = await this.ctx.service.search.get(query);
let torrents = [];
if (result.matches.length) {
const ids = [];
for (let i = 0; i < result.matches.length; i++) ids.push(result.matches[i].id);
torrents = await this.ctx.service.torrent.get({ ids, rows: query.rows });
// 关键词替换
for (let i = 0; i < torrents.length; i++) {
// 1. 先替换内容里面的 尖括号
torrents[i].name = torrents[i].name.replace(/</g, '<').replace(/>/g, '>');
for (let f = 0; f < torrents[i].files.length; f++) {
torrents[i].files[f].name = torrents[i].files[f].name.replace(/</g, '<').replace(/>/g, '>');
}
// 2. 再替换关键词
for (let j = 0; j < result.words.length; j++) {
const word = result.words[j];
const reg = new RegExp(word, 'gi');
torrents[i].name = torrents[i].name.replace(reg, '<em>' + word + '</em>');
for (let f = 0; f < torrents[i].files.length; f++) {
torrents[i].files[f].name = torrents[i].files[f].name.replace(reg, '<em>' + word + '</em>');
}
}
}
}
const maxPage = Math.ceil(result.total / query.rows);
const pageArray = this.ctx.helper.pageNavi(query.page, 5, maxPage);
const pagePre = '/search';
let title = '站内搜索';
if (query.page) title = '第' + query.page + '页 - ' + title;
if (query.word) title = query.word + ' 的搜索结果 - ' + title;
await this.ctx.helper.renderView('search.ejs', {
torrents,
count: result.total,
page: query.page,
pageArray,
pagePre,
maxPage,
title,
type: this.app.config.site.type,
});
}
};查询参数的预处理与安全过滤
query.page = Number(query.page || 1) || 1;
query.rows = Number(query.rows || 10) || 10;分页参数在这里做了 显式的数值转换,免得字符串混进计算里出问题,也能挡住非法参数直接干扰逻辑。
query.word = this.ctx.service.search.filterWord(query.word) || '';搜索词在进入核心搜索逻辑之前,先通过 filterWord 进行过滤,这一步通常用于:
- 去除多余空格
- 过滤非法字符
- 防止搜索引擎异常或注入问题
这段 通用逻辑很适合放到 Service 层。
搜索与业务数据的解耦设计
result = await this.ctx.service.search.get(query);搜索 Service 返回的不是完整的种子数据,长这样:
matches:匹配到的 ID 列表words:实际参与搜索的关键词total:匹配总数time:搜索耗时
这么设计是有道理的:
- 搜索引擎(如 Sphinx / ES / Meilisearch)只负责“查 ID”
- 业务数据仍然以数据库为准
然后拿 ID 再去查真正的种子信息:
torrents = await this.ctx.service.torrent.get({ ids, rows: query.rows });这是 搜索系统里典型的分层做法,以后想换搜索引擎也方便。
XSS 防护与关键词高亮
搜索结果页最容易出安全问题,尤其那个 关键词高亮。
torrents[i].name = torrents[i].name.replace(/</g, '<').replace(/>/g, '>');在插入 <em> 标签之前, 先转义尖括号 ,可以有效防止恶意 HTML 或脚本注入。
接着再替换关键词:
const reg = new RegExp(word, 'gi');
torrents[i].name = torrents[i].name.replace(reg, '<em>' + word + '</em>');这个先后顺序很要紧:
先把内容转义 → 再插入安全的高亮标签
种子内部的文件名也走了同一套逻辑,展示层统一,也安全。
分页导航与页面信息构建
const maxPage = Math.ceil(result.total / query.rows);
const pageArray = this.ctx.helper.pageNavi(query.page, 5, maxPage);分页逻辑被抽离到 helper 中,Controller 只负责传参与结果使用,保持了代码的清晰与可维护性。
页面标题也会跟着当前状态动态生成:
if (query.word) title = query.word + ' 的搜索结果 - ' + title;这样用户看着清楚,对 SEO 也好。
页面渲染与 Controller 的职责边界
最后靠这个:
await this.ctx.helper.renderView('search.ejs', { ... });把所有数据丢给视图层。Controller 不管页面长啥样,只在乎 数据全不全、安不安全。
Egg.js 推荐的正是这种做法:
- Controller:流程调度
- Service:业务逻辑
- Helper:通用工具
- View:页面展示
总结
这个搜索 Controller 代码量不大,但真实项目里搜索功能该注意的几点,基本都碰到了:
- 搜索参数规范化
- 搜索引擎与业务数据解耦
- XSS 安全处理
- 关键词高亮
- 分页与 SEO 友好设计
真到项目里,还能在这基础上往下加东西,比如:
- 搜索历史与热门关键词
- 多字段权重搜索
- 搜索结果缓存
- 搜索耗时统计与监控
要是你正拿 Egg.js 做中大型应用,这种 Controller + Service 的写法挺稳,也方便扩,可以拿去当参考。





