Skip to content

Commit

Permalink
use async and type inference properly
Browse files Browse the repository at this point in the history
  • Loading branch information
3vorp committed Feb 20, 2024
1 parent a7f6c16 commit da65e0a
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 101 deletions.
9 changes: 4 additions & 5 deletions src/v2/controller/addon.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
Addon,
Addons,
Files,
AddonAll,
AddonProperty,
AddonDownload,
AddonStatus,
Expand Down Expand Up @@ -53,7 +52,7 @@ export class AddonController extends Controller {

case "all":
default:
return this.service.getAll(id).then((addon: AddonAll) => {
return this.service.getAll(id).then((addon) => {
addon.files = addon.files.map((f) => {
if ((f.use === "header" || f.use === "screenshot") && f.source.startsWith("/"))
f.source = process.env.DB_IMAGE_ROOT + f.source;
Expand Down Expand Up @@ -179,7 +178,7 @@ export class AddonController extends Controller {
): Promise<Addon | Files> {
return this.service
.getAddonFromSlugOrId(id_or_slug)
.then((value: [number, Addon]) => this.getAddonProperty(value[0], property));
.then((value) => this.getAddonProperty(value[0], property));
}

/**
Expand All @@ -193,7 +192,7 @@ export class AddonController extends Controller {
public async getScreenshots(@Path() id_or_slug: string): Promise<Array<string>> {
return this.service
.getAddonFromSlugOrId(id_or_slug)
.then((value: [number, Addon]) => this.service.getScreenshots(value[0]))
.then((value) => this.service.getScreenshots(value[0]))
.then((screens) =>
screens.map((s) => (s.startsWith("/") ? process.env.DB_IMAGE_ROOT + s : s)),
);
Expand All @@ -210,7 +209,7 @@ export class AddonController extends Controller {
public async getScreenshotsIds(@Path() id_or_slug: string): Promise<Array<string>> {
return this.service
.getAddonFromSlugOrId(id_or_slug)
.then((value: [number, Addon]) => this.service.getScreenshotsIds(value[0]));
.then((value) => this.service.getScreenshotsIds(value[0]));
}

/**
Expand Down
54 changes: 21 additions & 33 deletions src/v2/firestorm/textures/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { MinecraftSorter } from "../../tools/sorter";
import { NotFoundError } from "../../tools/ApiError";

export const textures = firestorm.collection<FirestormTexture>("textures", (el) => {
el.uses = async (): Promise<Uses> =>
el.uses = (): Promise<Uses> =>
uses.search([
{
field: "texture",
Expand All @@ -30,27 +30,27 @@ export const textures = firestorm.collection<FirestormTexture>("textures", (el)
},
]);

el.paths = async (): Promise<Paths> =>
el.paths = (): Promise<Paths> =>
el
.uses()
.then((_uses) =>
Promise.all(_uses.map((_use) => uses.get(_use.id).then((u) => u.getPaths()))),
)
.then((arr) => arr.flat());

el.url = async (pack: PackID, version: string): Promise<string> => {
el.url = (pack: PackID, version: string): Promise<string> => {
const baseURL = "https://raw.githubusercontent.com";

let urls: Partial<Record<Edition, PackGitHub>>;
let path: Path;

return packs
.readRaw()
.get(pack)
.then((p) => {
urls = p[pack].github;
urls = p.github;
return el.paths();
})
.then((texturePaths: Paths) => {
.then((texturePaths) => {
// eq to [0]
if (version === "latest") {
[path] = texturePaths;
Expand All @@ -67,7 +67,7 @@ export const textures = firestorm.collection<FirestormTexture>("textures", (el)
});
};

el.contributions = async (): Promise<Contributions> =>
el.contributions = (): Promise<Contributions> =>
contributions.search([
{
field: "texture",
Expand All @@ -76,12 +76,12 @@ export const textures = firestorm.collection<FirestormTexture>("textures", (el)
},
]);

el.mcmeta = async (): Promise<MCMETA> =>
el.mcmeta = (): Promise<MCMETA> =>
el
.paths()
.then((ps: Paths) => ps.find((path: Path) => path.mcmeta) || null)
.then((p: Path | null) => Promise.all([el.uses(), p]))
.then(([us, p]: [Uses, Path | null]) => {
.then((ps) => ps.find((path: Path) => path.mcmeta) || null)
.then((p) => Promise.all([el.uses(), p]))
.then(([us, p]) => {
if (p === null) return [null, null];
return [us.find((use: Use) => use.id === p.use), p];
})
Expand All @@ -95,30 +95,18 @@ export const textures = firestorm.collection<FirestormTexture>("textures", (el)
)
.catch(() => null); // avoid crash if mcmeta file cannot be found
})
.then((res: any | null) => (res ? res.data : {}))
.then((res) => (res ? res.data : {}))
.catch(() => {});

el.all = async (): Promise<TextureAll> => {
const output = { id: el.id, name: el.name, tags: el.tags } as TextureAll;
return el
.uses()
.then((tUses: Uses) => {
output.uses = tUses;
return el.paths();
})
.then((tPaths: Paths) => {
output.paths = tPaths;
return el.mcmeta();
})
.then((mcmeta: MCMETA) => {
output.mcmeta = mcmeta;
return el.contributions();
})
.then((tContribs: Contributions) => {
output.contributions = tContribs;
return output;
});
};
el.all = async (): Promise<TextureAll> => ({
id: el.id,
name: el.name,
tags: el.tags,
uses: await el.uses(),
paths: await el.paths(),
mcmeta: await el.mcmeta(),
contributions: await el.contributions(),
});

return el;
});
4 changes: 2 additions & 2 deletions src/v2/firestorm/users/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { addons } from "../addons";
import "../config";

export const users = firestorm.collection<FirestormUser>("users", (el) => {
el.contributions = async (): Promise<Contributions> =>
el.contributions = (): Promise<Contributions> =>
contributions.search([
{
field: "authors",
Expand All @@ -14,7 +14,7 @@ export const users = firestorm.collection<FirestormUser>("users", (el) => {
},
]);

el.addons = async (): Promise<Addons> =>
el.addons = (): Promise<Addons> =>
addons.search([
{
field: "authors",
Expand Down
1 change: 1 addition & 0 deletions src/v2/interfaces/textures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface TextureAll extends Texture {
mcmeta: MCMETA;
contributions: Contributions;
}

export interface TexturesAll extends Array<TextureAll> {}

export interface EntireTextureToCreate extends TextureCreationParam {
Expand Down
7 changes: 4 additions & 3 deletions src/v2/repository/packs.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
PackID,
CreationPackAll,
PackSearch,
FirestormPack,
} from "~/v2/interfaces";
import { contributions, packs } from "../firestorm";
import SubmissionFirestormRepository from "./submissions.repository";
Expand Down Expand Up @@ -61,9 +60,11 @@ export default class PackFirestormRepository implements PackRepository {
criteria: "==",
value: resolution,
});
const searchPromise: Promise<FirestormPack[]> = options.length

// calling Object.values as a callback gets rid of type inference
const searchPromise = options.length
? packs.search(options)
: packs.readRaw().then(Object.values);
: packs.readRaw().then((res) => Object.values(res));

return searchPromise.then(async (searched) => {
if (!type || type === "all") return searched;
Expand Down
4 changes: 2 additions & 2 deletions src/v2/repository/path.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export default class PathFirestormRepository implements PathRepository {
modifyVersion(oldVersion: string, newVersion: string): Promise<void> {
return this.getRaw()
.then((r) => {
const old: Paths = Object.values(r);
const old = Object.values(r);
const filtered = old.filter((p) => p.versions.includes(oldVersion));
const edits: EditField<Path>[] = filtered.map((p) => ({
id: p.id,
Expand All @@ -79,7 +79,7 @@ export default class PathFirestormRepository implements PathRepository {
addNewVersionToVersion(version: string, newVersion: string): Promise<void> {
return this.getRaw()
.then((r) => {
const old: Paths = Object.values(r);
const old = Object.values(r);
const filtered = old.filter((p) => p.versions.includes(version));
const edits: EditField<Path>[] = filtered.map((p) => ({
id: p[ID_FIELD],
Expand Down
29 changes: 10 additions & 19 deletions src/v2/repository/user.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,7 @@ export default class UserFirestormRepository implements UserRepository {
}

getRaw(): Promise<Record<string, User>> {
return (
users
.readRaw()
.then(Object.entries)
// convert to entries to map, convert back to object after mapping done
.then((arr: [string, User][]) => arr.map(([key, el]) => [key, __transformUser(el)]))
.then(Object.fromEntries)
);
return users.readRaw();
}

getNames(): Promise<Usernames> {
Expand Down Expand Up @@ -79,15 +72,15 @@ export default class UserFirestormRepository implements UserRepository {
getProfileOrCreate(id: string): Promise<User> {
return users
.get(id)
.then((u) => __transformUser(u))
.then(__transformUser)
.catch((err) => {
if (err.isAxiosError && err.response && err.response.statusCode === 404) {
const empty: User = {
id,
anonymous: false,
roles: [],
username: "",
uuid: "",
id,
media: [],
};
return users.set(id, empty).then(() => this.getUserById(id));
Expand All @@ -98,19 +91,18 @@ export default class UserFirestormRepository implements UserRepository {
}

getUsersByName(name: string): Promise<Users> {
if (!name || name.length < 3)
return Promise.reject(new Error("User search requires at least 3 letters"));
if (!name) return Promise.reject(new Error("A name must be provided"));

return users
.search([
{
field: "username",
criteria: "includes",
criteria: name.length < 3 ? "==" : "includes",
value: name,
ignoreCase: true,
},
])
.then((arr: Users) => arr.map(__transformUser));
.then((arr) => arr.map(__transformUser));
}

getUsersFromRole(role: string, username?: string): Promise<Users> {
Expand All @@ -133,7 +125,7 @@ export default class UserFirestormRepository implements UserRepository {
ignoreCase: true,
});

return users.search(options).then((arr: Users) => arr.map((el) => __transformUser(el)));
return users.search(options).then((arr) => arr.map(__transformUser));
}

getRoles(): Promise<Array<string>> {
Expand All @@ -149,10 +141,9 @@ export default class UserFirestormRepository implements UserRepository {
}

getAddonsApprovedById(id: string): Promise<Addons> {
return users
.get(id)
.then((u) => u.addons())
.then((arr) => arr.filter((el) => el.approval.status === "approved"));
return this.getAddonsById(id).then((arr) =>
arr.filter((el) => el.approval.status === "approved"),
);
}

update(id: string, user: UserCreationParams): Promise<User> {
Expand Down
56 changes: 26 additions & 30 deletions src/v2/service/addon.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,46 +103,42 @@ export default class AddonService {
}

getStats(asAdmin: boolean): Promise<AddonStatsAdmin> {
return this.getRaw().then((entries) => {
let values = Object.values(entries);

if (!asAdmin) values = values.filter((a) => a.approval.status === AddonStatusApproved);

return values.reduce(
(acc, val) => {
acc[val.approval.status]++;
val.options.tags.forEach((t) => {
acc.numbers[t] = (acc.numbers[t] || 0) + 1;
});
return acc;
},
{
approved: 0,
pending: 0,
denied: 0,
archived: 0,
numbers: {},
} as AddonStatsAdmin,
return this.getRaw()
.then((entries) =>
Object.values(entries).filter((a) => asAdmin || a.approval.status === AddonStatusApproved),
)
.then((values) =>
values.reduce(
(acc, val) => {
acc[val.approval.status]++;
val.options.tags.forEach((t) => {
acc.numbers[t] = (acc.numbers[t] || 0) + 1;
});
return acc;
},
{
approved: 0,
pending: 0,
denied: 0,
archived: 0,
numbers: {},
} as AddonStatsAdmin,
),
);
});
}

getScreenshotsFiles(id): Promise<Files> {
getScreenshotsFiles(id: number): Promise<Files> {
return this.getFiles(id).then(
(files: Files) => files.filter((f: File) => f.use === "screenshot" || f.use === "carousel"), // TODO: only keep screenshots
);
}

getScreenshotsIds(id): Promise<Array<string>> {
return this.getScreenshotsFiles(id).then((files: Files) =>
Object.values(files).map((f: File) => f.id),
);
getScreenshotsIds(id: number): Promise<Array<string>> {
return this.getScreenshotsFiles(id).then((files) => Object.values(files).map((f) => f.id));
}

getScreenshots(id): Promise<Array<string>> {
return this.getScreenshotsFiles(id).then((files: Files) =>
Object.values(files).map((f: File) => f.source),
);
getScreenshots(id: number): Promise<Array<string>> {
return this.getScreenshotsFiles(id).then((files) => Object.values(files).map((f) => f.source));
}

async getScreenshotURL(id: number, index: number): Promise<string> {
Expand Down
3 changes: 1 addition & 2 deletions src/v2/service/pack.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
PackID,
PackSearch,
CreationPackAll,
Contributions,
PackAll,
Contribution,
} from "../interfaces";
Expand Down Expand Up @@ -41,7 +40,7 @@ export class PackService {
return contributions
.readRaw()
.then((r) => {
const old: Contributions = Object.values(r);
const old = Object.values(r);
const filtered = old.filter((c) => c.pack === oldPack);
const edits: EditField<Contribution>[] = filtered.map((p) => ({
id: p.id,
Expand Down
Loading

0 comments on commit da65e0a

Please sign in to comment.