feat(mastodon): add caching to mastodon

This commit is contained in:
Matyáš Caras 2023-11-23 19:24:47 +01:00
parent 5e610d9172
commit 794fd57b85
Signed by untrusted user who does not match committer: hernik
GPG key ID: 2A3175F98820C5C6
3 changed files with 22 additions and 5 deletions

View file

@ -1,3 +1,6 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
"typescript.tsdk": "node_modules/typescript/lib",
"conventionalCommits.scopes": [
"mastodon"
]
}

View file

@ -1,4 +1,5 @@
import axios from 'axios';
import { cache } from '../server';
async function findMastodonUser(username: string, host: string): Promise<string> {
const res = await axios.get(`${host}/api/v2/search?q=${username}`, {
@ -26,6 +27,11 @@ interface MastodonPost {
}
async function getLatestMastodonPost(id: string, host: string): Promise<MastodonPost> {
const cached = cache.get('mastodon') as MastodonPost | undefined;
if (cached != undefined) {
console.info('Returning mastodon from cache');
return cached;
}
const res = await axios.get(
`${host}/api/v1/accounts/${id}/statuses?limit=1&exclude_reblogs=true`,
{
@ -47,7 +53,7 @@ async function getLatestMastodonPost(id: string, host: string): Promise<Mastodon
mediaUrl.push(media['url'] as string);
}
});
return {
const postData = {
url: data['url'],
content: decodeURI(data['content']),
favourites: data['favourites_count'],
@ -55,8 +61,11 @@ async function getLatestMastodonPost(id: string, host: string): Promise<Mastodon
replies: data['replies_count'],
inReplyTo: inReplyTo,
mediaUrls: mediaUrl,
user: data['account']['username']
user: data['account']['username'],
};
cache.set('mastodon', postData);
console.info('Saved mastodon to cache');
return postData;
}
export { findMastodonUser, getLatestMastodonPost };

View file

@ -7,7 +7,12 @@ import fastifyView from '@fastify/view';
import ejs from 'ejs';
import path from 'path';
import { readFileSync } from 'fs';
import { createSchema as S, TsjsonParser, Validated } from 'ts-json-validator';
import { createSchema as S, TsjsonParser } from 'ts-json-validator';
import NodeCache from "node-cache"
const cache = new NodeCache({
stdTTL: 3600
});
// load userconfig
const parser = new TsjsonParser(
@ -102,7 +107,7 @@ const parser = new TsjsonParser(
required: ['theme'],
}),
);
export { parser };
export { parser, cache };
let userConfig;
try {