import { Api, Get, Query, useContext, useInject } from "@midwayjs/hooks"; import { RedisService } from "@midwayjs/redis"; import { prisma } from "../utils/prisma"; import { getSong } from "../utils/netease"; export default Api( Get(), Query<{ play?: string }>(), async () => { const ctx = useContext(); const client = await useInject(RedisService); // 设置 Header ctx.set("access-control-allow-origin", "*"); ctx.set("access-control-allow-headers", "x-requested-with"); // 增加使用数量 await client.incr("api-next:stat:acgm"); const dbCount = await prisma.aCGM.count(); const skip = Math.floor(Math.random() * dbCount); const item = await prisma.aCGM.findMany({ take: 1, skip }); const id = item ?. [0] ?. music_id; if (!id) { return { code: 0, msg: "Failed, no data found" } } // 直接播放 if ("play" in ctx.query) { ctx.status = 302; ctx.set("location", `https://music.163.com/song/media/outer/url?id=${id}`); return ""; } // 尝试使用缓存 const cached = await client.lrange(`api-next:163:${id}`, 0, 7); if (cached.length) { return { code: 1, msg: "Success", data: { id: Number(id), title: cached[0], artist: cached[1], album: cached[2], alias: cached[3], cover: cached[4], lyric: cached[5], sub_lyric: cached[6], link: cached[7], served: Boolean(cached[8]), cached: true } }; } // 全新获取 const song = await getSong(id); if (song) { await client.rpush(`api-next:163:${id}`, song.title, song.artist, song.album, song.alias, song.cover, song.lyric, song.sub_lyric, song.link, song.served, err => { err && console.log(err); } ); await client.expire(`api-next:163:${id}`, 21600); return { code: 1, msg: "Success", data: { ...song, cached: false } }; } return { code: 1, msg: "Failed", data: undefined }; } );