Skip to content

Commit

Permalink
chore(build): enable strict mode (#58)
Browse files Browse the repository at this point in the history
* chore(build): enable strict mode
* chore(build): mark decorated props as definate
* chore(build): add some null checks
* chore(build): fix module loader types
* chore(build): shore up the LookupResult type
* chore(build): fix up more decorated definates
* chore(build): appease codacy
  • Loading branch information
ackwell authored May 16, 2022
1 parent a7b263d commit 9154036
Show file tree
Hide file tree
Showing 11 changed files with 56 additions and 37 deletions.
7 changes: 6 additions & 1 deletion core/src/bot/discord.options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,13 @@ export class DiscordOptions implements DiscordOptionsFactory {
constructor(private config: ConfigService) {}

public createDiscordOptions(): DiscordModuleOption {
const token = this.config.get('TOKEN');
if (token == null) {
throw new Error(`Missing TOKEN configuration key.`);
}

return {
token: this.config.get('TOKEN'),
token,
discordClientOptions: {
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
},
Expand Down
2 changes: 1 addition & 1 deletion core/src/bot/dto/play.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ export class PlayDto {
'Name or URL of song/playlist. Could be from (Youtube, Spotify, SoundCloud)',
required: true,
})
song: string;
song!: string;
}
41 changes: 25 additions & 16 deletions core/src/module-system/module.loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ export class ModuleLoader {
__dirname,
);

if (checkPath == null) {
throw new Error(`Failed to resolve own package path.`);
}

let modulesPath;

do {
Expand All @@ -41,12 +45,12 @@ export class ModuleLoader {

private static async resolveModules(
rootPath: string,
prefix: string = null,
prefix?: string,
): Promise<DynamicModule[]> {
const nodeModules = await fs.readdir(rootPath);
const resolvedModules = [];
const resolvedModules: DynamicModule[] = [];
for (const nodeModule of nodeModules) {
if (nodeModule.startsWith('@') && !prefix) {
if (nodeModule.startsWith('@') && prefix == null) {
resolvedModules.push(
...(await this.resolveModules(
path.join(rootPath, nodeModule),
Expand All @@ -60,30 +64,35 @@ export class ModuleLoader {
if (nodeModule.startsWith('venat-module-')) {
try {
const modulePath = (prefix ?? '') + nodeModule;
let module = await import(modulePath);
let metadata: VenatModuleMetadata;
for (const exp of Object.values(module)) {
if (Reflect.hasMetadata(METADATA_KEY, exp)) {
module = exp;
metadata = Reflect.getMetadata(METADATA_KEY, exp);
break;
}
}
const module: { [key: string]: object } = await import(modulePath);

const nestModule = Object.values(module).find(
(item): item is DynamicModule =>
Reflect.hasMetadata(METADATA_KEY, item),
);

if (!metadata) {
if (nestModule == null) {
throw new Error(
`Module ${module} does not have @VenatModule decorator`,
);
}

const metadata: VenatModuleMetadata = Reflect.getMetadata(
METADATA_KEY,
nestModule,
);

ModuleLoader.logger.log(
`Found module: ${metadata.name} (${modulePath})`,
);
resolvedModules.push(module);
resolvedModules.push(nestModule);
ModuleLoader.loadedModuleInfo.push(metadata);
} catch (e) {
} catch (error) {
if (!(error instanceof Error)) {
throw error;
}
ModuleLoader.logger.error(
`Failed to load module ${nodeModule}: ${e.message}`,
`Failed to load module ${nodeModule}: ${error.message}`,
);
}
}
Expand Down
6 changes: 3 additions & 3 deletions core/src/users/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ export class User {
* The Discord user ID/snowflake.
*/
@PrimaryColumn()
id: number;
id!: number;

/**
* Is this Discord user an administrator of this bot instance?
*/
// todo: replace this with roles in the future?
@Column()
isAdmin: boolean;
isAdmin!: boolean;

/**
* Is this Discord user banned from using the bot?
*/
@Column()
isBanned: boolean;
isBanned!: boolean;
}
2 changes: 1 addition & 1 deletion core/src/users/guards/user-is-bot-admin.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ export class UserIsBotAdminGuard implements DiscordGuard {
[message, user]: [Message, User],
): Promise<boolean> {
const userEntity = await this.usersService.find(user);
return userEntity && userEntity.isAdmin;
return userEntity?.isAdmin ?? false;
}
}
8 changes: 3 additions & 5 deletions core/src/util/io.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
export interface LookupResult<TValue> {
value: TValue;
success: boolean;
err?: Error;
}
export type LookupResult<TValue> =
| { success: true; value: TValue }
| { success: false; err: Error };
4 changes: 2 additions & 2 deletions modules/venat-module-xiv-market/src/data/listings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function getMarketInfoByName(
server: string,
): Promise<MarketInfo | string> => {
const itemLookup = await getItemIdByName(itemName);
if (itemLookup.err != null) {
if (!itemLookup.success) {
logError(itemLookup.err.message, itemLookup.err.stack);
return 'Failed to access XIVAPI; please try again later.';
}
Expand All @@ -43,7 +43,7 @@ export function getMarketInfoByName(

const item = itemLookup.value;
const marketLookup = await getMarketInfo(item.ID, server);
if (marketLookup.err != null) {
if (!marketLookup.success) {
logError(marketLookup.err.message, marketLookup.err.stack);
return 'The item could not be found; please check your spelling of the server and try again.';
}
Expand Down
5 changes: 4 additions & 1 deletion modules/venat-module-xiv-market/src/data/universalis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ export async function getMarketInfo(
`https://universalis.app/api/${server}/${itemId}`,
);
} catch (err) {
return { value: null, success: false, err };
if (!(err instanceof Error)) {
throw err;
}
return { success: false, err };
}

return { value: res.data, success: true };
Expand Down
10 changes: 8 additions & 2 deletions modules/venat-module-xiv-market/src/data/xivapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ export async function getItemIdByName(
`https://xivapi.com/search?string=${name}&filters=ItemSearchCategory.ID>8&columns=ID,Name`,
);
} catch (err) {
return { value: null, success: false, err };
if (!(err instanceof Error)) {
throw err;
}
return { success: false, err };
}

const nameLower = name.toLowerCase();
Expand All @@ -29,5 +32,8 @@ export async function getItemIdByName(
}
}

return { value: null, success: false };
return {
err: new Error(`The item ${name} could not be found.`),
success: false,
};
}
4 changes: 2 additions & 2 deletions modules/venat-module-xiv-market/src/dto/market.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ export class MarketDto {
name: 'item',
required: true,
})
public item: string;
public item!: string;

@Transform(cleanText)
@Param({
description: 'The server to look up prices on.',
name: 'server',
required: true,
})
public server: string;
public server!: string;
}
4 changes: 1 addition & 3 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
"composite": true,
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"strict": true,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
"useDefineForClassFields": true
Expand Down

0 comments on commit 9154036

Please sign in to comment.