Skip to content

Commit

Permalink
fix: typings unwrap
Browse files Browse the repository at this point in the history
  • Loading branch information
askuzminov committed Dec 25, 2020
1 parent c413e12 commit aa95cf2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/http/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,24 @@ export function cloneInternal(source: unknown, objs: unknown[]): unknown {
}
}

export const unwrap = async <K, S, E>(
export function unwrap<K, S, E>(
result: GError | GSuccess<K> | Promise<GError | GSuccess<K>>,
onSuccess: (data: K) => S | Promise<S>,
onError: ((error: GError['error']) => E | Promise<E>) | undefined
): Promise<S | E>;
export function unwrap<K, S>(
result: GError | GSuccess<K> | Promise<GError | GSuccess<K>>,
onSuccess: (data: K) => S | Promise<S>
): Promise<S | undefined>;
export async function unwrap<K, S, E>(
result: GError | GSuccess<K> | Promise<GError | GSuccess<K>>,
onSuccess: (data: K) => S | Promise<S>,
onError?: (error: GError['error']) => E | Promise<E>
): Promise<S | E | undefined> => {
): Promise<S | E | undefined> {
const resp = await result;
if (resp.success) {
return onSuccess(resp.data);
} else {
return onError?.(resp.error);
}
};
}
15 changes: 15 additions & 0 deletions tests/demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,19 @@ const TOKEN = '123';
);

console.log(userEmail);

const userEmailStrict = await unwrap(
grpc(whisk_api_user_v2_UserAPI_UpdateSettings, { id: 'abc' }),
data => data.user?.email ?? 'Default',
() => 'Nobody'
);

console.log(userEmailStrict);

const userEmailShort = await unwrap(
grpc(whisk_api_user_v2_UserAPI_UpdateSettings, { id: 'abc' }),
data => data.user?.email ?? 'User'
);

console.log(userEmailShort);
})();

0 comments on commit aa95cf2

Please sign in to comment.