Skip to content

Commit

Permalink
feat(discussion): parse comment replies response (#10372)
Browse files Browse the repository at this point in the history
  • Loading branch information
mxdvl authored Jan 29, 2024
1 parent 1ebf0c1 commit b447348
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
12 changes: 6 additions & 6 deletions dotcom-rendering/src/lib/discussionApi.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
import {
discussionApiResponseSchema,
parseAbuseResponse,
parseCommentRepliesResponse,
parseCommentResponse,
} from '../types/discussion';
import type { SignedInWithCookies, SignedInWithOkta } from './identity';
Expand Down Expand Up @@ -421,10 +422,7 @@ export const unPickComment = async (

export const getMoreResponses = async (
commentId: number,
): Promise<{
status: 'ok' | 'error';
comment: CommentType;
}> => {
): Promise<Result<GetDiscussionError, CommentType[]>> => {
const url =
joinUrl(options.baseUrl, 'comment', commentId.toString()) +
objAsParams({
Expand All @@ -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);
};
23 changes: 23 additions & 0 deletions dotcom-rendering/src/types/discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,29 @@ const comment: BaseSchema<CommentType> = 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;
Expand Down

0 comments on commit b447348

Please sign in to comment.