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

Commit

Permalink
feat: add PIITry
Browse files Browse the repository at this point in the history
  • Loading branch information
tdreyno committed Mar 7, 2021
1 parent 602b1a4 commit e39613d
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/__tests__/try.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
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")
})

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")
})
})
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./pii"
export * from "./result"
33 changes: 33 additions & 0 deletions src/result.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
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>>> {
try {
return new Ok(PII(await fn()))
} catch (e) {
return new Err(PII(e))
}
}

0 comments on commit e39613d

Please sign in to comment.