云函数的使用
cloudfunctions 目录 右键 新建 Node.js 云函数
> 输入目录名 getPlaylist
在云函数中向第三方服务器发送请求要依赖第三方库
安装依赖包
云函数目录 getPlaylist
右键 在终端打开
打开命令行 输入命令:
1 2
| npm install --save request npm install --save request-promise
|
github request-promise:https://github.com/request/request-promise
然后写相应代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const cloud = require("wx-server-sdk");
cloud.init();
const rp = require("request-promise");
const URL = "http://musicapi.xiecheng.live/personalized";
exports.main = async (event, context) => { const playlist = await rp(URL).then((res) => { return JSON.parse(res).result; }); console.log(playlist); };
|
写完代码,云函数目录 getPlaylist
右键 上传并部署:云端安装依赖(不上传node_modules)
进行上传部署代码到云端,等待上传成功,打开云开发控制台即可看到已经上传的云函数,并可对云函数进行测试。
数据库操作
数据库> 创建集合 > playlist
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| const cloud = require("wx-server-sdk");
cloud.init();
const db = cloud.database();
const rp = require("request-promise");
const URL = "http://musicapi.xiecheng.live/personalized";
const playlistCollection = db.collection("playlist");
const MAX_LIMIT = 10;
exports.main = async (event, context) => {
const countResult = await playlistCollection.count(); const total = countResult.total; const batchTimes = Math.ceil(total / MAX_LIMIT); const tasks = []; for (let i = 0; i < batchTimes; i++) { let promise = playlistCollection .skip(i * MAX_LIMIT) .limit(MAX_LIMIT) .get(); tasks.push(promise); } let list = { data: [], }; if (tasks.length > 0) { list = (await Promise.all(tasks)).reduce((acc, cur) => { return { data: acc.data.concat(cur.data), }; }); }
const playlist = await rp(URL).then((res) => { return JSON.parse(res).result; });
const newData = []; for (let i = 0, len1 = playlist.length; i < len1; i++) { let flag = true; for (let j = 0, len2 = list.data.length; j < len2; j++) { if (playlist[i].id === list.data[j].id) { flag = false; break; } } if (flag) { newData.push(playlist[i]); } }
for (let i = 0, len = newData.length; i < len; i++) { await playlistCollection .add({ data: { ...newData[i], createTime: db.serverDate(), }, }) .then((res) => { console.log("数据添加成功"); }) .catch((err) => { console.error(err); }); } return newData.length; };
|
查询数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
const cloud = require("wx-server-sdk");
cloud.init();
const TcbRouter = require("tcb-router"); const db = cloud.database(); const blogCollection = db.collection("blog");
exports.main = async (event, context) => { const app = new TcbRouter({ event });
app.router("list", async (ctx, next) => { ctx.body = await blogCollection .skip(event.start) .limit(event.count) .orderBy("createTime", "desc") .get() .then((res) => { return res.data; }); });
return app.serve(); };
|
云函数调试
云控制台中可会云函数进行云端测试
在小程序调用云函数后,可查看云函数日志