aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authormat <27899617+mat-1@users.noreply.github.com>2021-03-02 18:54:57 -0600
committermat <27899617+mat-1@users.noreply.github.com>2021-03-02 18:54:57 -0600
commitd1758e3f0e8e9334bbfc160dbe2245d15a6cd859 (patch)
treeb56885ad260fc2b9967bd4bf6373ca8c8b824948 /src
parent67da5a4e42c94f3a6baddc3f15a8d18a407ca9ad (diff)
downloadskyblock-api-d1758e3f0e8e9334bbfc160dbe2245d15a6cd859.tar.gz
skyblock-api-d1758e3f0e8e9334bbfc160dbe2245d15a6cd859.tar.bz2
skyblock-api-d1758e3f0e8e9334bbfc160dbe2245d15a6cd859.zip
add some more typings
Diffstat (limited to 'src')
-rw-r--r--src/constants.ts15
-rw-r--r--src/database.ts29
-rw-r--r--src/hypixel.ts4
-rw-r--r--src/hypixelCached.ts9
-rw-r--r--src/util.ts29
5 files changed, 50 insertions, 36 deletions
diff --git a/src/constants.ts b/src/constants.ts
index 1c27e14..760dcb1 100644
--- a/src/constants.ts
+++ b/src/constants.ts
@@ -3,6 +3,7 @@
*/
import fetch from 'node-fetch'
+import * as nodeFetch from 'node-fetch'
import { Agent } from 'https'
import NodeCache from 'node-cache'
import Queue from 'queue-promise'
@@ -28,7 +29,7 @@ const queue = new Queue({
* @param headers The extra headers
* @param json The JSON body, only applicable for some types of methods
*/
-async function fetchGithubApi(method: string, route: string, headers?: any, json?: any) {
+async function fetchGithubApi(method: string, route: string, headers?: any, json?: any): Promise<nodeFetch.Response> {
return await fetch(
githubApiBase + route,
{
@@ -87,7 +88,7 @@ async function fetchFile(path: string): Promise<GithubFile> {
* @param message The commit message
* @param newContent The new content in the file
*/
-async function editFile(file: GithubFile, message: string, newContent: string) {
+async function editFile(file: GithubFile, message: string, newContent: string): Promise<void> {
const r = await fetchGithubApi(
'PUT',
`/repos/${owner}/${repo}/contents/${file.path}`,
@@ -118,7 +119,7 @@ async function fetchJSONConstant(filename: string): Promise<string[]> {
}
/** Add stats to skyblock-constants. This has caching so it's fine to call many times */
-export async function addJSONConstants(filename: string, addingValues: string[], units: string='stats') {
+export async function addJSONConstants(filename: string, addingValues: string[], units: string='stats'): Promise<void> {
if (addingValues.length === 0) return // no stats provided, just return
queue.enqueue(async() => {
@@ -154,7 +155,7 @@ export async function fetchStats(): Promise<string[]> {
}
/** Add stats to skyblock-constants. This has caching so it's fine to call many times */
-export async function addStats(addingStats: string[]) {
+export async function addStats(addingStats: string[]): Promise<void> {
await addJSONConstants('stats.json', addingStats, 'stats')
}
@@ -164,7 +165,7 @@ export async function fetchCollections(): Promise<string[]> {
}
/** Add collections to skyblock-constants. This has caching so it's fine to call many times */
-export async function addCollections(addingCollections: string[]) {
+export async function addCollections(addingCollections: string[]): Promise<void> {
await addJSONConstants('collections.json', addingCollections, 'collections')
}
@@ -174,7 +175,7 @@ export async function fetchSkills(): Promise<string[]> {
}
/** Add skills to skyblock-constants. This has caching so it's fine to call many times */
-export async function addSkills(addingSkills: string[]) {
+export async function addSkills(addingSkills: string[]): Promise<void> {
await addJSONConstants('skills.json', addingSkills, 'skills')
}
@@ -184,6 +185,6 @@ export async function fetchZones(): Promise<string[]> {
}
/** Add skills to skyblock-constants. This has caching so it's fine to call many times */
-export async function addZones(addingZones: string[]) {
+export async function addZones(addingZones: string[]): Promise<void> {
await addJSONConstants('zones.json', addingZones, 'zones')
}
diff --git a/src/database.ts b/src/database.ts
index 5d97e88..37605a6 100644
--- a/src/database.ts
+++ b/src/database.ts
@@ -49,7 +49,7 @@ let client: MongoClient
let database: Db
let memberLeaderboardsCollection: Collection<any>
-async function connect() {
+async function connect(): Promise<void> {
if (!process.env.db_uri)
return console.warn('Warning: db_uri was not found in .env. Features that utilize the database such as leaderboards won\'t work.')
if (!process.env.db_name)
@@ -59,8 +59,11 @@ async function connect() {
memberLeaderboardsCollection = database.collection('member-leaderboards')
}
+interface StringNumber {
+ [ name: string]: number
+}
-function getMemberCollectionAttributes(member: CleanMember) {
+function getMemberCollectionAttributes(member: CleanMember): StringNumber {
const collectionAttributes = {}
for (const collection of member.collections) {
const collectionLeaderboardName = `collection_${collection.name}`
@@ -69,7 +72,7 @@ function getMemberCollectionAttributes(member: CleanMember) {
return collectionAttributes
}
-function getMemberSkillAttributes(member: CleanMember) {
+function getMemberSkillAttributes(member: CleanMember): StringNumber {
const skillAttributes = {}
for (const collection of member.skills) {
const skillLeaderboardName = `skill_${collection.name}`
@@ -78,7 +81,7 @@ function getMemberSkillAttributes(member: CleanMember) {
return skillAttributes
}
-function getMemberLeaderboardAttributes(member: CleanMember) {
+function getMemberLeaderboardAttributes(member: CleanMember): StringNumber {
// if you want to add a new leaderboard for member attributes, add it here (and getAllLeaderboardAttributes)
return {
// we use the raw stat names rather than the clean stats in case hypixel adds a new stat and it takes a while for us to clean it
@@ -180,7 +183,13 @@ async function fetchMemberLeaderboardRaw(name: string): Promise<DatabaseLeaderbo
return leaderboardRaw
}
-export async function fetchMemberLeaderboard(name: string) {
+interface Leaderboard {
+ name: string
+ unit?: string
+ list: LeaderboardItem[]
+}
+
+export async function fetchMemberLeaderboard(name: string): Promise<Leaderboard> {
const leaderboardRaw = await fetchMemberLeaderboardRaw(name)
const fetchLeaderboardPlayer = async(item: DatabaseLeaderboardItem): Promise<LeaderboardItem> => {
return {
@@ -210,7 +219,7 @@ async function getMemberLeaderboardRequirement(name: string): Promise<number> {
}
/** Get the attributes for the member, but only ones that would put them on the top 100 for leaderboards */
-async function getApplicableAttributes(member): Promise<{ [key: string]: number }> {
+async function getApplicableAttributes(member): Promise<StringNumber> {
const leaderboardAttributes = getMemberLeaderboardAttributes(member)
const applicableAttributes = {}
for (const [ leaderboard, attributeValue ] of Object.entries(leaderboardAttributes)) {
@@ -223,7 +232,7 @@ async function getApplicableAttributes(member): Promise<{ [key: string]: number
}
/** Update the member's leaderboard data on the server if applicable */
-export async function updateDatabaseMember(member: CleanMember, profile: CleanFullProfile) {
+export async function updateDatabaseMember(member: CleanMember, profile: CleanFullProfile): Promise<void> {
if (!client) return // the db client hasn't been initialized
// the member's been updated too recently, just return
if (recentlyUpdated.get(profile.uuid + member.uuid))
@@ -279,7 +288,7 @@ const queue = new Queue({
})
/** Queue an update for the member's leaderboard data on the server if applicable */
-export async function queueUpdateDatabaseMember(member: CleanMember, profile: CleanFullProfile) {
+export async function queueUpdateDatabaseMember(member: CleanMember, profile: CleanFullProfile): Promise<void> {
queue.enqueue(async() => await updateDatabaseMember(member, profile))
}
@@ -287,7 +296,7 @@ export async function queueUpdateDatabaseMember(member: CleanMember, profile: Cl
/**
* Remove leaderboard attributes for members that wouldn't actually be on the leaderboard. This saves a lot of storage space
*/
-async function removeBadMemberLeaderboardAttributes() {
+async function removeBadMemberLeaderboardAttributes(): Promise<void> {
const leaderboards = await fetchAllMemberLeaderboardAttributes()
// shuffle so if the application is restarting many times itll still be useful
for (const leaderboard of shuffle(leaderboards)) {
@@ -313,7 +322,7 @@ async function removeBadMemberLeaderboardAttributes() {
}
/** Fetch all the leaderboards, used for caching. Don't call this often! */
-async function fetchAllLeaderboards() {
+async function fetchAllLeaderboards(): Promise<void> {
const leaderboards = await fetchAllMemberLeaderboardAttributes()
// shuffle so if the application is restarting many times itll still be useful
if (debug) console.log('Caching leaderboards!')
diff --git a/src/hypixel.ts b/src/hypixel.ts
index b0bcf03..979b57f 100644
--- a/src/hypixel.ts
+++ b/src/hypixel.ts
@@ -28,7 +28,7 @@ export interface ApiOptions {
}
/** Sends an API request to Hypixel and cleans it up. */
-export async function sendCleanApiRequest({ path, args }, included?: Included[], options?: ApiOptions) {
+export async function sendCleanApiRequest({ path, args }, included?: Included[], options?: ApiOptions): Promise<any> {
const key = await chooseApiKey()
const rawResponse = await sendApiRequest({ path, key, args })
if (rawResponse.throttled) {
@@ -43,7 +43,7 @@ export async function sendCleanApiRequest({ path, args }, included?: Included[],
-async function cleanResponse({ path, data }: { path: string, data: HypixelResponse }, options: ApiOptions) {
+async function cleanResponse({ path, data }: { path: string, data: HypixelResponse }, options: ApiOptions): Promise<any> {
// Cleans up an api response
switch (path) {
case 'player': return await cleanPlayerResponse(data.player)
diff --git a/src/hypixelCached.ts b/src/hypixelCached.ts
index 0d5e0e3..4e3316e 100644
--- a/src/hypixelCached.ts
+++ b/src/hypixelCached.ts
@@ -54,7 +54,12 @@ const profileNameCache = new NodeCache({
useClones: false,
})
-function waitForCacheSet(cache: NodeCache, key?: string, value?: string): Promise<any> {
+interface KeyValue {
+ key: any
+ value: any
+}
+
+function waitForCacheSet(cache: NodeCache, key?: string, value?: string): Promise<KeyValue> {
return new Promise((resolve, reject) => {
const listener = (setKey, setValue) => {
if (setKey === key || (value && setValue === value)) {
@@ -239,7 +244,7 @@ async function fetchBasicProfiles(user: string): Promise<CleanBasicProfile[]> {
* @param user A username or uuid
* @param profile A profile name or profile uuid
*/
-export async function fetchProfileUuid(user: string, profile: string) {
+export async function fetchProfileUuid(user: string, profile: string): Promise<string> {
// if a profile wasn't provided, return
if (!profile) {
if (debug) console.log('no profile provided?', user, profile)
diff --git a/src/util.ts b/src/util.ts
index e0c7699..cc9cffb 100644
--- a/src/util.ts
+++ b/src/util.ts
@@ -6,28 +6,27 @@ export function undashUuid(uuid: string): string {
return uuid.replace(/-/g, '').toLowerCase()
}
-
-
-export function queryToJson(queryString) {
- var query = {};
- var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
- for (var i = 0; i < pairs.length; i++) {
- var pair = pairs[i].split('=');
- query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
+export function queryToJson(queryString): { [ key: string ]: string } {
+ const query = {}
+ const pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&')
+ for (let i = 0; i < pairs.length; i++) {
+ const pair = pairs[i].split('=')
+ query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')
}
- return query;
+ return query
}
-export function jsonToQuery(data) {
+
+export function jsonToQuery(data): string {
return Object.entries(data || {}).map(e => e.join('=')).join('&')
}
-export function shuffle(a) {
+export function shuffle(a): string {
for (let i = a.length - 1; i > 0; i--) {
- const j = Math.floor(Math.random() * (i + 1));
- [a[i], a[j]] = [a[j], a[i]];
+ const j = Math.floor(Math.random() * (i + 1))
+ ;[a[i], a[j]] = [a[j], a[i]]
}
- return a;
+ return a
}
@@ -81,6 +80,6 @@ export function colorCodeFromName(colorName: string): string {
}
}
-export async function sleep(ms: number) {
+export async function sleep(ms: number): Promise<void> {
await new Promise(resolve => setTimeout(resolve, ms))
} \ No newline at end of file