[questions][feat] paginate browse queries

pull/410/head
Jeff Sieu 3 years ago
parent 3ac3f8ee2d
commit d2c5013bb9

@ -17,29 +17,26 @@ export type FilterChoices<V extends string = string> = ReadonlyArray<
FilterChoice<V> FilterChoice<V>
>; >;
type FilterSectionType<FilterOptions extends Array<FilterOption>> = type FilterSectionType<V extends string> =
| { | {
isSingleSelect: true; isSingleSelect: true;
onOptionChange: (optionValue: FilterOptions[number]['value']) => void; onOptionChange: (option: FilterOption<V>) => void;
} }
| { | {
isSingleSelect?: false; isSingleSelect?: false;
onOptionChange: ( onOptionChange: (option: FilterOption<V>) => void;
optionValue: FilterOptions[number]['value'],
checked: boolean,
) => void;
}; };
export type FilterSectionProps<FilterOptions extends Array<FilterOption>> = export type FilterSectionProps<V extends string = string> =
FilterSectionType<FilterOptions> & { FilterSectionType<V> & {
label: string; label: string;
options: FilterOptions; options: Array<FilterOption<V>>;
} & ( } & (
| { | {
renderInput: (props: { renderInput: (props: {
field: UseFormRegisterReturn<'search'>; field: UseFormRegisterReturn<'search'>;
onOptionChange: FilterSectionType<FilterOptions>['onOptionChange']; onOptionChange: FilterSectionType<V>['onOptionChange'];
options: FilterOptions; options: Array<FilterOption<V>>;
}) => React.ReactNode; }) => React.ReactNode;
showAll?: never; showAll?: never;
} }
@ -53,16 +50,14 @@ export type FilterSectionFormData = {
search: string; search: string;
}; };
export default function FilterSection< export default function FilterSection<V extends string>({
FilterOptions extends Array<FilterOption>,
>({
label, label,
options, options,
showAll, showAll,
onOptionChange, onOptionChange,
isSingleSelect, isSingleSelect,
renderInput, renderInput,
}: FilterSectionProps<FilterOptions>) { }: FilterSectionProps<V>) {
const { register, reset } = useForm<FilterSectionFormData>(); const { register, reset } = useForm<FilterSectionFormData>();
const registerSearch = register('search'); const registerSearch = register('search');
@ -76,7 +71,9 @@ export default function FilterSection<
}; };
const autocompleteOptions = useMemo(() => { const autocompleteOptions = useMemo(() => {
return options.filter((option) => !option.checked) as FilterOptions; return options.filter((option) => !option.checked) as Array<
FilterOption<V>
>;
}, [options]); }, [options]);
const selectedCount = useMemo(() => { const selectedCount = useMemo(() => {
@ -102,11 +99,12 @@ export default function FilterSection<
<div className="z-10"> <div className="z-10">
{renderInput({ {renderInput({
field, field,
onOptionChange: async ( onOptionChange: async (option: FilterOption<V>) => {
optionValue: FilterOptions[number]['value'],
) => {
reset(); reset();
return onOptionChange(optionValue, true); return onOptionChange({
...option,
checked: true,
});
}, },
options: autocompleteOptions, options: autocompleteOptions,
})} })}
@ -119,7 +117,13 @@ export default function FilterSection<
label={label} label={label}
value={options.find((option) => option.checked)?.value} value={options.find((option) => option.checked)?.value}
onChange={(value) => { onChange={(value) => {
onOptionChange(value); const changedOption = options.find(
(option) => option.value === value,
)!;
onOptionChange({
...changedOption,
checked: !changedOption.checked,
});
}}> }}>
{options.map((option) => ( {options.map((option) => (
<RadioList.Item <RadioList.Item
@ -140,7 +144,10 @@ export default function FilterSection<
label={option.label} label={option.label}
value={option.checked} value={option.checked}
onChange={(checked) => { onChange={(checked) => {
onOptionChange(option.value, checked); onOptionChange({
...option,
checked,
});
}} }}
/> />
))} ))}

@ -1,4 +1,6 @@
import type { ComponentProps } from 'react'; import type { ComponentProps } from 'react';
import { useState } from 'react';
import { useMemo } from 'react';
import { Button, Typeahead } from '@tih/ui'; import { Button, Typeahead } from '@tih/ui';
import type { RequireAllOrNone } from '~/utils/questions/RequireAllOrNone'; import type { RequireAllOrNone } from '~/utils/questions/RequireAllOrNone';
@ -7,6 +9,8 @@ type TypeaheadProps = ComponentProps<typeof Typeahead>;
type TypeaheadOption = TypeaheadProps['options'][number]; type TypeaheadOption = TypeaheadProps['options'][number];
export type ExpandedTypeaheadProps = RequireAllOrNone<{ export type ExpandedTypeaheadProps = RequireAllOrNone<{
clearOnSelect?: boolean;
filterOption: (option: TypeaheadOption) => boolean;
onSuggestionClick: (option: TypeaheadOption) => void; onSuggestionClick: (option: TypeaheadOption) => void;
suggestedCount: number; suggestedCount: number;
}> & }> &
@ -15,9 +19,20 @@ export type ExpandedTypeaheadProps = RequireAllOrNone<{
export default function ExpandedTypeahead({ export default function ExpandedTypeahead({
suggestedCount = 0, suggestedCount = 0,
onSuggestionClick, onSuggestionClick,
filterOption = () => true,
clearOnSelect = false,
options,
onSelect,
...typeaheadProps ...typeaheadProps
}: ExpandedTypeaheadProps) { }: ExpandedTypeaheadProps) {
const suggestions = typeaheadProps.options.slice(0, suggestedCount); const [key, setKey] = useState(0);
const filteredOptions = useMemo(() => {
return options.filter(filterOption);
}, [options, filterOption]);
const suggestions = useMemo(
() => filteredOptions.slice(0, suggestedCount),
[filteredOptions, suggestedCount],
);
return ( return (
<div className="flex flex-wrap gap-x-2"> <div className="flex flex-wrap gap-x-2">
@ -32,7 +47,17 @@ export default function ExpandedTypeahead({
/> />
))} ))}
<div className="flex-1"> <div className="flex-1">
<Typeahead {...typeaheadProps} /> <Typeahead
key={key}
options={filteredOptions}
{...typeaheadProps}
onSelect={(option) => {
if (clearOnSelect) {
setKey((key + 1) % 2);
}
onSelect(option);
}}
/>
</div> </div>
</div> </div>
); );

@ -5,24 +5,22 @@ import { useEffect, useMemo, useState } from 'react';
import { Bars3BottomLeftIcon } from '@heroicons/react/20/solid'; import { Bars3BottomLeftIcon } from '@heroicons/react/20/solid';
import { NoSymbolIcon } from '@heroicons/react/24/outline'; import { NoSymbolIcon } from '@heroicons/react/24/outline';
import type { QuestionsQuestionType } from '@prisma/client'; import type { QuestionsQuestionType } from '@prisma/client';
import { Button, SlideOut, Typeahead } from '@tih/ui'; import { Button, SlideOut } from '@tih/ui';
import QuestionOverviewCard from '~/components/questions/card/question/QuestionOverviewCard'; import QuestionOverviewCard from '~/components/questions/card/question/QuestionOverviewCard';
import ContributeQuestionCard from '~/components/questions/ContributeQuestionCard'; import ContributeQuestionCard from '~/components/questions/ContributeQuestionCard';
import type { FilterOption } from '~/components/questions/filter/FilterSection';
import FilterSection from '~/components/questions/filter/FilterSection'; import FilterSection from '~/components/questions/filter/FilterSection';
import QuestionSearchBar from '~/components/questions/QuestionSearchBar'; import QuestionSearchBar from '~/components/questions/QuestionSearchBar';
import CompanyTypeahead from '~/components/questions/typeahead/CompanyTypeahead';
import LocationTypeahead from '~/components/questions/typeahead/LocationTypeahead';
import RoleTypeahead from '~/components/questions/typeahead/RoleTypeahead';
import type { QuestionAge } from '~/utils/questions/constants'; import type { QuestionAge } from '~/utils/questions/constants';
import { SORT_TYPES } from '~/utils/questions/constants'; import { SORT_TYPES } from '~/utils/questions/constants';
import { SORT_ORDERS } from '~/utils/questions/constants'; import { SORT_ORDERS } from '~/utils/questions/constants';
import { APP_TITLE } from '~/utils/questions/constants'; import { APP_TITLE } from '~/utils/questions/constants';
import { ROLES } from '~/utils/questions/constants'; import { QUESTION_AGES, QUESTION_TYPES } from '~/utils/questions/constants';
import {
COMPANIES,
LOCATIONS,
QUESTION_AGES,
QUESTION_TYPES,
} from '~/utils/questions/constants';
import createSlug from '~/utils/questions/createSlug'; import createSlug from '~/utils/questions/createSlug';
import { import {
useSearchParam, useSearchParam,
@ -148,12 +146,18 @@ export default function QuestionsBrowsePage() {
: undefined; : undefined;
}, [selectedQuestionAge]); }, [selectedQuestionAge]);
const { data: questions } = trpc.useQuery( const {
data: questionsQueryData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = trpc.useInfiniteQuery(
[ [
'questions.questions.getQuestionsByFilter', 'questions.questions.getQuestionsByFilter',
{ {
companyNames: selectedCompanies, companyNames: selectedCompanies,
endDate: today, endDate: today,
limit: 5,
locations: selectedLocations, locations: selectedLocations,
questionTypes: selectedQuestionTypes, questionTypes: selectedQuestionTypes,
roles: selectedRoles, roles: selectedRoles,
@ -163,10 +167,21 @@ export default function QuestionsBrowsePage() {
}, },
], ],
{ {
getNextPageParam: (lastPage) => lastPage.nextCursor,
keepPreviousData: true, keepPreviousData: true,
}, },
); );
const questionCount = useMemo(() => {
if (!questionsQueryData) {
return undefined;
}
return questionsQueryData.pages.reduce(
(acc, page) => acc + page.data.length,
0,
);
}, [questionsQueryData]);
const utils = trpc.useContext(); const utils = trpc.useContext();
const { mutate: createQuestion } = trpc.useMutation( const { mutate: createQuestion } = trpc.useMutation(
'questions.questions.create', 'questions.questions.create',
@ -180,12 +195,17 @@ export default function QuestionsBrowsePage() {
const [loaded, setLoaded] = useState(false); const [loaded, setLoaded] = useState(false);
const [filterDrawerOpen, setFilterDrawerOpen] = useState(false); const [filterDrawerOpen, setFilterDrawerOpen] = useState(false);
const companyFilterOptions = useMemo(() => { const [selectedCompanyOptions, setSelectedCompanyOptions] = useState<
return COMPANIES.map((company) => ({ Array<FilterOption>
...company, >([]);
checked: selectedCompanies.includes(company.value),
})); const [selectedRoleOptions, setSelectedRoleOptions] = useState<
}, [selectedCompanies]); Array<FilterOption>
>([]);
const [selectedLocationOptions, setSelectedLocationOptions] = useState<
Array<FilterOption>
>([]);
const questionTypeFilterOptions = useMemo(() => { const questionTypeFilterOptions = useMemo(() => {
return QUESTION_TYPES.map((questionType) => ({ return QUESTION_TYPES.map((questionType) => ({
@ -201,20 +221,6 @@ export default function QuestionsBrowsePage() {
})); }));
}, [selectedQuestionAge]); }, [selectedQuestionAge]);
const roleFilterOptions = useMemo(() => {
return ROLES.map((role) => ({
...role,
checked: selectedRoles.includes(role.value),
}));
}, [selectedRoles]);
const locationFilterOptions = useMemo(() => {
return LOCATIONS.map((location) => ({
...location,
checked: selectedLocations.includes(location.value),
}));
}, [selectedLocations]);
const areSearchOptionsInitialized = useMemo(() => { const areSearchOptionsInitialized = useMemo(() => {
return ( return (
areCompaniesInitialized && areCompaniesInitialized &&
@ -287,35 +293,89 @@ export default function QuestionsBrowsePage() {
setSelectedQuestionAge('all'); setSelectedQuestionAge('all');
setSelectedRoles([]); setSelectedRoles([]);
setSelectedLocations([]); setSelectedLocations([]);
setSelectedCompanyOptions([]);
setSelectedRoleOptions([]);
setSelectedLocationOptions([]);
}} }}
/> />
<FilterSection <FilterSection
label="Company" label="Companies"
options={companyFilterOptions} options={selectedCompanyOptions}
renderInput={({ renderInput={({ onOptionChange, field: { ref: _, ...field } }) => (
onOptionChange, <CompanyTypeahead
options,
field: { ref: _, ...field },
}) => (
<Typeahead
{...field} {...field}
clearOnSelect={true}
filterOption={(option) => {
return !selectedCompanyOptions.some((selectedOption) => {
return selectedOption.value === option.value;
});
}}
isLabelHidden={true} isLabelHidden={true}
label="Companies"
options={options}
placeholder="Search companies" placeholder="Search companies"
// eslint-disable-next-line @typescript-eslint/no-empty-function onSelect={(option) => {
onQueryChange={() => {}} onOptionChange({
onSelect={({ value }) => { ...option,
onOptionChange(value, true); checked: true,
});
}} }}
/> />
)} )}
onOptionChange={(optionValue, checked) => { onOptionChange={(option) => {
if (checked) { if (option.checked) {
setSelectedCompanies([...selectedCompanies, optionValue]); setSelectedCompanies([...selectedCompanies, option.label]);
setSelectedCompanyOptions((prevOptions) => [
...prevOptions,
{ ...option, checked: true },
]);
} else { } else {
setSelectedCompanies( setSelectedCompanies(
selectedCompanies.filter((company) => company !== optionValue), selectedCompanies.filter((company) => company !== option.label),
);
setSelectedCompanyOptions((prevOptions) =>
prevOptions.filter(
(prevOption) => prevOption.label !== option.label,
),
);
}
}}
/>
<FilterSection
label="Roles"
options={selectedRoleOptions}
renderInput={({ onOptionChange, field: { ref: _, ...field } }) => (
<RoleTypeahead
{...field}
clearOnSelect={true}
filterOption={(option) => {
return !selectedRoleOptions.some((selectedOption) => {
return selectedOption.value === option.value;
});
}}
isLabelHidden={true}
placeholder="Search roles"
onSelect={(option) => {
onOptionChange({
...option,
checked: true,
});
}}
/>
)}
onOptionChange={(option) => {
if (option.checked) {
setSelectedRoles([...selectedRoles, option.value]);
setSelectedRoleOptions((prevOptions) => [
...prevOptions,
{ ...option, checked: true },
]);
} else {
setSelectedRoles(
selectedCompanies.filter((role) => role !== option.value),
);
setSelectedRoleOptions((prevOptions) =>
prevOptions.filter(
(prevOption) => prevOption.value !== option.value,
),
); );
} }
}} }}
@ -324,13 +384,13 @@ export default function QuestionsBrowsePage() {
label="Question types" label="Question types"
options={questionTypeFilterOptions} options={questionTypeFilterOptions}
showAll={true} showAll={true}
onOptionChange={(optionValue, checked) => { onOptionChange={(option) => {
if (checked) { if (option.checked) {
setSelectedQuestionTypes([...selectedQuestionTypes, optionValue]); setSelectedQuestionTypes([...selectedQuestionTypes, option.value]);
} else { } else {
setSelectedQuestionTypes( setSelectedQuestionTypes(
selectedQuestionTypes.filter( selectedQuestionTypes.filter(
(questionType) => questionType !== optionValue, (questionType) => questionType !== option.value,
), ),
); );
} }
@ -341,68 +401,47 @@ export default function QuestionsBrowsePage() {
label="Question age" label="Question age"
options={questionAgeFilterOptions} options={questionAgeFilterOptions}
showAll={true} showAll={true}
onOptionChange={(optionValue) => { onOptionChange={({ value }) => {
setSelectedQuestionAge(optionValue); setSelectedQuestionAge(value);
}} }}
/> />
<FilterSection <FilterSection
label="Roles" label="Locations"
options={roleFilterOptions} options={selectedLocationOptions}
renderInput={({ renderInput={({ onOptionChange, field: { ref: _, ...field } }) => (
onOptionChange, <LocationTypeahead
options,
field: { ref: _, ...field },
}) => (
<Typeahead
{...field} {...field}
isLabelHidden={true} clearOnSelect={true}
label="Roles" filterOption={(option) => {
options={options} return !selectedLocationOptions.some((selectedOption) => {
placeholder="Search roles" return selectedOption.value === option.value;
// eslint-disable-next-line @typescript-eslint/no-empty-function });
onQueryChange={() => {}}
onSelect={({ value }) => {
onOptionChange(value, true);
}} }}
/>
)}
onOptionChange={(optionValue, checked) => {
if (checked) {
setSelectedRoles([...selectedRoles, optionValue]);
} else {
setSelectedRoles(
selectedRoles.filter((role) => role !== optionValue),
);
}
}}
/>
<FilterSection
label="Location"
options={locationFilterOptions}
renderInput={({
onOptionChange,
options,
field: { ref: _, ...field },
}) => (
<Typeahead
{...field}
isLabelHidden={true} isLabelHidden={true}
label="Locations"
options={options}
placeholder="Search locations" placeholder="Search locations"
// eslint-disable-next-line @typescript-eslint/no-empty-function onSelect={(option) => {
onQueryChange={() => {}} onOptionChange({
onSelect={({ value }) => { ...option,
onOptionChange(value, true); checked: true,
});
}} }}
/> />
)} )}
onOptionChange={(optionValue, checked) => { onOptionChange={(option) => {
if (checked) { if (option.checked) {
setSelectedLocations([...selectedLocations, optionValue]); setSelectedLocations([...selectedLocations, option.value]);
setSelectedLocationOptions((prevOptions) => [
...prevOptions,
{ ...option, checked: true },
]);
} else { } else {
setSelectedLocations( setSelectedLocations(
selectedLocations.filter((location) => location !== optionValue), selectedLocations.filter((role) => role !== option.value),
);
setSelectedLocationOptions((prevOptions) =>
prevOptions.filter(
(prevOption) => prevOption.value !== option.value,
),
); );
} }
}} }}
@ -443,29 +482,50 @@ export default function QuestionsBrowsePage() {
onSortOrderChange={setSortOrder} onSortOrderChange={setSortOrder}
onSortTypeChange={setSortType} onSortTypeChange={setSortType}
/> />
<div className="flex flex-col gap-4 pb-4"> <div className="flex flex-col gap-2 pb-4">
{(questions ?? []).map((question) => ( {(questionsQueryData?.pages ?? []).flatMap(
<QuestionOverviewCard ({ data: questions }) =>
key={question.id} questions.map((question) => (
answerCount={question.numAnswers} <QuestionOverviewCard
companies={{ [question.company]: 1 }} key={question.id}
content={question.content} answerCount={question.numAnswers}
href={`/questions/${question.id}/${createSlug( companies={
question.content, question.aggregatedQuestionEncounters.companyCounts
)}`} }
locations={{ [question.location]: 1 }} content={question.content}
questionId={question.id} href={`/questions/${question.id}/${createSlug(
receivedCount={question.receivedCount} question.content,
roles={{ [question.role]: 1 }} )}`}
timestamp={question.seenAt.toLocaleDateString(undefined, { locations={
month: 'short', question.aggregatedQuestionEncounters.locationCounts
year: 'numeric', }
})} questionId={question.id}
type={question.type} receivedCount={question.receivedCount}
upvoteCount={question.numVotes} roles={
/> question.aggregatedQuestionEncounters.roleCounts
))} }
{questions?.length === 0 && ( timestamp={question.seenAt.toLocaleDateString(
undefined,
{
month: 'short',
year: 'numeric',
},
)}
type={question.type}
upvoteCount={question.numVotes}
/>
)),
)}
<Button
disabled={!hasNextPage || isFetchingNextPage}
isLoading={isFetchingNextPage}
label={hasNextPage ? 'Load more' : 'Nothing more to load'}
variant="tertiary"
onClick={() => {
fetchNextPage();
}}
/>
{questionCount === 0 && (
<div className="flex w-full items-center justify-center gap-2 rounded-md border border-slate-300 bg-slate-200 p-4 text-slate-600"> <div className="flex w-full items-center justify-center gap-2 rounded-md border border-slate-300 bg-slate-200 p-4 text-slate-600">
<NoSymbolIcon className="h-6 w-6" /> <NoSymbolIcon className="h-6 w-6" />
<p>Nothing found.</p> <p>Nothing found.</p>

@ -11,14 +11,16 @@ export const questionsQuestionRouter = createProtectedRouter()
.query('getQuestionsByFilter', { .query('getQuestionsByFilter', {
input: z.object({ input: z.object({
companyNames: z.string().array(), companyNames: z.string().array(),
cursor: z.object({ cursor: z
idCursor: z.string().optional(), .object({
lastSeenCursor: z.date().optional(), idCursor: z.string().optional(),
upvoteCursor: z.string().optional(), lastSeenCursor: z.date().optional(),
}).nullish(), upvoteCursor: z.number().optional(),
})
.nullish(),
endDate: z.date().default(new Date()), endDate: z.date().default(new Date()),
limit: z.number().min(1).default(50),
locations: z.string().array(), locations: z.string().array(),
pageSize: z.number().default(50),
questionTypes: z.nativeEnum(QuestionsQuestionType).array(), questionTypes: z.nativeEnum(QuestionsQuestionType).array(),
roles: z.string().array(), roles: z.string().array(),
sortOrder: z.nativeEnum(SortOrder), sortOrder: z.nativeEnum(SortOrder),
@ -26,44 +28,47 @@ export const questionsQuestionRouter = createProtectedRouter()
startDate: z.date().optional(), startDate: z.date().optional(),
}), }),
async resolve({ ctx, input }) { async resolve({ ctx, input }) {
const { cursor } = input const { cursor } = input;
const sortCondition = const sortCondition =
input.sortType === SortType.TOP input.sortType === SortType.TOP
? [ ? [
{ {
upvotes: input.sortOrder upvotes: input.sortOrder,
}, },
{ {
id: input.sortOrder id: input.sortOrder,
} },
] ]
: [ : [
{ {
lastSeenAt: input.sortOrder, lastSeenAt: input.sortOrder,
}, },
{ {
id: input.sortOrder id: input.sortOrder,
} },
]; ];
const cursorCondition = const cursorCondition =
input.sortType === SortType.TOP input.sortType === SortType.TOP
? { ? {
id: cursor ? cursor!.idCursor : undefined, id: cursor ? cursor!.idCursor : undefined,
upvotes: cursor ? cursor!.upvoteCursor : undefined, // Upvotes: cursor ? cursor!.upvoteCursor : undefined,
} }
: { : {
id: cursor ? cursor!.idCursor : undefined, id: cursor ? cursor!.idCursor : undefined,
lastSeenAt: cursor ? cursor!.lastSeenCursor : undefined, // LastSeenAt: cursor ? cursor!.lastSeenCursor : undefined,
}; };
const toSkip = cursor ? 1 : 0; const toSkip = cursor ? 1 : 0;
const questionsData = await ctx.prisma.questionsQuestion.findMany({ const questionsData = await ctx.prisma.questionsQuestion.findMany({
cursor: { cursor:
...cursorCondition, cursor !== undefined
}, ? {
...cursorCondition,
}
: undefined,
include: { include: {
_count: { _count: {
select: { select: {
@ -88,7 +93,7 @@ export const questionsQuestionRouter = createProtectedRouter()
}, },
orderBy: sortCondition, orderBy: sortCondition,
skip: toSkip, skip: toSkip,
take: input.pageSize, take: input.limit + 1,
where: { where: {
...(input.questionTypes.length > 0 ...(input.questionTypes.length > 0
? { ? {
@ -131,11 +136,6 @@ export const questionsQuestionRouter = createProtectedRouter()
}, },
}); });
const lastQuestion = questionsData[input.pageSize - 1];
const nextIdCursor: string | undefined = lastQuestion.id;
const nextLastSeenCursor = input.sortType === SortType.NEW ? lastQuestion.lastSeenAt : undefined;
const nextupvoteCursor = input.sortType === SortType.TOP ? lastQuestion.upvotes : undefined;
const processedQuestionsData = questionsData.map((data) => { const processedQuestionsData = questionsData.map((data) => {
const votes: number = data.votes.reduce( const votes: number = data.votes.reduce(
(previousValue: number, currentValue) => { (previousValue: number, currentValue) => {
@ -156,32 +156,32 @@ export const questionsQuestionRouter = createProtectedRouter()
const companyCounts: Record<string, number> = {}; const companyCounts: Record<string, number> = {};
const locationCounts: Record<string, number> = {}; const locationCounts: Record<string, number> = {};
const roleCounts:Record<string, number> = {}; const roleCounts: Record<string, number> = {};
let latestSeenAt = data.encounters[0].seenAt; let latestSeenAt = data.encounters[0].seenAt;
for (let i = 0; i < data.encounters.length; i++) { for (let i = 0; i < data.encounters.length; i++) {
const encounter = data.encounters[i]; const encounter = data.encounters[i];
latestSeenAt = latestSeenAt < encounter.seenAt ? encounter.seenAt : latestSeenAt; latestSeenAt =
latestSeenAt < encounter.seenAt ? encounter.seenAt : latestSeenAt;
if (!(encounter.company!.name in companyCounts)) { if (!(encounter.company!.name in companyCounts)) {
companyCounts[encounter.company!.name] = 1; companyCounts[encounter.company!.name] = 1;
} }
companyCounts[encounter.company!.name] += 1; companyCounts[encounter.company!.name] += 1;
if (!(encounter.location in locationCounts)) { if (!(encounter.location in locationCounts)) {
locationCounts[encounter.location] = 1; locationCounts[encounter.location] = 1;
} }
locationCounts[encounter.location] += 1; locationCounts[encounter.location] += 1;
if (!(encounter.role in roleCounts)) { if (!(encounter.role in roleCounts)) {
roleCounts[encounter.role] = 1; roleCounts[encounter.role] = 1;
} }
roleCounts[encounter.role] += 1; roleCounts[encounter.role] += 1;
} }
const question: Question = { const question: Question = {
aggregatedQuestionEncounters: { aggregatedQuestionEncounters: {
companyCounts, companyCounts,
@ -205,16 +205,27 @@ export const questionsQuestionRouter = createProtectedRouter()
let nextCursor: typeof cursor | undefined = undefined; let nextCursor: typeof cursor | undefined = undefined;
nextCursor = { if (questionsData.length > input.limit) {
idCursor: nextIdCursor, const nextItem = questionsData.pop()!;
lastSeenCursor: nextLastSeenCursor, processedQuestionsData.pop();
upvoteCursor: nextupvoteCursor,
const nextIdCursor: string | undefined = nextItem.id;
const nextLastSeenCursor =
input.sortType === SortType.NEW ? nextItem.lastSeenAt : undefined;
const nextUpvoteCursor =
input.sortType === SortType.TOP ? nextItem.upvotes : undefined;
nextCursor = {
idCursor: nextIdCursor,
lastSeenCursor: nextLastSeenCursor,
upvoteCursor: nextUpvoteCursor,
};
} }
return { return {
data: processedQuestionsData,
nextCursor, nextCursor,
processedQuestionsData };
}
}, },
}) })
.query('getQuestionById', { .query('getQuestionById', {
@ -274,37 +285,38 @@ export const questionsQuestionRouter = createProtectedRouter()
const companyCounts: Record<string, number> = {}; const companyCounts: Record<string, number> = {};
const locationCounts: Record<string, number> = {}; const locationCounts: Record<string, number> = {};
const roleCounts:Record<string, number> = {}; const roleCounts: Record<string, number> = {};
let latestSeenAt = questionData.encounters[0].seenAt; let latestSeenAt = questionData.encounters[0].seenAt;
for (let i = 0; i < questionData.encounters.length; i++) { for (let i = 0; i < questionData.encounters.length; i++) {
const encounter = questionData.encounters[i]; const encounter = questionData.encounters[i];
latestSeenAt = latestSeenAt < encounter.seenAt ? encounter.seenAt : latestSeenAt; latestSeenAt =
latestSeenAt < encounter.seenAt ? encounter.seenAt : latestSeenAt;
if (!(encounter.company!.name in companyCounts)) { if (!(encounter.company!.name in companyCounts)) {
companyCounts[encounter.company!.name] = 1; companyCounts[encounter.company!.name] = 1;
} }
companyCounts[encounter.company!.name] += 1; companyCounts[encounter.company!.name] += 1;
if (!(encounter.location in locationCounts)) { if (!(encounter.location in locationCounts)) {
locationCounts[encounter.location] = 1; locationCounts[encounter.location] = 1;
} }
locationCounts[encounter.location] += 1; locationCounts[encounter.location] += 1;
if (!(encounter.role in roleCounts)) { if (!(encounter.role in roleCounts)) {
roleCounts[encounter.role] = 1; roleCounts[encounter.role] = 1;
} }
roleCounts[encounter.role] += 1; roleCounts[encounter.role] += 1;
} }
const question: Question = { const question: Question = {
aggregatedQuestionEncounters: { aggregatedQuestionEncounters: {
companyCounts, companyCounts,
latestSeenAt, latestSeenAt,
locationCounts, locationCounts,
roleCounts, roleCounts,
}, },
content: questionData.content, content: questionData.content,
id: questionData.id, id: questionData.id,

@ -2,7 +2,6 @@ import type { QuestionsQuestionType } from '@prisma/client';
export type Question = { export type Question = {
aggregatedQuestionEncounters: AggregatedQuestionEncounter; aggregatedQuestionEncounters: AggregatedQuestionEncounter;
// TODO: company, location, role maps
content: string; content: string;
id: string; id: string;
numAnswers: number; numAnswers: number;

Loading…
Cancel
Save