Browse Source

Add Option type and update tryDo to use it

ghorsington 4 years ago
parent
commit
99debdbe79
3 changed files with 8 additions and 4 deletions
  1. 1 1
      bot/src/plugins/inspire.ts
  2. 1 1
      bot/src/plugins/rcg.ts
  3. 6 2
      bot/src/util.ts

+ 1 - 1
bot/src/plugins/inspire.ts

@@ -15,7 +15,7 @@ export class Inspire {
     })
     async inspire({ message }: ICommandData): Promise<void> {
         const result = await tryDo(got.get("https://inspirobot.me/api?generate=true"));
-        if(!result.ok || !result.result) {
+        if(!result.ok) {
             logger.error("Failed to get inspiration, error %s", result.error);
             await message.reply("sorry, couldn't get inspiration :(.");
             return;

+ 1 - 1
bot/src/plugins/rcg.ts

@@ -32,7 +32,7 @@ export class Rcg {
     async randomComic({ message }: ICommandData): Promise<void> {
         const result = await tryDo(got.get("http://explosm.net/rcg/view/?promo=false"));
     
-        if (!result.ok || !result.result) {
+        if (!result.ok) {
             logger.error("Failed to get RCG. Got error: %s", result.error);
             await this.sendErrorMessage(message);
             return;

+ 6 - 2
bot/src/util.ts

@@ -79,7 +79,7 @@ export function formatString(str: string, vars: Record<string, string>): string
     return Object.keys(vars).filter(s => Object.prototype.hasOwnProperty.call(vars, s)).reduce((s, cur) => s.replace(`{${cur}}`, vars[cur]), str);
 }
 
-export async function tryDo<TResult>(promise: Promise<TResult>) : Promise<{ok: boolean, result?: TResult, error?: unknown}> {
+export async function tryDo<TResult>(promise: Promise<TResult>) : Promise<Option<{result: TResult}, {error: unknown}>> {
     try {
         return {ok: true, result: await promise};
     } catch(err) {
@@ -173,4 +173,8 @@ export function parseDuration(s: string): number | undefined {
     if (buffer.length != 0)
         return undefined;
     return result;
-}
+}
+
+export type Ok<T> = T & { ok: true };
+export type Error<T> = T & { ok: false };
+export type Option<T, U = unknown> = Ok<T> | Error<U>;