populateEmojisのリファクタと絵文字情報のキャッシュ (#7378)

* revert

* Refactor populateEmojis, Cache emojis

* ん

* fix typo

* コメント
This commit is contained in:
MeiMei 2021-03-22 00:44:38 +09:00 committed by GitHub
parent 2f2a8e537d
commit d1efe1d208
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 89 additions and 216 deletions

View file

@ -0,0 +1,58 @@
import { Emojis } from '../models';
import { Emoji } from '../models/entities/emoji';
import { Cache } from './cache';
import { isSelfHost, toPunyNullable } from './convert-host';
const cache = new Cache<Emoji | null>(1000 * 60 * 60);
/**
*
*/
type PopulatedEmoji = {
name: string;
url: string;
};
/**
*
* @param emojiName (:, @. (decodeReactionで可能))
* @param noteUserHost
* @returns , nullは未マッチを意味する
*/
export async function populateEmoji(emojiName: string, noteUserHost: string | null): Promise<PopulatedEmoji | null> {
const match = emojiName.match(/^(\w+)(?:@([\w.-]+))?$/);
if (!match) return null;
const name = match[1];
// クエリに使うホスト
let host = match[2] === '.' ? null // .はローカルホスト (ここがマッチするのはリアクションのみ)
: match[2] === undefined ? noteUserHost // ノートなどでホスト省略表記の場合はローカルホスト (ここがリアクションにマッチすることはない)
: isSelfHost(match[2]) ? null // 自ホスト指定
: (match[2] || noteUserHost); // 指定されたホスト || ノートなどの所有者のホスト (こっちがリアクションにマッチすることはない)
host = toPunyNullable(host);
const queryOrNull = async () => (await Emojis.findOne({
name,
host
})) || null;
const emoji = await cache.fetch(`${name} ${host}`, queryOrNull);
if (emoji == null) return null;
return {
name: emojiName,
url: emoji.url,
};
}
/**
* (, )
*/
export async function populateEmojis(emojiNames: string[], noteUserHost: string | null): Promise<PopulatedEmoji[]> {
const emojis = await Promise.all(emojiNames.map(x => populateEmoji(x, noteUserHost)));
return emojis.filter((x): x is PopulatedEmoji => x != null);
}