Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor getCommentContext #10512

Merged
merged 5 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions dotcom-rendering/src/components/Discussion.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { palette, space } from '@guardian/source-foundations';
import { Button, SvgPlus } from '@guardian/source-react-components';
import { useEffect, useReducer } from 'react';
import { assertUnreachable } from '../lib/assert-unreachable';
import { getDiscussion, type reportAbuse } from '../lib/discussionApi';
import {
getCommentContext,
initFiltersFromLocalStorage,
} from '../lib/getCommentContext';
getDiscussion,
type reportAbuse,
} from '../lib/discussionApi';
import { initFiltersFromLocalStorage } from '../lib/discussionFilters';
import { palette as themePalette } from '../palette';
import type {
CommentForm,
Expand Down Expand Up @@ -480,10 +481,16 @@ export const Discussion = ({
remapToValidFilters(filters, hashCommentId),
)
.then((context) => {
dispatch({
type: 'updateCommentPage',
commentPage: context.page,
});
if (context.kind === 'ok') {
dispatch({
type: 'updateCommentPage',
commentPage: context.value.page,
});
} else {
console.error(
`getCommentContext - error: ${context.error}`,
);
}
})
.catch((e) =>
console.error(`getCommentContext - error: ${String(e)}`),
Expand Down
35 changes: 35 additions & 0 deletions dotcom-rendering/src/lib/discussionApi.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@ import type {
} from '../types/discussion';
import {
discussionApiResponseSchema,
getCommentContextResponseSchema,
parseAbuseResponse,
parseCommentRepliesResponse,
parseCommentResponse,
pickResponseSchema,
postUsernameResponseSchema,
} from '../types/discussion';
import type { CommentContextType } from './discussionFilters';
import { buildParams } from './discussionFilters';
import type { SignedInWithCookies, SignedInWithOkta } from './identity';
import { getOptionsHeadersWithOkta } from './identity';
import { fetchJSON } from './json';
Expand Down Expand Up @@ -436,3 +439,35 @@ export const getMoreResponses = async (

return parseCommentRepliesResponse(jsonResult.value);
};

export const getCommentContext = async (
ajaxUrl: string,
commentId: number,
filters: FilterOptions,
): Promise<Result<GetDiscussionError, CommentContextType>> => {
const url = joinUrl(ajaxUrl, 'comment', commentId.toString(), 'context');
const params = buildParams(filters);

const response = await fetch(url + '?' + params.toString());
DanielCliftonGuardian marked this conversation as resolved.
Show resolved Hide resolved

if (!response.ok) {
const sentryError = new Error(
response.statusText ||
`getCommentContext | An api call returned HTTP status ${response.status}`,
);
window.guardian.modules.sentry.reportError(
sentryError,
'get-comment-page',
);
return error('ApiError');
}

const json = await response.json();
const result = safeParse(getCommentContextResponseSchema, json);

if (!result.success) {
return error('ParsingError');
}

return ok(result.output as CommentContextType);
DanielCliftonGuardian marked this conversation as resolved.
Show resolved Hide resolved
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isOneOf, isString, joinUrl, storage } from '@guardian/libs';
import { isOneOf, isString, storage } from '@guardian/libs';

const orderByTypes = ['newest', 'oldest', 'recommendations'] as const;
const threadTypes = ['collapsed', 'expanded', 'unthreaded'] as const;
Expand All @@ -11,7 +11,7 @@ type PageSizeType = (typeof pageSizeTypes)[number];
/**
* @see http://discussion.guardianapis.com/discussion-api/comment/3519111/context
*/
type CommentContextType = {
export type CommentContextType = {
status: 'ok' | 'error';
commentId: number;
commentAncestorId: number;
Expand Down Expand Up @@ -55,7 +55,7 @@ export const initFiltersFromLocalStorage = (): FilterOptions => {
};
};

const buildParams = (filters: FilterOptions) => {
export const buildParams = (filters: FilterOptions): URLSearchParams => {
return new URLSearchParams({
DanielCliftonGuardian marked this conversation as resolved.
Show resolved Hide resolved
// Frontend uses the 'recommendations' key to store this options but the api expects
// 'mostRecommended' so we have to map here to support both
Expand All @@ -69,31 +69,3 @@ const buildParams = (filters: FilterOptions) => {
),
});
};

export const getCommentContext = async (
ajaxUrl: string,
commentId: number,
filters: FilterOptions,
): Promise<CommentContextType> => {
const url = joinUrl(ajaxUrl, 'comment', commentId.toString(), 'context');

const params = buildParams(filters);

return fetch(url + '?' + params.toString())
.then((response) => {
if (!response.ok) {
throw Error(
response.statusText ||
`getCommentContext | An api call returned HTTP status ${response.status}`,
);
}
return response;
})
.then((response) => response.json())
.catch((error) => {
window.guardian.modules.sentry.reportError(
error,
'get-comment-page',
);
});
};
12 changes: 12 additions & 0 deletions dotcom-rendering/src/types/discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,3 +389,15 @@ export type CommentForm = {
previewBody: string;
body: string;
};

export const getCommentContextResponseSchema = object({
status: literal('ok'),
commentId: number(),
commentAncestorId: number(),
discussionKey: string(),
discussionWebUrl: string(),
discussionApiUrl: string(),
orderBy: string(),
pageSize: number(),
page: number(),
});
Loading