Feat: Install Redis & Test API

安装 Redis,测试编写必应和状态 API(昨晚应该提交的
This commit is contained in:
2022-04-10 14:15:40 +08:00
parent 30062e5d99
commit c2999ea5e7
5 changed files with 172 additions and 1 deletions
+63
View File
@@ -0,0 +1,63 @@
import { Api, Get, Query, useContext } from '@midwayjs/hooks';
import fetch from 'isomorphic-unfetch';
import { client } from '../utils/redis';
export default Api(
Get(),
Query<{ info: undefined }>(),
async (ddd) => {
const ctx = useContext();
// 增加使用数量
await client.incr("api-next:stat:bing");
const cache = await client.lRange("api-next:bing", 0, 2);
let image;
if (cache.length) {
image = {
url: cache[0],
copyright: cache[1],
};
}
else {
const response = await fetch("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1", {
headers: {
"cache-control": "max-age=0",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36"
}
});
const json = await response.json();
image = {
url: `https://cn.bing.com${json.images[0].url}`,
copyright: json.images[0].copyright,
};
await client.rPush("api-next:bing", [image.url, image.copyright]);
await client.expire("api-next:bing", 21600);
}
// 获取失败
if (!image) {
return {
code: 0,
msg: "Failed"
}
}
// 没有 info,跳转图片地址
if (!("info" in ctx.query)) {
ctx.status = 302;
ctx.set('location', image.url);
}
return {
code: 1,
data: image,
cached: cache.length ? true : false
};
}
);
+20
View File
@@ -0,0 +1,20 @@
import { Api, Get } from '@midwayjs/hooks';
import { client } from '../utils/redis';
export default Api(Get(), async (repo: string) => {
const neteaseStat = await client.get("api-next:stat:netease");
const bingStat = await client.get("api-next:stat:bing");
return {
code: 1,
data: {
wallpaper: -1,
netease: Number(neteaseStat),
music: -1,
avatar: -1,
bili: -1,
bing: Number(bingStat),
}
};
});
+13
View File
@@ -0,0 +1,13 @@
import { createClient, RedisClientType } from 'redis';
export let client: RedisClientType;
(async () => {
client = createClient({
url: 'redis://127.0.0.1:6379'
});
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
})();