emoji-meanings
Version:
Fetch unicode emoji information such as name, slug, description, category and the emoji version it was added in.
98 lines (86 loc) • 2.79 kB
JavaScript
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const CACHE_FILE = path.join(__dirname, 'emoji_cache.json');
const API_URL = 'https://emoji.gg/api/v2/unicode';
class EmojiCache {
constructor() {
this.emojis = [];
this.loadCache();
}
// Fetch emoji data from the API and save it to cache
async fetchEmojis() {
try {
const response = await axios.get(API_URL);
this.emojis = response.data;
this.saveCache();
} catch (error) {
console.error('Error fetching emojis:', error);
}
}
// Save the emoji data to a local cache file
saveCache() {
try {
fs.writeFileSync(CACHE_FILE, JSON.stringify(this.emojis, null, 2));
} catch (error) {
console.error('Error saving cache:', error);
}
}
// Load emoji data from the cache file if it exists
loadCache() {
if (fs.existsSync(CACHE_FILE)) {
try {
const data = fs.readFileSync(CACHE_FILE, 'utf8');
this.emojis = data ? JSON.parse(data) : [];
} catch (error) {
console.error('Error loading cache:', error);
this.emojis = [];
}
}
}
// Initialize the emoji cache by fetching data if not already loaded
async init() {
if (!this.emojis.length) {
await this.fetchEmojis();
}
}
// Search for emojis by name (case insensitive)
search(query) {
try {
return this.emojis.filter(emoji =>
emoji.name.toLowerCase().includes(query.toLowerCase())
);
} catch (error) {
console.error('Error searching emojis:', error);
return [];
}
}
// Filter emojis by their category
filterByCategory(category) {
try {
return this.emojis.filter(emoji => emoji.category === category);
} catch (error) {
console.error('Error filtering emojis by category:', error);
return [];
}
}
// List all stored emojis
listAll() {
try {
return this.emojis;
} catch (error) {
console.error('Error listing all emojis:', error);
return [];
}
}
// Retrieve an emoji by its Unicode value
getByUnicode(unicode) {
try {
return this.emojis.find(emoji => emoji.unicode === unicode) || null;
} catch (error) {
console.error('Error getting emoji by unicode:', error);
return null;
}
}
}
module.exports = new EmojiCache();