Skip to content
This repository has been archived by the owner on Apr 2, 2023. It is now read-only.

Commit

Permalink
fix: simpler PIITry
Browse files Browse the repository at this point in the history
  • Loading branch information
tdreyno committed Mar 7, 2021
1 parent e39613d commit 33a6115
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 38 deletions.
21 changes: 8 additions & 13 deletions src/__tests__/try.spec.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
import { PIITry, unwrap } from "../index"
import { identity } from "../result"

describe("PIITry", () => {
it("should wrap results in PII", async () => {
const result = await PIITry(() => "TEST_STRING")
const success = result.fold(identity, () => void 0)
expect(unwrap(success)).toBe("TEST_STRING")
expect(result).toBe("TEST_STRING")
})

it("should wrap exceptions in PII", async () => {
const result = await PIITry<never, Error>(() => {
throw new Error("Error message")
})

const errorMessage = result.fold(
() => "never",
e => unwrap(e).message,
)

expect(errorMessage).toBe("Error message")
try {
await PIITry(() => {
throw new Error("Error message")
})
} catch (e) {
expect(unwrap(e).message).toBe("Error message")
}
})
})
28 changes: 3 additions & 25 deletions src/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,10 @@ import { PII } from "./pii"

export const identity = <X>(x: X): X => x

export class Ok<S, E> {
constructor(private value: S) {}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
fold<R>(ok: (value: S) => R, _err: (err: E) => R): R {
return ok(this.value)
}
}

export class Err<E, S> {
constructor(private err: E) {}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
fold<R>(_ok: (value: S) => R, err: (err: E) => R): R {
return err(this.err)
}
}

export type Result<S, E> = Ok<S, E> | Err<E, S>

export async function PIITry<S, E extends Error>(
fn: () => S | Promise<S>,
): Promise<Result<PII<S>, PII<E>>> {
export async function PIITry<S>(fn: () => S | Promise<S>): Promise<S> {
try {
return new Ok(PII(await fn()))
return fn()
} catch (e) {
return new Err(PII(e))
throw PII(e)
}
}

0 comments on commit 33a6115

Please sign in to comment.