Skip to content

Commit

Permalink
Merge pull request #18 from meech-ward/dev
Browse files Browse the repository at this point in the history
Update either type
  • Loading branch information
meech-ward authored Oct 27, 2024
2 parents d55676e + 2b40a67 commit c3f47a6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
28 changes: 28 additions & 0 deletions examples/mightFailBasic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,31 @@ async function main() {
}

main()

function someResponse() {
const responses = [
{ status: 200, data: { id: 1, name: "John Doe" }, json: async () => ({ status: 200, data: { id: 1, name: "John Doe" } }) },
{ status: 404, error: "Not Found", json: async () => ({ status: 404, error: "Not Found" }) },
{ status: 500, error: "Internal Server Error", json: async () => ({ status: 500, error: "Internal Server Error" }) },
{ status: 201, data: { id: 2, name: "Jane Smith", created: true }, json: async () => ({ status: 201, data: { id: 2, name: "Jane Smith", created: true } }) },
{ status: 400, error: "Bad Request", details: ["Invalid email", "Password too short"], json: async () => ({ status: 400, error: "Bad Request", details: ["Invalid email", "Password too short"] }) },
];

const randomIndex = Math.floor(Math.random() * responses.length);
const randomResponse = responses[randomIndex];

return randomResponse;
}

async function main2() {
const res = someResponse()
const [error, result] = await mightFail(res.json())
if (error) {
console.error(error)
return
}
console.log(result)
}

main2()

8 changes: 4 additions & 4 deletions src/utils/utils.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ export type EitherMode = "standard" | "go" | "any"
export type AnyEither<T> = StandardEither<T> | GoEither<T>

export type MightFailFunction<TEitherMode extends EitherMode> = <T>(
promise: Promise<T>
promise: T
) => Promise<
TEitherMode extends "standard"
? StandardEither<T>
? StandardEither<Awaited<T>>
: TEitherMode extends "go"
? GoEither<T>
: AnyEither<T>
? GoEither<Awaited<T>>
: AnyEither<Awaited<T>>
>

export type PromiseFulfilledResult<T> = {
Expand Down

0 comments on commit c3f47a6

Please sign in to comment.