diff --git a/dotcom-rendering/src/components/Discussion/CommentContainer.tsx b/dotcom-rendering/src/components/Discussion/CommentContainer.tsx index e9cf6599a72..55842f077d1 100644 --- a/dotcom-rendering/src/components/Discussion/CommentContainer.tsx +++ b/dotcom-rendering/src/components/Discussion/CommentContainer.tsx @@ -122,9 +122,13 @@ export const CommentContainer = ({ const expand = (commentId: number) => { setLoading(true); getMoreResponses(commentId) - .then((json) => { + .then((result) => { + if (result.kind === 'error') { + console.error(result.error); + return; + } setExpanded(true); - setResponses(json.comment.responses ?? []); + setResponses(result.value); }) .finally(() => { setLoading(false); diff --git a/dotcom-rendering/src/lib/discussionApi.tsx b/dotcom-rendering/src/lib/discussionApi.tsx index b600a8b64a2..af7428900c6 100644 --- a/dotcom-rendering/src/lib/discussionApi.tsx +++ b/dotcom-rendering/src/lib/discussionApi.tsx @@ -13,6 +13,7 @@ import type { import { discussionApiResponseSchema, parseAbuseResponse, + parseCommentRepliesResponse, parseCommentResponse, } from '../types/discussion'; import type { SignedInWithCookies, SignedInWithOkta } from './identity'; @@ -421,10 +422,7 @@ export const unPickComment = async ( export const getMoreResponses = async ( commentId: number, -): Promise<{ - status: 'ok' | 'error'; - comment: CommentType; -}> => { +): Promise> => { const url = joinUrl(options.baseUrl, 'comment', commentId.toString()) + objAsParams({ @@ -435,11 +433,13 @@ export const getMoreResponses = async ( }, }); - const resp = await fetch(url, { + const jsonResult = await fetchJSON(url, { headers: { ...options.headers, }, }); - return resp.json(); + if (jsonResult.kind === 'error') return jsonResult; + + return parseCommentRepliesResponse(jsonResult.value); }; diff --git a/dotcom-rendering/src/types/discussion.ts b/dotcom-rendering/src/types/discussion.ts index 14868e00231..143192ef944 100644 --- a/dotcom-rendering/src/types/discussion.ts +++ b/dotcom-rendering/src/types/discussion.ts @@ -108,6 +108,29 @@ const comment: BaseSchema = object({ ), }); +const discussionApiCommentSuccessSchema = variant('status', [ + object({ + status: literal('error'), + }), + object({ + status: literal('ok'), + comment, + }), +]); + +export const parseCommentRepliesResponse = ( + data: unknown, +): Result<'ParsingError' | 'ApiError', CommentType[]> => { + const result = safeParse(discussionApiCommentSuccessSchema, data); + if (!result.success) { + return { kind: 'error', error: 'ParsingError' }; + } + if (result.output.status === 'error') { + return { kind: 'error', error: 'ApiError' }; + } + return { kind: 'ok', value: result.output.comment.responses ?? [] }; +}; + export interface CommentType { id: number; body: string;