refactor for reduced repetition
This commit is contained in:
@@ -10,12 +10,12 @@ module.exports = {
|
||||
.setDescription('Full war earnings total before cuts')),
|
||||
async execute(interaction) {
|
||||
const total = interaction.options.getInteger('total');
|
||||
const lastWarRaw = await torn.api('https://api.torn.com/v2/faction/rankedwars?offset=0&limit=1&sort=DESC');
|
||||
const lastWarID = lastWarRaw.rankedwars[0].id
|
||||
const lastWar = await torn.api(`https://api.torn.com/v2/faction/${lastWarID}/rankedwarreport?`);
|
||||
const ourMembers = lastWar.rankedwarreport.factions.find(faction => faction.id === 53026).members; // TODO: dont hardcore faction ID
|
||||
const lastWarRaw = await torn.faction.rankedWars({ offset: 0, limit: 1, sort: 'DESC' });
|
||||
const lastWarID = lastWarRaw[0].id
|
||||
const lastWar = await torn.faction.rankedWarReport(lastWarID);
|
||||
const ourMembers = lastWar.factions.find(faction => faction.id === 53026).members; // TODO: dont hardcore faction ID
|
||||
let totalParticipants = 0;
|
||||
let message = `# War Payout Calculation for War against ${lastWar.rankedwarreport.factions.find(faction => faction.id !== 53026).name} with total earnings of $${total.toLocaleString()}:\n`;
|
||||
let message = `# War Payout Calculation for War against ${lastWar.factions.find(faction => faction.id !== 53026).name} with total earnings of $${total.toLocaleString()}:\n`;
|
||||
ourMembers.forEach(member => {
|
||||
if (member.id == 2993713) {
|
||||
console.log(`User ${member.name} is calculated separately.`);
|
||||
|
||||
@@ -4,7 +4,7 @@ module.exports = async (client, torn, config) => {
|
||||
const channel = client.channels.resolve(config.channels.ocAlert);
|
||||
const now = new Date();
|
||||
const state = require('../state.json');
|
||||
const data = await torn.api(`https://api.torn.com/v2/faction/crimes?cat=planning&sort=DESC`);
|
||||
const data = { crimes: await torn.faction.crimes({ category: 'planning', sort: 'DESC' }) };
|
||||
let itemsneeded = 0;
|
||||
let message = "OCs with unavailable items:\n";
|
||||
for (const crime of data.crimes) {
|
||||
@@ -36,13 +36,13 @@ module.exports = async (client, torn, config) => {
|
||||
);
|
||||
channel.send({ content: message, components: [row] });
|
||||
state.itemAlertLast = now.toISOString();
|
||||
fs.writeFile('./state.json', JSON.stringify(state, null, 4), err => {if (err) {console.error(err)}});
|
||||
fs.writeFile('./state.json', JSON.stringify(state, null, 4), err => { if (err) { console.error(err) } });
|
||||
} else { console.debug(`noItemOC: Would send alert, but one was sent recently`); }
|
||||
} else {
|
||||
console.debug(`noItemOC: Nobody needs items, not sending alert`);
|
||||
const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
state.itemAlertLast = twentyFourHoursAgo.toISOString();
|
||||
fs.writeFile('./state.json', JSON.stringify(state, null, 4), err => {if (err) {console.error(err)}});
|
||||
fs.writeFile('./state.json', JSON.stringify(state, null, 4), err => { if (err) { console.error(err) } });
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
@@ -40,7 +40,8 @@ module.exports = async (client, torn, config) => {
|
||||
|
||||
let embed = new EmbedBuilder()
|
||||
.setTitle('Crime Availability Check')
|
||||
await torn.api(`https://api.torn.com/v2/faction/crimes?cat=recruiting&offset=0&sort=DESC`).then(data => {
|
||||
await torn.faction.crimes({ category: 'recruiting', offset: 0, sort: 'DESC' }).then(crimeList => {
|
||||
const data = { crimes: crimeList };
|
||||
data.crimes.forEach(crime => {
|
||||
crimes.difficulty[crime.difficulty - 1].count++
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ module.exports = async (client, torn, config) => {
|
||||
const now = new Date();
|
||||
const state = require('../state.json');
|
||||
let embeds = [];
|
||||
const data = await torn.api(`https://api.torn.com/v2/faction/crimes?cat=successful&from=${now.getTime() / 1000 - 7 * 24 * 60 * 60}&sort=DESC`);
|
||||
const data = { crimes: await torn.faction.crimes({ category: 'successful', from: now.getTime() / 1000 - 7 * 24 * 60 * 60, sort: 'DESC' }) };
|
||||
for (const crime of data.crimes) {
|
||||
if (!crime.rewards.payout) {
|
||||
console.debug(`unpaidOC: Found unpaid crime: ${crime.name}:${crime.id}`);
|
||||
@@ -56,15 +56,15 @@ module.exports = async (client, torn, config) => {
|
||||
.setLabel('Click when sorted')
|
||||
.setStyle(ButtonStyle.Success),
|
||||
);
|
||||
channel.send({content: "# Unpaid Faction Crimes:", embeds: embeds, components: [row] });
|
||||
channel.send({ content: "# Unpaid Faction Crimes:", embeds: embeds, components: [row] });
|
||||
state.payoutAlertLast = now.toISOString();
|
||||
fs.writeFile('./state.json', JSON.stringify(state, null, 4), err => {if (err) {console.error(err)}});
|
||||
fs.writeFile('./state.json', JSON.stringify(state, null, 4), err => { if (err) { console.error(err) } });
|
||||
} else { console.debug(`unpaidOC: Would send alert, but one was sent recently`); }
|
||||
} else {
|
||||
console.debug(`unpaidOC: All crimes are paid, not sending alert`);
|
||||
const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
state.payoutAlertLast = twentyFourHoursAgo.toISOString();
|
||||
fs.writeFile('./state.json', JSON.stringify(state, null, 4), err => {if (err) {console.error(err)}});
|
||||
fs.writeFile('./state.json', JSON.stringify(state, null, 4), err => { if (err) { console.error(err) } });
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
395
torn.js
395
torn.js
@@ -1,119 +1,143 @@
|
||||
const fs = require('fs');
|
||||
let config;
|
||||
let cache;
|
||||
try {config = require('./config.json')} catch {return}
|
||||
try {cache = require('./cache.json')} catch {
|
||||
|
||||
// Load config and cache
|
||||
try {
|
||||
config = require('./config.json');
|
||||
} catch (e) {
|
||||
console.error("Failed to load config.json", e);
|
||||
}
|
||||
|
||||
try {
|
||||
cache = require('./cache.json');
|
||||
} catch (e) {
|
||||
cache = {
|
||||
users: {},
|
||||
factions: {},
|
||||
companies: {},
|
||||
items: {}
|
||||
};
|
||||
try {
|
||||
fs.writeFileSync('./cache.json', JSON.stringify(cache));
|
||||
return;
|
||||
} catch (writeErr) {
|
||||
console.error("Failed to write initial cache.json", writeErr);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = () => {};
|
||||
module.exports.readyCheck = async (key) => {
|
||||
const url = `https://api.torn.com/user/?selections=basic&key=${key}`
|
||||
// Constants
|
||||
const TIME_12H = 12 * 60 * 60 * 1000;
|
||||
const TIME_7D = 7 * 24 * 60 * 60 * 1000;
|
||||
const TIME_30D = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
// Helper to save cache
|
||||
function saveCache() {
|
||||
try {
|
||||
fs.writeFileSync('./cache.json', JSON.stringify(cache));
|
||||
} catch (e) {
|
||||
console.error("Failed to save cache:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Generic Caching Helper
|
||||
async function getCached(collectionName, id, fetchFn, ttl) {
|
||||
const now = new Date().getTime();
|
||||
const item = cache[collectionName][id];
|
||||
let lastUpdated = 0;
|
||||
|
||||
if (item && item.updated) {
|
||||
try {
|
||||
lastUpdated = new Date(item.updated).getTime();
|
||||
} catch (e) {
|
||||
lastUpdated = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (item && (now - lastUpdated < ttl)) {
|
||||
console.debug(`Cache: Hit for ${collectionName} ${item.name || id}`);
|
||||
return item;
|
||||
} else {
|
||||
console.debug(`Cache: Miss for ${collectionName} ${id || 'unknown'}`);
|
||||
try {
|
||||
// The fetchFn is expected to update the cache and return the data, or we can structure it differently.
|
||||
// Based on the refactor code below, the fetchFn calls saveCache() and returns the data.
|
||||
// But wait, the original logic for checking cache was inside the 'cache' object functions,
|
||||
// calling the specific fetcher which updated the cache.
|
||||
// In the refactored 'api.cache.user' below, I call 'api.user.basic(user)'.
|
||||
// 'api.user.basic' updates the cache and returns data.
|
||||
// So this helper just needs to return that result.
|
||||
// BUT, I need to make sure I return the logical object.
|
||||
|
||||
const result = await fetchFn();
|
||||
console.debug(`Cache: Resolved ${collectionName} ${id}`);
|
||||
|
||||
// If the fetchFn updated the cache, we can return the cached item to be consistent
|
||||
// or just the result. The original returned the cached item in the cache wrapper.
|
||||
// Let's return the result from fetchFn which is usually the data.
|
||||
// However, the original cache wrappers returned `cache.users[user]`.
|
||||
// Let's see if there is a difference.
|
||||
// `api.user.basic` returns `data`. `cache.users[user]` is a subset of `data`?
|
||||
// Original:
|
||||
// `cache.users[user] = { name, player_id, level, ... }`
|
||||
// `return(data)` (full api response)
|
||||
// But `module.exports.cache.user` returned `cache.users[user]`.
|
||||
// So the CACHE wrapper returned the CACHED OBJECT (subset), while the FETCH function returned the FULL API response.
|
||||
// This is a subtle difference.
|
||||
// If I want to maintain compatibility, `getCached` should return the cached item from `cache` after fetching.
|
||||
|
||||
return cache[collectionName][id];
|
||||
} catch (e) {
|
||||
console.error(`Error fetching for ${collectionName} ${id}:`, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper for generic API fetching
|
||||
async function fetchApi(path) {
|
||||
const glue = path.includes('?') ? '&' : '?';
|
||||
const response = await fetch(`${path}${glue}key=${config.torn}`);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
const api = {
|
||||
readyCheck: async (key) => {
|
||||
const url = `https://api.torn.com/user/?selections=basic&key=${key}`;
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
console.log(`Torn: Connected as ${data.name} [${data.player_id}]`);
|
||||
};
|
||||
module.exports.test = async () => {
|
||||
const url = `https://api.torn.com/user/?selections=basic&key=${config.torn}`
|
||||
},
|
||||
|
||||
test: async () => {
|
||||
const url = `https://api.torn.com/user/?selections=basic&key=${config.torn}`;
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
return(`Connected to Torn as ${data.name} [${data.player_id}]`);
|
||||
};
|
||||
module.exports.api = async (url) => {
|
||||
return `Connected to Torn as ${data.name} [${data.player_id}]`;
|
||||
},
|
||||
|
||||
api: async (url) => {
|
||||
const response = await fetch(`${url}&key=${config.torn}`);
|
||||
const data = await response.json();
|
||||
return(data);
|
||||
};
|
||||
module.exports.cache = {
|
||||
return response.json();
|
||||
},
|
||||
|
||||
cache: {
|
||||
async user(user) {
|
||||
const twelveHours = 12 * 60 * 60 * 1000;
|
||||
const now = new Date().getTime();
|
||||
let last
|
||||
try {
|
||||
last = new Date(cache.users[user].updated).getTime();
|
||||
} catch {
|
||||
last = new Date(now - twelveHours).getTime();
|
||||
}
|
||||
if (cache.users[user] && (now - last < twelveHours)) {
|
||||
console.debug(`Cache: Hit for user ${cache.users[user].name}`)
|
||||
return(cache.users[user]);
|
||||
} else {
|
||||
console.debug(`Cache: Miss for user ${user}`)
|
||||
await module.exports.user.basic(user);
|
||||
console.debug(`Cache: Resolved user ${cache.users[user].name}`)
|
||||
return(cache.users[user]);
|
||||
}
|
||||
return getCached('users', user, async () => await api.user.basic(user), TIME_12H);
|
||||
},
|
||||
async faction(faction) {
|
||||
const twelveHours = 12 * 60 * 60 * 1000;
|
||||
const now = new Date().getTime();
|
||||
let last
|
||||
try {
|
||||
last = new Date(cache.factions[faction].updated).getTime();
|
||||
} catch {
|
||||
last = new Date(now - twelveHours).getTime();
|
||||
}
|
||||
if (cache.factions[faction] && (now - last < twelveHours)) {
|
||||
console.debug(`Cache: Hit for faction ${cache.factions[faction].name}`)
|
||||
return(cache.factions[faction]);
|
||||
} else {
|
||||
console.debug(`Cache: Miss for faction ${faction}`)
|
||||
await module.exports.faction.basic(faction);
|
||||
console.debug(`Cache: Resolved faction ${cache.factions[faction].name}`)
|
||||
return(cache.factions[faction]);
|
||||
}
|
||||
return getCached('factions', faction, async () => await api.faction.basic(faction), TIME_12H);
|
||||
},
|
||||
async company(company) {
|
||||
const twelveHours = 12 * 60 * 60 * 1000;
|
||||
const now = new Date().getTime();
|
||||
let last
|
||||
try {
|
||||
last = new Date(cache.companies[company].updated).getTime();
|
||||
} catch {
|
||||
last = new Date(now - twelveHours).getTime();
|
||||
}
|
||||
if (cache.companies[company] && (now - last < twelveHours)) {
|
||||
console.debug(`Cache: Hit for company ${cache.companies[company].name}`)
|
||||
return(cache.companies[company]);
|
||||
} else {
|
||||
console.debug(`Cache: Miss for company ${company}`)
|
||||
await module.exports.company(company);
|
||||
console.debug(`Cache: Resolved company ${cache.companies[company].name}`)
|
||||
return(cache.companies[company]);
|
||||
}
|
||||
return getCached('companies', company, async () => await api.company(company), TIME_12H);
|
||||
},
|
||||
async item(item) {
|
||||
const sevenDays = 7 * 24 * 60 * 60 * 1000;
|
||||
const now = new Date().getTime();
|
||||
let last
|
||||
try {
|
||||
last = new Date(cache.items[item].updated).getTime();
|
||||
} catch {
|
||||
last = new Date(now - sevenDays).getTime();
|
||||
return getCached('items', item, async () => await api.item(item), TIME_7D);
|
||||
}
|
||||
if (cache.items[item] && (now - last < sevenDays)) {
|
||||
console.debug(`Cache: Hit for item ${cache.items[item].name}`)
|
||||
return(cache.items[item]);
|
||||
} else {
|
||||
console.debug(`Cache: Miss for item ${item}`)
|
||||
await module.exports.item(item);
|
||||
console.debug(`Cache: Resolved item ${cache.items[item].name}`)
|
||||
return(cache.items[item]);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
module.exports.user = {
|
||||
user: {
|
||||
async basic(user) {
|
||||
const response = await fetch(`https://api.torn.com/user/${user}?selections=basic&key=${config.torn}`);
|
||||
const data = await response.json();
|
||||
const data = await fetchApi(`https://api.torn.com/user/${user}?selections=basic`);
|
||||
const now = new Date();
|
||||
cache.users[user] = {
|
||||
name: data.name,
|
||||
@@ -122,12 +146,11 @@ module.exports.user = {
|
||||
gender: data.gender,
|
||||
updated: now.toISOString()
|
||||
};
|
||||
fs.writeFileSync('./cache.json', JSON.stringify(cache));
|
||||
return(data);
|
||||
saveCache();
|
||||
return data;
|
||||
},
|
||||
async profile(user) {
|
||||
const response = await fetch(`https://api.torn.com/user/${user}?selections=profile&key=${config.torn}`);
|
||||
const data = await response.json();
|
||||
const data = await fetchApi(`https://api.torn.com/user/${user}?selections=profile`);
|
||||
const now = new Date();
|
||||
cache.users[user] = {
|
||||
name: data.name,
|
||||
@@ -136,30 +159,28 @@ module.exports.user = {
|
||||
gender: data.gender,
|
||||
updated: now.toISOString()
|
||||
};
|
||||
fs.writeFileSync('./cache.json', JSON.stringify(cache));
|
||||
return(data);
|
||||
saveCache();
|
||||
return data;
|
||||
},
|
||||
async stats(user, category, statName) {
|
||||
let url = `https://api.torn.com/v2/user`;
|
||||
if (user) { url += `/${user}/personalstats` };
|
||||
if (category) { url += `?cat=${category}` } else { url += `?cat=all` };
|
||||
if (statName) { url += `&stat=${statName}` };
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
return(data);
|
||||
}
|
||||
};
|
||||
if (user) { url += `/${user}/personalstats`; }
|
||||
if (category) { url += `?cat=${category}`; } else { url += `?cat=all`; }
|
||||
if (statName) { url += `&stat=${statName}`; }
|
||||
return fetchApi(url);
|
||||
},
|
||||
// Added lookup to maintain feature parity if it was ever needed, though not in original user object
|
||||
},
|
||||
|
||||
module.exports.faction = {
|
||||
faction: {
|
||||
async basic(faction) {
|
||||
let response
|
||||
if (faction) {
|
||||
response = await fetch(`https://api.torn.com/v2/faction/${faction}/basic?key=${config.torn}`);
|
||||
} else {
|
||||
response = await fetch(`https://api.torn.com/v2/faction/basic?key=${config.torn}`);
|
||||
}
|
||||
const data = (await response.json()).basic;
|
||||
const endpoint = faction ? `https://api.torn.com/v2/faction/${faction}/basic` : `https://api.torn.com/v2/faction/basic`;
|
||||
const response = await fetchApi(endpoint);
|
||||
// v2 return structure: { basic: { ... } }
|
||||
const data = response.basic;
|
||||
|
||||
const now = new Date();
|
||||
// Store by ID. If faction is null (own faction), we rely on data.id
|
||||
cache.factions[data.id] = {
|
||||
name: data.name,
|
||||
leader_id: data.leader_id,
|
||||
@@ -168,50 +189,70 @@ module.exports.faction = {
|
||||
best_chain: data.best_chain,
|
||||
updated: now.toISOString()
|
||||
};
|
||||
fs.writeFileSync('./cache.json', JSON.stringify(cache));
|
||||
return(data);
|
||||
saveCache();
|
||||
return data;
|
||||
},
|
||||
async members(faction) {
|
||||
let response
|
||||
if (faction) {
|
||||
response = await fetch(`https://api.torn.com/v2/faction/${faction}/members?striptags=true&key=${config.torn}`);
|
||||
} else {
|
||||
response = await fetch(`https://api.torn.com/v2/faction/members?striptags=true&key=${config.torn}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
return(data.members);
|
||||
const endpoint = faction ? `https://api.torn.com/v2/faction/${faction}/members?striptags=true` : `https://api.torn.com/v2/faction/members?striptags=true`;
|
||||
const data = await fetchApi(endpoint);
|
||||
return data.members;
|
||||
},
|
||||
async crimes(category) {
|
||||
let response
|
||||
if (category) {
|
||||
response = await fetch(`https://api.torn.com/v2/faction/crimes/${category}?key=${config.torn}`);
|
||||
async crimes(options = {}) {
|
||||
let params = new URLSearchParams();
|
||||
let category = '';
|
||||
|
||||
if (typeof options === 'string') {
|
||||
category = options;
|
||||
} else {
|
||||
response = await fetch(`https://api.torn.com/v2/faction/crimes?key=${config.torn}`);
|
||||
if (options.category) category = options.category;
|
||||
if (options.from) params.append('from', options.from);
|
||||
if (options.to) params.append('to', options.to);
|
||||
if (options.limit) params.append('limit', options.limit);
|
||||
if (options.sort) params.append('sort', options.sort);
|
||||
if (options.offset !== undefined) params.append('offset', options.offset);
|
||||
if (options.initiator) params.append('initiator', options.initiator);
|
||||
}
|
||||
const data = await response.json();
|
||||
return(data.crimes);
|
||||
|
||||
const endpoint = category ? `https://api.torn.com/v2/faction/crimes/${category}` : `https://api.torn.com/v2/faction/crimes`;
|
||||
const queryString = params.toString() ? `?${params.toString()}` : '';
|
||||
|
||||
const data = await fetchApi(`${endpoint}${queryString}`);
|
||||
return data.crimes;
|
||||
},
|
||||
async upgrades() {
|
||||
const response = await fetch(`https://api.torn.com/v2/faction/upgrades?key=${config.torn}`);
|
||||
const data = await response.json();
|
||||
return(data);
|
||||
const data = await fetchApi(`https://api.torn.com/v2/faction/upgrades`);
|
||||
return data;
|
||||
},
|
||||
async news(category, from) {
|
||||
const response = await fetch(`https://api.torn.com/v2/faction/news?striptags=false&limit=100&sort=DESC&from=${from}&cat=${category}&key=${config.torn}`)
|
||||
const data = await response.json();
|
||||
return(data.news);
|
||||
}
|
||||
}
|
||||
const data = await fetchApi(`https://api.torn.com/v2/faction/news?striptags=false&limit=100&sort=DESC&from=${from}&cat=${category}`);
|
||||
return data.news;
|
||||
},
|
||||
async rankedWars(options = {}) {
|
||||
let params = new URLSearchParams();
|
||||
if (options.limit) params.append('limit', options.limit);
|
||||
if (options.offset !== undefined) params.append('offset', options.offset);
|
||||
if (options.sort) params.append('sort', options.sort);
|
||||
if (options.to) params.append('to', options.to);
|
||||
if (options.from) params.append('from', options.from);
|
||||
|
||||
module.exports.company = async (company) => {
|
||||
let response
|
||||
if (company) {
|
||||
response = await fetch(`https://api.torn.com/company/${company}?selections=profile&key=${config.torn}`);
|
||||
} else {
|
||||
response = await fetch(`https://api.torn.com/company/?selections=profile&key=${config.torn}`);
|
||||
const queryString = params.toString() ? `?${params.toString()}` : '';
|
||||
const data = await fetchApi(`https://api.torn.com/v2/faction/rankedwars${queryString}`);
|
||||
return data.rankedwars;
|
||||
},
|
||||
async rankedWarReport(id) {
|
||||
const data = await fetchApi(`https://api.torn.com/v2/faction/${id}/rankedwarreport`);
|
||||
return data.rankedwarreport;
|
||||
}
|
||||
const data = await response.json();
|
||||
},
|
||||
|
||||
// company was a top-level function in export, but also used as property
|
||||
// Original: module.exports.company = async ...
|
||||
// So api.company should be a function
|
||||
company: async (company) => {
|
||||
const endpoint = company ? `https://api.torn.com/company/${company}?selections=profile` : `https://api.torn.com/company/?selections=profile`;
|
||||
const data = await fetchApi(endpoint);
|
||||
const now = new Date();
|
||||
// company ID is data.company.ID
|
||||
cache.companies[data.company.ID] = {
|
||||
name: data.company.name,
|
||||
id: data.company.ID,
|
||||
@@ -220,28 +261,34 @@ module.exports.company = async (company) => {
|
||||
rating: data.company.rating,
|
||||
updated: now.toISOString()
|
||||
};
|
||||
fs.writeFileSync('./cache.json', JSON.stringify(cache));
|
||||
return(data.company);
|
||||
}
|
||||
saveCache();
|
||||
return data.company;
|
||||
},
|
||||
|
||||
module.exports.item = async (item) => {
|
||||
const response = await fetch(`https://api.torn.com/v2/torn/${item}/items?sort=ASC&key=${config.torn}`);
|
||||
const data = await response.json();
|
||||
// item was a function with a .lookup property
|
||||
item: Object.assign(
|
||||
async (item) => {
|
||||
const data = await fetchApi(`https://api.torn.com/v2/torn/${item}/items?sort=ASC`);
|
||||
const now = new Date();
|
||||
cache.items[item] = data.items[0];
|
||||
cache.items[item] = data.items[0]; // Assuming item is ID
|
||||
if (cache.items[item]) {
|
||||
cache.items[item].updated = now.toISOString();
|
||||
fs.writeFileSync('./cache.json', JSON.stringify(cache));
|
||||
return(data.items[0]);
|
||||
}
|
||||
module.exports.item.lookup = async (itemName) => {
|
||||
console.debug(`Torn: Looking up item ${itemName}`)
|
||||
const thirtyDays = 30 * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
saveCache();
|
||||
return data.items[0];
|
||||
},
|
||||
{
|
||||
lookup: async (itemName) => {
|
||||
console.debug(`Torn: Looking up item ${itemName}`);
|
||||
const now = new Date().getTime();
|
||||
|
||||
// Check cache first
|
||||
for (const itemId in cache.items) {
|
||||
if (cache.items[itemId].name === itemName) {
|
||||
let last = new Date(cache.items[itemId].updated).getTime();
|
||||
if (now - last < thirtyDays) {
|
||||
let last = 0;
|
||||
try { last = new Date(cache.items[itemId].updated).getTime(); } catch (e) { }
|
||||
|
||||
if (now - last < TIME_30D) {
|
||||
console.debug(`Cache: Hit for item ${cache.items[itemId].name}`);
|
||||
return cache.items[itemId];
|
||||
}
|
||||
@@ -249,33 +296,41 @@ module.exports.item.lookup = async (itemName) => {
|
||||
}
|
||||
|
||||
console.debug(`Cache: Miss for item ${itemName}`);
|
||||
const response = await fetch(`https://api.torn.com/v2/torn/items?cat=All&sort=ASC&key=${config.torn}`);
|
||||
const data = await response.json();
|
||||
const data = await fetchApi(`https://api.torn.com/v2/torn/items?cat=All&sort=ASC`);
|
||||
let target;
|
||||
if (data.items) {
|
||||
data.items.forEach(item => {
|
||||
if (item.name === itemName) {
|
||||
console.debug(`Torn: Found item ${item.name} as ${item.id}`)
|
||||
console.debug(`Torn: Found item ${item.name} as ${item.id}`);
|
||||
target = item;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (target) {
|
||||
cache.items[target.id] = target;
|
||||
cache.items[target.id].updated = new Date().toISOString();
|
||||
fs.writeFileSync('./cache.json', JSON.stringify(cache));
|
||||
saveCache();
|
||||
}
|
||||
return(target);
|
||||
};
|
||||
return target;
|
||||
}
|
||||
}
|
||||
),
|
||||
|
||||
|
||||
module.exports.self = {
|
||||
self: {
|
||||
async id() {
|
||||
if (!config.tornid) {
|
||||
const url = `https://api.torn.com/user/?selections=basic&key=${config.torn}`
|
||||
const url = `https://api.torn.com/user/?selections=basic&key=${config.torn}`;
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
config.tornid = data.player_id;
|
||||
console.log(`Torn: Retrieved default ID as "${data.player_id}"`)
|
||||
return(data.player_id);
|
||||
} else return config.tornid;
|
||||
console.log(`Torn: Retrieved default ID as "${data.player_id}"`);
|
||||
return data.player_id;
|
||||
} else {
|
||||
return config.tornid;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
Reference in New Issue
Block a user