Skip to content

Commit

Permalink
refactor: introduce ErrorWithKey (translation keys as error code)
Browse files Browse the repository at this point in the history
  • Loading branch information
sidvishnoi committed Sep 23, 2024
1 parent 9bb2bad commit 7742172
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 11 deletions.
5 changes: 5 additions & 0 deletions src/background/services/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
failure,
getNextOccurrence,
getWalletInformation,
isErrorWithKey,
success,
} from '@/shared/helpers';
import { OpenPaymentsClientError } from '@interledger/open-payments/dist/client/error';
Expand Down Expand Up @@ -250,6 +251,10 @@ export class Background {
return;
}
} catch (e) {
if (isErrorWithKey(e)) {
this.logger.error(message.action, e);
return failure({ key: e.key, substitutions: e.substitutions });
}
if (e instanceof OpenPaymentsClientError) {
this.logger.error(message.action, e.message, e.description);
return failure(
Expand Down
10 changes: 8 additions & 2 deletions src/popup/lib/context.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import React, { type PropsWithChildren } from 'react';
import type { Browser } from 'webextension-polyfill';
import { tFactory, type Translation } from '@/shared/helpers';
import {
tFactory,
type IErrorWithKey,
type Translation,
} from '@/shared/helpers';
import type { DeepNonNullable, PopupStore } from '@/shared/types';
import {
BACKGROUND_TO_POPUP_CONNECTION_NAME as CONNECTION_NAME,
Expand Down Expand Up @@ -153,7 +157,9 @@ export const BrowserContextProvider = ({
// #endregion

// #region Translation
const TranslationContext = React.createContext<Translation>((v: string) => v);
const TranslationContext = React.createContext<Translation>(
(v: string | IErrorWithKey) => (typeof v === 'string' ? v : v.key),
);

export const useTranslation = () => React.useContext(TranslationContext);

Expand Down
70 changes: 61 additions & 9 deletions src/shared/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import { parse, toSeconds } from 'iso8601-duration';
import type { Browser } from 'webextension-polyfill';
import type { Storage, RepeatingInterval, AmountValue } from './types';

export type TranslationKeys =
keyof typeof import('../_locales/en/messages.json');

export const cn = (...inputs: CxOptions) => {
return twMerge(cx(inputs));
};
Expand Down Expand Up @@ -53,16 +56,56 @@ export const getWalletInformation = async (
return json;
};

/**
* Error object with key and substitutions based on `_locales/[lang]/messages.json`
*/
export interface IErrorWithKey<T extends TranslationKeys = TranslationKeys> {
key: Extract<TranslationKeys, T>;
// Could be empty, but required for checking if an object follows this interface
substitutions: string[];
}

export class ErrorWithKey<T extends TranslationKeys = TranslationKeys>
extends Error
implements IErrorWithKey<T>
{
constructor(
public readonly key: IErrorWithKey<T>['key'],
public readonly substitutions: IErrorWithKey<T>['substitutions'] = [],
) {
super(key);
}
}

/**
* Same as {@linkcode ErrorWithKey} but creates plain object instead of Error
* instance.
* Easier than creating object ourselves, but more performant than Error.
*/
export const errorWithKey = <T extends TranslationKeys = TranslationKeys>(
key: IErrorWithKey<T>['key'],
substitutions: IErrorWithKey<T>['substitutions'] = [],
) => ({ key, substitutions });

export const isErrorWithKey = (err: any): err is IErrorWithKey => {
return (
err instanceof ErrorWithKey ||
(typeof err.key === 'string' && Array.isArray(err.substitutions))
);
};

export const success = <TPayload = undefined>(
payload: TPayload,
): SuccessResponse<TPayload> => ({
success: true,
payload,
});

export const failure = (message: string) => ({
success: false,
message,
export const failure = (message: string | IErrorWithKey) => ({
success: false as const,
...(typeof message === 'string'
? { message }
: { error: message, message: message.key }),
});

export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
Expand Down Expand Up @@ -199,19 +242,28 @@ export function bigIntMax<T extends bigint | AmountValue>(a: T, b: T): T {
return BigInt(a) > BigInt(b) ? a : b;
}

export type TranslationKeys =
keyof typeof import('../_locales/en/messages.json');

export type Translation = ReturnType<typeof tFactory>;
export function tFactory(browser: Pick<Browser, 'i18n'>) {
/**
* Helper over calling cumbersome `this.browser.i18n.getMessage(key)` with
* added benefit that it type-checks if key exists in message.json
*/
return <T extends TranslationKeys>(
function t<T extends TranslationKeys>(
key: T,
substitutions?: string | string[],
) => browser.i18n.getMessage(key, substitutions);
substitutions?: string[],
): string;
function t<T extends TranslationKeys>(err: IErrorWithKey<T>): string;
function t<T extends TranslationKeys>(
key: T | IErrorWithKey<T>,
substitutions?: string[],
): string {
if (typeof key === 'string') {
return browser.i18n.getMessage(key, substitutions);
}
const err = key;
return browser.i18n.getMessage(err.key, err.substitutions);
}
return t;
}

type Primitive = string | number | boolean | null | undefined;
Expand Down
2 changes: 2 additions & 0 deletions src/shared/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
} from '@interledger/open-payments';
import type { Browser } from 'webextension-polyfill';
import type { AmountValue, Storage } from '@/shared/types';
import type { IErrorWithKey } from '@/shared/helpers';
import type { PopupState } from '@/popup/lib/context';

// #region MessageManager
Expand All @@ -15,6 +16,7 @@ export interface SuccessResponse<TPayload = void> {
export interface ErrorResponse {
success: false;
message: string;
error?: IErrorWithKey;
}

export type Response<TPayload = void> =
Expand Down

0 comments on commit 7742172

Please sign in to comment.