From 55fffef5cbce1cd3e0c309aae9b587b9d41393a1 Mon Sep 17 00:00:00 2001 From: James Collins Date: Thu, 23 Mar 2023 10:14:30 +1000 Subject: [PATCH] added getApiResultData helper --- resources/js/helpers/api.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/resources/js/helpers/api.ts b/resources/js/helpers/api.ts index 24c3cea..ec27559 100644 --- a/resources/js/helpers/api.ts +++ b/resources/js/helpers/api.ts @@ -275,3 +275,23 @@ export const api = { return await this.send(options); }, }; + +/** + * Get an api result data as type. + * + * @param result The api result object. + * @param defaultValue The default data to return if no result exists. + * @returns Data object. + */ +export function getApiResultData( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + result: any, + defaultValue: T | null = null +): T | null { + if (!result || !Object.prototype.hasOwnProperty.call(result, "data")) { + return defaultValue; + } + + const data = result.data as T; + return data instanceof Object ? data : defaultValue; +}