|
| 1 | +import { ActionResponse } from "@/backend/models/action-contracts"; |
1 | 2 | import { clsx, type ClassValue } from "clsx"; |
| 3 | +import { toast } from "sonner"; |
2 | 4 | import { twMerge } from "tailwind-merge"; |
3 | 5 | import { z, ZodAnyDef, ZodObject } from "zod"; |
4 | 6 |
|
@@ -110,3 +112,49 @@ export function filterUndefined<T>( |
110 | 112 | Object.entries(mapping).filter(([_, value]) => value !== undefined) |
111 | 113 | ) as Partial<Record<string, any>>; |
112 | 114 | } |
| 115 | + |
| 116 | +// Improved with automatic type inference |
| 117 | +export const actionPromisify = async <T = any>( |
| 118 | + action: Promise<ActionResponse<T>> |
| 119 | +): Promise<T> => { |
| 120 | + const promise = new Promise<T>(async (resolve, reject) => { |
| 121 | + try { |
| 122 | + const resolvedAction = await action; |
| 123 | + |
| 124 | + if (!resolvedAction) { |
| 125 | + reject("Action returned undefined"); |
| 126 | + return; |
| 127 | + } |
| 128 | + |
| 129 | + if (!resolvedAction.success) { |
| 130 | + // @ts-ignore |
| 131 | + reject(resolvedAction.error ?? "Unknown error occurred"); |
| 132 | + return; |
| 133 | + } |
| 134 | + |
| 135 | + if (resolvedAction.success) { |
| 136 | + resolve(resolvedAction.data); |
| 137 | + return; |
| 138 | + } |
| 139 | + } catch (error) { |
| 140 | + if (error instanceof Error) { |
| 141 | + reject(error.message); |
| 142 | + } else { |
| 143 | + reject("An unexpected error occurred"); |
| 144 | + } |
| 145 | + } |
| 146 | + }); |
| 147 | + |
| 148 | + // if (options?.withToast) { |
| 149 | + // toast.promise(promise, { |
| 150 | + // loading: options?.messages?.loading ?? "Loading...", |
| 151 | + // success: options?.messages?.success ?? "Success!", |
| 152 | + // error: (errorMsg: string) => errorMsg || "Operation failed", |
| 153 | + // }); |
| 154 | + // } |
| 155 | + |
| 156 | + return promise; |
| 157 | +}; |
| 158 | + |
| 159 | +export const sleep = (ms: number) => |
| 160 | + new Promise((resolve) => setTimeout(() => resolve("Hello"), ms)); |
0 commit comments