收藏

    <?php
    $path='D:/wamp/www/DolrPHP/Smarty';
    function loseWeight($path){
        $handle=opendir($path);
        readdir($handle);//.
        readdir($handle);//..
        while($file=readdir($handle)){
            $newPath=$path.'/'.$file;
            if(is_dir($newPath))
                loseWeight($newPath);
            else{
                //去掉注释行---
                $content=file_get_contents($newPath);
                $mode=array('/\/\*\*?(.*?)\*\//is','/^\s*$/iU');
                $newContent=preg_replace($mode,"",$content);
                file_put_contents($newPath,$newContent);
                //-----
                // 去掉空白行
                $content='';
                $fp=fopen($newPath,'r');
                while(!feof($fp)){
                    $line=trim(fgets($fp));
                    if(strlen($line)<=0){
                        continue;
                    }
                    $content.=$line."\n";
                }
                file_put_contents($newPath,$content);
                echo '文件'.$newPath.'瘦身完成!<br />';
            }
        }
    }
    show($path);


最新收藏列表:    (4) [{…}, {…}, {…}, {…}] 取消收藏的参数:    {contentid: "craft-001", type: "craft", _openid: "o9I9A1-D1fVtSzy7Emrx4cduPZfU"} 最新收藏列表:    (4) [{…}, {…}, {…}, {…}]// cloudfunctions/getCraftData/index.js // 支持:轮播图/热门非遗手作(城市+类型筛选)/非遗知识库/知识答题/手作地图/用户分享作品/收藏/点赞/记录保存 等操作 const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) const db = cloud.database() const _ = db.command; // 引入数据库操作符(自增/自减) // 云函数入口函数 exports.main = async (event, context) => { // 解构所有参数 const { queryType, city, craftType, _id, keyword,num, topicId, openid, workId, content, userName, userAvatar, type: recordType, contentId, title, learnTime, imgUrl, isCorrect, userAnswer, correctAnswer, score, totalScore, totalNum, correctNum, type: collectType, isCollect, _openid } = event; const wxContext = cloud.getWXContext();//获取当前用户的 _openid(云函数自动获取,数据库存储用) const currentOpenid = wxContext.OPENID; // 这是数据库里存储的 _openid 字段 const userOpenid = _openid || currentOpenid; // 优先用传入的openid,否则用当前用户 try { // ========== 1. 轮播图查询 ========== if (queryType === 'banner') { const res = await db.collection('banner') .where({ isActive: true // 只查有效轮播图 }) .get(); return { success: true, data: res.data };// 返回轮播图数据(含 images 数组) } // ========== 2. 热门非遗手作 ========== // 2.1 查询热门非遗手作列表 else if (queryType === 'hotCraft') { let query = {}; // 基础查询条件(可根据需求加,比如只查热门:isHot: true) // 地域筛选:前端传"全部"则忽略,否则匹配city字段 if (city && city !== '全部') query.region = city; // 工艺类型筛选:同理 if (craftType && craftType !== '全部') query.type = craftType; // 关键词搜索:匹配标题/描述 if (keyword) { query.$or = [ { title: db.RegExp({ regexp: keyword, options: 'i' }) }, { desc: db.RegExp({ regexp: keyword, options: 'i' }) } ]; } // 查询craft集合(热门手作所在集合) const res = await db.collection('craft') .where(query) .orderBy('viewCount', 'desc') // 按浏览量倒序,体现“热门” .get(); return { success: true, data: res.data }; } //2.2查询单条热门非遗手作的详情 else if (queryType === 'hotCraftDetail') { if (!_id) return { success: false, errMsg: '缺少手作ID' }; // 查询 craft 集合的单条详情 const res = await db.collection('craft').doc(_id).get(); return { success: true, data: res.data }; } // ========== 3. 科普知识库 ========== // 3.1 查询科普知识库 else if (queryType === 'science') { const res = await db.collection('science') .where({ isActive: true }) .orderBy('createTime', 'desc') // 按时间倒序排列 .get(); return { success: true, data: res.data }; } // 3.2.查询科普详情 else if (queryType === 'scienceDetail') { if (!_id) return { success: false, errMsg: '缺少科普_id' }; const res = await db.collection('science').doc(_id).get(); return { success: true, data: res.data || {} }; } // ========== 4. 答题相关 ========== // 4.1 查询答题题库总数 else if (queryType === 'examCount') { const res = await db.collection('examQuestion') .where({ isActive: true }) .count(); // 统计有效题目总数 return { success: true, data: res.total }; } // 4.1. 查询单道答题 else if (queryType === 'exam') { if (!num) return { success: false, errMsg: '缺少题目序号' }; const res = await db.collection('examQuestion') .where({ isActive: true, questionNum: num + '' // 匹配题目序号(数据库存字符串,需转义) }) .get(); if (res.data.length === 0) { return { success: false, errMsg: `第${num}题不存在` }; } // 组装选项数组(前端需要数组格式渲染选项) const question = res.data[0]; const options = [ question.optionA || '', // 兼容字段缺失的情况 question.optionB || '', question.optionC || '', question.optionD || '' ]; return { success: true, data: { ...question, options: options } // 合并原字段+新增options数组 }; } // ========== 5. 手作地图 ========== else if (queryType === 'craftMap') { const res = await db.collection('craftMap').get(); return { success: true, data: res.data }; } // ========== 6. 用户分享作品 ========== // 6.1 所有用户分享列表(广场) else if (queryType === 'shareList') { let query = {}; // 话题筛选:如果topicId不是all,就筛选对应话题 if (topicId && topicId !== 'all') { query.topicId = topicId; } const res = await db.collection('share') .where(query) // 新增:应用话题筛选条件 .orderBy('createTime', 'desc') .get(); console.log('share集合查询结果:', res.data); // 云开发控制台会显示这行日志 return { success: true, data: res.data }; } // 6.2 我的分享作品列表(个人中心) else if (queryType === 'myShareList') { const targetOpenid = openid || currentOpenid; if (!targetOpenid) return { success: false, errMsg: '无法获取用户信息' }; const res = await db.collection('share') .where({ _openid: targetOpenid }) .orderBy('createTime', 'desc') .get(); return { success: true, data: res.data }; } // 6.3 分享作品总数 else if (queryType === 'shareCount') { const res = await db.collection('share').count(); return { success: true, data: res.total }; } // 6.4 单篇用户作品详情(userWorkDetail) else if (queryType === 'userWorkDetail') { // 必须传递作品的_id才能查询 if (!_id) { return { success: false, errMsg: '缺少作品_id' }; } // 从share集合中查询对应_id的作品详情 const res = await db.collection('share').doc(_id).get(); // 如果查询结果为空(作品不存在或已删除) if (!res.data) { return { success: false, errMsg: '该作品不存在或已删除' }; } // 查询该作品的评论列表 const commentRes = await db.collection('comment') .where({ workId: _id }) // 关联作品ID(评论集合的workId对应作品_id) .orderBy('createTime', 'desc') // 按评论时间倒序排列 .get(); //把评论列表合并到返回数据中 const workData = { ...res.data, commentList: commentRes.data || [] // 新增commentList字段 }; // 返回包含评论列表的作品数据 return { success: true, data: workData }; } // ========== 7. 发布评论(addComment) ========== else if (queryType === 'addComment') { // 校验必要参数 if (!workId || !content || !currentOpenid) { return { success: false, errMsg: '缺少评论必要参数' }; } // 向comment集合添加评论 await db.collection('comment').add({ data: { workId: workId, // 关联的作品ID content: content, // 评论内容 userName: userName || '非遗爱好者', // 评论者昵称(默认值) userAvatar: userAvatar || '', // 评论者头像(默认空) _openid: currentOpenid, // 评论者OpenID createTime: db.serverDate() // 服务器时间(自动生成) } }); // 同步更新share集合的评论数(+1) await db.collection('share').doc(workId).update({ data: { commentNum: db.command.inc(1) // 评论数自增1 } }); return { success: true }; } // ========== 8. 保存各类记录(saveAllRecord) ========== else if (queryType === 'saveAllRecord') { // 校验用户身份 if (!currentOpenid) return { success: false, errMsg: '请登录后操作' }; // 8.1 保存【学习记录】(craft/science) if (recordType === 'learn_craft' || recordType === 'learn_science') { // 校验学习记录必填参数 if (!contentId || !title || learnTime === undefined) { return { success: false, errMsg: '学习记录缺少必填参数(内容ID/标题/时长)' }; } // 存到learningRecord集合,contentType区分craft/science await db.collection('learningRecord').add({ data: { _openid: currentOpenid, contentId, title, learnTime, contentType: recordType === 'learn_craft' ? 'craft' : 'science', // 关键:标记类型 imgUrl: imgUrl || '', createTime: db.serverDate() } }); return { success: true, errMsg: recordType === 'learn_craft' ? '手作学习记录保存成功' : '知识库学习记录保存成功' }; } // 8.2 保存【答题记录】(单题/总分) else if (recordType === 'exam') { if (!contentId || isCorrect === undefined || !userAnswer || !correctAnswer || score === undefined) { return { success: false, errMsg: '单题记录缺少必填参数' }; } // 存到examRecord集合 await db.collection('examRecord').add({ data: { _openid: currentOpenid, contentId, isCorrect, userAnswer, correctAnswer, score, createTime: db.serverDate() } }); return { success: true, errMsg: '单题答题记录保存成功' }; } else if (recordType === 'examTotal') { if (!totalScore || !totalNum || !correctNum) { return { success: false, errMsg: '总分记录缺少必填参数' }; } // 存到examTotalRecord集合 await db.collection('examTotalRecord').add({ data: { _openid: currentOpenid, totalScore, totalNum, correctNum, accuracy: (correctNum / totalNum * 100).toFixed(1) + '%', createTime: db.serverDate() } }); return { success: true, errMsg: '答题总分记录保存成功' }; } else { return { success: false, errMsg: '无效的记录类型' }; } } // ========== 9. 收藏/取消收藏(collect) ========== else if (queryType === 'collect') { // 9.1 仅查询收藏状态 if (!isCollect && event.action !== 'operate') { if (!collectType || !userOpenid || !['craft', 'share'].includes(collectType)) { return { success: false, errMsg: '查询参数缺失/类型无效' }; } try { const relateField = collectType === 'craft' ? 'craftId' : 'shareId'; const targetCollection = collectType; // 步骤1:先查询用户该类型的所有收藏(初始化allCollect) const allCollect = await db.collection('collect') .where({ _openid: userOpenid, type: collectType }) .get(); // 步骤2:再查询当前作品是否被收藏 const collectRes = await db.collection('collect') .where({ [relateField]: _id, // 匹配存储的craftId/shareId _openid: userOpenid }) .get(); console.log('匹配到的收藏记录:', collectRes.data); // 新增日志 // 遍历收藏记录,关联查询原内容的标题/图片 const allCollectWithDetail = await Promise.all( allCollect.data.map(async (item) => { const contentRes = await db.collection(targetCollection).doc(item[relateField]).get(); const contentData = contentRes.data || {}; return { ...item, title: contentData.title || '未命名', // 补充标题 imgUrl: contentData.imgUrl || (contentData.imgList && contentData.imgList[0]) || '', // 补充图片 desc: contentData.desc || contentData.intro || '' // 补充描述 }; }) ); return { success: true, isCollected: collectRes.data.length > 0, // 当前作品是否收藏 data: allCollectWithDetail }; } catch (err) { return { success: false, errMsg: '查询失败:' + err.message }; } } // 9.2 收藏/取消收藏操作 if (!collectType || !_id || !userOpenid || !['craft', 'share'].includes(collectType)) { return { success: false, errMsg: '缺少参数或类型无效(仅支持craft/share)' }; } try { const relateField = collectType === 'craft' ? 'craftId' : 'shareId'; const targetCollection = collectType; // 查询是否已收藏 const collectRes = await db.collection('collect') .where({ [relateField]: _id, _openid: userOpenid }) .get(); console.log('操作前匹配的收藏记录:', collectRes.data); // 收藏逻辑 + 更新总收藏数 if (isCollect) { if (collectRes.data.length === 0) { // 1. 添加收藏记录到collect集合 await db.collection('collect').add({ data: { [relateField]: _id, type: collectType, _openid: userOpenid, collectTime: db.serverDate() } }); // 2. 原内容的收藏数加1 await db.collection(targetCollection).doc(_id).update({ data: { collectNum: _.inc(1) } }); // 3. 标记原内容为已收藏 await db.collection(targetCollection).doc(_id).update({ data: { isCollected: true } }); console.log('收藏成功,已添加记录'); } } else { // 取消收藏逻辑 if (collectRes.data.length > 0) { // 1. 删除collect集合中的这条收藏记录 await db.collection('collect').doc(collectRes.data[0]._id).remove(); // 2. 原内容的收藏数减1(最小为0) await db.collection(targetCollection).doc(_id).update({ data: { collectNum: _.inc(-1).min(0) } }); // 3. 标记原内容为未收藏 await db.collection(targetCollection).doc(_id).update({ data: { isCollected: false } }); console.log('取消收藏成功,已删除记录:', collectRes.data[0]._id); } } // 3. 强制把原内容的isCollected字段设为false await db.collection(targetCollection).doc(_id).update({ data: { isCollected: isCollect } }); return { success: true, errMsg: isCollect ? `${collectType === 'craft' ? '手作' : '作品'}收藏成功` : `${collectType === 'craft' ? '手作' : '作品'}取消收藏成功` }; } catch (err) { console.error('收藏操作失败:', err); return { success: false, errMsg: '操作失败:' + err.message }; } } // ========== 无效查询类型 ========== else { const validTypes = ['banner', 'hotCraft', 'hotCraftDetail', 'science', 'scienceDetail', 'examCount', 'exam', 'craftMap', 'shareList', 'myShareList', 'shareCount', 'userWorkDetail', 'addComment', 'saveAllRecord']; return { success: false, errMsg: `无效的查询类型,支持类型:${validTypes.join('/')}` }; } } catch (err) { console.error('查询失败:', err); // 云开发控制台打印错误日志 return { success: false, errMsg: `查询异常:${err.message}` }; } };怎么解决取消收藏后还是处于收藏状态的
最新发布
12-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chaojie2009

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值