123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284 |
- 我基于你的代码做了一些调整,接下来请更新记忆:
- 1. index2.js
- import Fastify from 'fastify';
- import * as drpy from './libs/drpy.js';
- import path from 'path';
- import {fileURLToPath} from 'url';
- const fastify = Fastify({logger: true});
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
- console.log('__dirname:', __dirname);
- // 动态加载模块并根据 query 执行不同逻辑
- fastify.get('/api/:module', async (request, reply) => {
- const moduleName = request.params.module;
- const query = request.query; // 获取 query 参数
- const modulePath = path.join(__dirname, 'js', `${moduleName}.js`);
- try {
- // 根据 query 参数决定执行逻辑
- if ('play' in query) {
- // 处理播放逻辑
- const result = await drpy.play(modulePath);
- return reply.send(result);
- }
- if ('ac' in query && 't' in query) {
- // 分类逻辑
- const result = await drpy.cate(modulePath);
- return reply.send(result);
- }
- if ('ac' in query && 'ids' in query) {
- // 详情逻辑
- const result = await drpy.detail(modulePath);
- return reply.send(result);
- }
- if ('wd' in query) {
- // 搜索逻辑
- const result = await drpy.search(modulePath);
- return reply.send(result);
- }
- if ('refresh' in query) {
- // 强制刷新初始化逻辑
- const refreshedObject = await drpy.init(modulePath, true);
- return reply.send(refreshedObject);
- }
- // 默认逻辑,返回 home + homeVod 接口
- const result_home = await drpy.home(modulePath);
- const result_homeVod = await drpy.homeVod(modulePath);
- const result = {
- class: result_home,
- list: result_homeVod
- }
- reply.send(result);
- } catch (error) {
- console.log('Error processing request:', error);
- reply.status(500).send({error: `Failed to process request for module ${moduleName}: ${error.message}`});
- }
- });
- // 启动服务
- const start = async () => {
- try {
- await fastify.listen(5757);
- console.log('Server listening at http://localhost:5757');
- } catch (err) {
- fastify.log.error(err);
- process.exit(1);
- }
- };
- start();
- 2. libs/drpy.js
- import * as utils from '../utils/utils.js'; // 使用 import 引入工具类
- import {readFile} from 'fs/promises';
- import vm from 'vm'; // Node.js 的 vm 模块
- const {req} = await import('../utils/req.js');
- const {sleep, sleepSync} = await import('../utils/utils.js');
- // 缓存已初始化的模块
- const moduleCache = new Map();
- /**
- * 初始化模块:加载并执行模块文件,存储初始化后的 rule 对象
- * 如果存在 `预处理` 属性且为函数,会在缓存前执行
- * @param {string} filePath - 模块文件路径
- * @param refresh 强制清除缓存
- * @returns {Promise<object>} - 返回初始化后的模块对象
- */
- export async function init(filePath, refresh) {
- if (moduleCache.has(filePath) && !refresh) {
- console.log(`Module ${filePath} already initialized, returning cached instance.`);
- return moduleCache.get(filePath);
- }
- try {
- let t1 = utils.getNowTime();
- // 读取 JS 文件的内容
- const fileContent = await readFile(filePath, 'utf-8');
- // 创建一个沙箱上下文,注入需要的全局变量和函数
- const sandbox = {
- console,
- req,
- sleep,
- sleepSync,
- utils,
- rule: {}, // 用于存放导出的 rule 对象
- };
- // 创建一个上下文
- const context = vm.createContext(sandbox);
- // 执行文件内容,将其放入沙箱中
- const script = new vm.Script(fileContent);
- script.runInContext(context);
- // 访问沙箱中的 rule 对象
- const moduleObject = utils.deepCopy(sandbox.rule);
- // 检查并执行 `预处理` 方法
- if (typeof moduleObject.预处理 === 'function') {
- console.log('Executing preprocessing...');
- await moduleObject.预处理();
- }
- // 缓存初始化后的模块
- moduleCache.set(filePath, moduleObject);
- let t2 = utils.getNowTime();
- moduleObject.cost = t2 - t1;
- return moduleObject;
- } catch (error) {
- console.log('Error in drpy.init:', error);
- throw new Error('Failed to initialize module');
- }
- }
- /**
- * 调用模块的指定方法
- * @param {string} filePath - 模块文件路径
- * @param {string} method - 要调用的属性方法名称
- * @returns {Promise<any>} - 方法调用的返回值
- */
- async function invokeMethod(filePath, method) {
- const moduleObject = await init(filePath); // 确保模块已初始化
- if (moduleObject[method] && typeof moduleObject[method] === 'function') {
- return await moduleObject[method](); // 调用对应的方法
- } else {
- throw new Error(`Method ${method} not found in module ${filePath}`);
- }
- }
- // 各种接口调用方法
- export async function home(filePath) {
- return await invokeMethod(filePath, 'class_parse');
- }
- export async function homeVod(filePath) {
- return await invokeMethod(filePath, '推荐');
- }
- export async function cate(filePath) {
- return await invokeMethod(filePath, '一级');
- }
- export async function detail(filePath) {
- return await invokeMethod(filePath, '二级');
- }
- export async function search(filePath) {
- return await invokeMethod(filePath, '搜索');
- }
- export async function play(filePath) {
- return await invokeMethod(filePath, 'lazy');
- }
- 3.utils/req.js
- export async function req(param) {
- // 模拟异步请求
- return new Promise((resolve) => {
- setTimeout(() => {
- resolve(`Response for ${param}`);
- }, 1000);
- });
- }
- 4.utils/utils.js
- // utils.js: 存放工具类方法
- import pkg from 'lodash';
- const {cloneDeep} = pkg;
- export function getTitleLength(title) {
- return title.length; // 返回标题长度
- }
- export function getNowTime() {
- return (new Date()).getTime()
- }
- export async function sleep(ms) {
- // 模拟异步请求
- return new Promise((resolve) => {
- setTimeout(() => {
- resolve();
- }, ms);
- });
- }
- export function sleepSync(ms) {
- const end = Date.now() + ms; // 获取当前时间并计算结束时间
- while (Date.now() < end) {
- // 阻塞式等待,直到时间到达
- }
- }
- export const deepCopy = cloneDeep
- 5. js/_360.js
- // js/_360.js
- var rule = {
- title: '标题1',
- description: '这是描述',
- category: '视频',
- class_parse: async () => {
- console.log('执行了分类获取')
- return [
- {type_id: '1', type_name: '电影'},
- {type_id: '2', type_name: '电视剧'},
- {type_id: '3', type_name: '综艺'},
- {type_id: '4', type_name: '动漫'},
- ]
- },
- 预处理: async () => {
- console.log('执行了预处理')
- rule.title = '360影视'
- },
- 推荐: async () => {
- sleepSync(2000);
- console.log('进入了推荐')
- // return '这是推荐:' + rule.title
- return [
- {vod_name: '测试电影1', vod_pic: '1.png', vod_remarks: '测试描述1', vod_id: 'http://www.1.com'},
- {vod_name: '测试电影2', vod_pic: '2.png', vod_remarks: '测试描述2', vod_id: 'http://www.2.com'},
- ]
- },
- 一级: async () => {
- // await sleep(200);
- sleepSync(200);
- let html = await req('123');
- console.log('title:', rule.title);
- console.log('html:' + html);
- return html + '\n' + '这是一级:' + rule.title
- },
- 二级: async () => {
- return '这是二级:' + rule.title
- },
- 搜索: async () => {
- return '这是搜索:' + rule.title
- },
- lazy: async () => {
- return '这是播放:' + rule.title
- },
- };
|