Last active
March 5, 2024 12:37
-
-
Save elierotenberg/261f8a008c6062c257878eb1631f5276 to your computer and use it in GitHub Desktop.
Maybe with fallback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { app_by_id } = await gql.getMiddlewareData({ app_id: MOSAIC_APP_ID }); | |
const appLocaleList = maybe(app_by_id, `App not found`) | |
.pipe((app) => app.locale, `App locale not found`) | |
.get() | |
.map((appLocale) => | |
appLocale?.locale_code | |
? { | |
code: appLocale.locale_code.code, | |
isDefault: appLocale.is_default, | |
slug: appLocale.slug, | |
} | |
: null, | |
) | |
.filter(isNonNullable); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const isNonNullable = <T>(value: T): value is NonNullable<T> => | |
typeof value !== `undefined` && value != null; | |
export class Maybe<T> { | |
private readonly value: T; | |
private readonly notFoundMessage: string; | |
public constructor(value: T, notFoundMessage: string) { | |
this.value = value; | |
this.notFoundMessage = notFoundMessage; | |
} | |
public readonly pipe = <U>( | |
fn: (value: NonNullable<T>) => U, | |
notFoundMessage?: string, | |
): Maybe<U> | Maybe<U | null> => { | |
if (isNonNullable(this.value)) { | |
return new Maybe<U>( | |
fn(this.value), | |
notFoundMessage ?? this.notFoundMessage, | |
); | |
} | |
return new Maybe<U | null>(null, this.notFoundMessage); | |
}; | |
public readonly fallback = <F extends NonNullable<T>>( | |
fallbackValue: F, | |
): NonNullable<T> | F => { | |
if (isNonNullable(this.value)) { | |
return this.value; | |
} | |
return fallbackValue; | |
}; | |
public readonly get = (): NonNullable<T> => { | |
if (isNonNullable(this.value)) { | |
return this.value; | |
} | |
throw new Error(this.notFoundMessage); | |
}; | |
} | |
export const maybe = <T>( | |
value: T | null | undefined, | |
notFoundMessage: string, | |
) => new Maybe(value, notFoundMessage); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment