refactor: migrate to tsup for builds and update tsconfigs fix: update error handling and validation in payment service chore: update package scripts and dependencies docs: update README and env examples
26 lines
959 B
TypeScript
26 lines
959 B
TypeScript
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 = <T, E extends AppError<unknown>>(
|
|
operation: () => Promise<T>,
|
|
errorFactory: (error: unknown) => E,
|
|
): ResultAsync<T, E> => {
|
|
return ResultAsync.fromPromise(operation(), errorFactory);
|
|
};
|
|
|
|
export const wrapDbOperationWithNull = <T, E extends AppError<unknown>>(
|
|
operation: () => Promise<T | null>,
|
|
notFoundError: E,
|
|
dbErrorFactory: (error: unknown) => E,
|
|
): ResultAsync<T, E> => {
|
|
return ResultAsync.fromPromise(operation(), (error) =>
|
|
dbErrorFactory(error),
|
|
).andThen((result) => (result === null ? err(notFoundError) : ok(result)));
|
|
};
|