import { ResultAsync, err, ok } from "neverthrow"; import { AppError } from "../types"; /** * Wraps a database operation in a Result type to handle errors gracefully * @param operation - The database operation to execute * @param errorFactory - Function to create a custom error if the operation fails * @returns Result containing the operation result or error */ export const wrapDbOperation = >( operation: () => Promise, errorFactory: (error: unknown) => E, ): ResultAsync => { return ResultAsync.fromPromise(operation(), errorFactory); }; export const wrapDbOperationWithNull = >( operation: () => Promise, notFoundError: E, dbErrorFactory: (error: unknown) => E, ): ResultAsync => { return ResultAsync.fromPromise(operation(), (error) => dbErrorFactory(error), ).andThen((result) => (result === null ? err(notFoundError) : ok(result))); };