Paul-API-Next/src/api/netease.ts

100 lines
2.1 KiB
TypeScript

import { Api, Get, Query, useContext, useInject } from "@midwayjs/hooks";
import { RedisService } from "@midwayjs/redis";
import { getSong } from "./utils/netease";
export default Api(
Get(),
Query<{ id?: string, 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");
const { id } = ctx.query;
if (!id) {
return {
code: 0,
msg: "Failed, no id found"
}
}
// 增加使用数量
await client.incr("api-next:stat:netease");
// 直接播放
if ("play" in ctx.query) {
ctx.status = 302;
ctx.set("location", `https://music.163.com/song/media/outer/url?id=${id}`);
return "";
}
// 成功获取,设置缓存头
ctx.set("cache-control", "max-age=604800");
// 尝试使用缓存
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
};
}
);