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

Route data refactor #1043

Merged
merged 11 commits into from
Jun 17, 2023
13 changes: 10 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,16 @@
"themes:watch": "sass --watch src/assets/css/themes/:src/assets/css/themes"
},
"lint-staged": {
"*.{ts,tsx,js}": ["prettier --write", "eslint --fix"],
"*.{css, scss}": ["prettier --write"],
"package.json": ["sortpack"]
"*.{ts,tsx,js}": [
"prettier --write",
"eslint --fix"
],
"*.{css, scss}": [
"prettier --write"
],
"package.json": [
"sortpack"
]
},
"dependencies": {
"@babel/plugin-proposal-decorators": "^7.21.0",
Expand Down
28 changes: 13 additions & 15 deletions src/server/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ import {
ILemmyConfig,
InitialFetchRequest,
IsoDataOptionalSite,
RouteData,
} from "../shared/interfaces";
import { routes } from "../shared/routes";
import { RequestState, wrapClient } from "../shared/services/HttpService";
import { FailedRequestState, wrapClient } from "../shared/services/HttpService";
import {
ErrorPageData,
favIconPngUrl,
Expand Down Expand Up @@ -136,7 +137,7 @@ server.get("/*", async (req, res) => {
// This bypasses errors, so that the client can hit the error on its own,
// in order to remove the jwt on the browser. Necessary for wrong jwts
let site: GetSiteResponse | undefined = undefined;
const routeData: RequestState<any>[] = [];
let routeData: RouteData = {};
let errorPageData: ErrorPageData | undefined = undefined;
let try_site = await client.getSite(getSiteForm);
if (try_site.state === "failed" && try_site.msg == "not_logged_in") {
Expand All @@ -160,7 +161,7 @@ server.get("/*", async (req, res) => {
return res.redirect("/setup");
}

if (site) {
if (site && activeRoute?.fetchInitialData) {
const initialFetchReq: InitialFetchRequest = {
client,
auth,
Expand All @@ -169,26 +170,23 @@ server.get("/*", async (req, res) => {
site,
};

if (activeRoute?.fetchInitialData) {
routeData.push(
...(await Promise.all([
...activeRoute.fetchInitialData(initialFetchReq),
]))
);
}
routeData = await activeRoute.fetchInitialData(initialFetchReq);
}
} else if (try_site.state === "failed") {
errorPageData = getErrorPageData(new Error(try_site.msg), site);
}

const error = Object.values(routeData).find(
res => res.state === "failed"
) as FailedRequestState | undefined;
SleeplessOne1917 marked this conversation as resolved.
Show resolved Hide resolved

// Redirect to the 404 if there's an API error
if (routeData[0] && routeData[0].state === "failed") {
const error = routeData[0].msg;
console.error(error);
if (error === "instance_is_private") {
if (error) {
console.error(error.msg);
if (error.msg === "instance_is_private") {
return res.redirect(`/signup`);
} else {
errorPageData = getErrorPageData(new Error(error), site);
errorPageData = getErrorPageData(new Error(error.msg), site);
}
}

Expand Down
25 changes: 18 additions & 7 deletions src/shared/components/community/communities.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService";
import {
QueryParams,
RouteDataResponse,
editCommunity,
getPageFromString,
getQueryParams,
Expand All @@ -30,6 +31,10 @@ import { CommunityLink } from "./community-link";

const communityLimit = 50;

type CommunitiesData = RouteDataResponse<{
listCommunitiesResponse: ListCommunitiesResponse;
}>;

interface CommunitiesState {
listCommunitiesResponse: RequestState<ListCommunitiesResponse>;
siteRes: GetSiteResponse;
Expand All @@ -47,7 +52,7 @@ function getListingTypeFromQuery(listingType?: string): ListingType {
}

export class Communities extends Component<any, CommunitiesState> {
private isoData = setIsoData(this.context);
private isoData = setIsoData<CommunitiesData>(this.context);
state: CommunitiesState = {
listCommunitiesResponse: { state: "empty" },
siteRes: this.isoData.site_res,
Expand All @@ -62,9 +67,11 @@ export class Communities extends Component<any, CommunitiesState> {

// Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) {
const { listCommunitiesResponse } = this.isoData.routeData;

this.state = {
...this.state,
listCommunitiesResponse: this.isoData.routeData[0],
listCommunitiesResponse,
isIsomorphic: true,
};
}
Expand Down Expand Up @@ -274,13 +281,13 @@ export class Communities extends Component<any, CommunitiesState> {
i.context.router.history.push(`/search?q=${searchParamEncoded}`);
}

static fetchInitialData({
static async fetchInitialData({
query: { listingType, page },
client,
auth,
}: InitialFetchRequest<QueryParams<CommunitiesProps>>): Promise<
RequestState<any>
>[] {
}: InitialFetchRequest<
QueryParams<CommunitiesProps>
>): Promise<CommunitiesData> {
const listCommunitiesForm: ListCommunities = {
type_: getListingTypeFromQuery(listingType),
sort: "TopMonth",
Expand All @@ -289,7 +296,11 @@ export class Communities extends Component<any, CommunitiesState> {
auth: auth,
};

return [client.listCommunities(listCommunitiesForm)];
return {
listCommunitiesResponse: await client.listCommunities(
listCommunitiesForm
),
};
}

getCommunitiesQueryParams() {
Expand Down
43 changes: 29 additions & 14 deletions src/shared/components/community/community.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import { FirstLoadService } from "../../services/FirstLoadService";
import { HttpService, RequestState } from "../../services/HttpService";
import {
QueryParams,
RouteDataResponse,
commentsToFlatNodes,
communityRSSUrl,
editComment,
Expand Down Expand Up @@ -100,6 +101,12 @@ import { SiteSidebar } from "../home/site-sidebar";
import { PostListings } from "../post/post-listings";
import { CommunityLink } from "./community-link";

type CommunityData = RouteDataResponse<{
communityRes: GetCommunityResponse;
postsRes: GetPostsResponse;
commentsRes: GetCommentsResponse;
}>;

interface State {
communityRes: RequestState<GetCommunityResponse>;
postsRes: RequestState<GetPostsResponse>;
Expand Down Expand Up @@ -140,7 +147,7 @@ export class Community extends Component<
RouteComponentProps<{ name: string }>,
State
> {
private isoData = setIsoData(this.context);
private isoData = setIsoData<CommunityData>(this.context);
state: State = {
communityRes: { state: "empty" },
postsRes: { state: "empty" },
Expand Down Expand Up @@ -194,13 +201,14 @@ export class Community extends Component<

// Only fetch the data if coming from another route
if (FirstLoadService.isFirstLoad) {
const [communityRes, postsRes, commentsRes] = this.isoData.routeData;
const { communityRes, commentsRes, postsRes } = this.isoData.routeData;

this.state = {
...this.state,
isIsomorphic: true,
commentsRes,
communityRes,
postsRes,
commentsRes,
isIsomorphic: true,
};
}
}
Expand All @@ -227,30 +235,33 @@ export class Community extends Component<
saveScrollPosition(this.context);
}

static fetchInitialData({
static async fetchInitialData({
client,
path,
query: { dataType: urlDataType, page: urlPage, sort: urlSort },
auth,
}: InitialFetchRequest<QueryParams<CommunityProps>>): Promise<
RequestState<any>
>[] {
Promise<CommunityData>
> {
const pathSplit = path.split("/");
const promises: Promise<RequestState<any>>[] = [];

const communityName = pathSplit[2];
const communityForm: GetCommunity = {
name: communityName,
auth,
};
promises.push(client.getCommunity(communityForm));

const dataType = getDataTypeFromQuery(urlDataType);

const sort = getSortTypeFromQuery(urlSort);

const page = getPageFromString(urlPage);

let postsResponse: RequestState<GetPostsResponse> = { state: "empty" };
let commentsResponse: RequestState<GetCommentsResponse> = {
state: "empty",
};

if (dataType === DataType.Post) {
const getPostsForm: GetPosts = {
community_name: communityName,
Expand All @@ -261,8 +272,8 @@ export class Community extends Component<
saved_only: false,
auth,
};
promises.push(client.getPosts(getPostsForm));
promises.push(Promise.resolve({ state: "empty" }));

postsResponse = await client.getPosts(getPostsForm);
} else {
const getCommentsForm: GetComments = {
community_name: communityName,
Expand All @@ -273,11 +284,15 @@ export class Community extends Component<
saved_only: false,
auth,
};
promises.push(Promise.resolve({ state: "empty" }));
promises.push(client.getComments(getCommentsForm));

commentsResponse = await client.getComments(getCommentsForm);
}

return promises;
return {
communityRes: await client.getCommunity(communityForm),
commentsRes: commentsResponse,
postsRes: postsResponse,
};
}

get documentTitle(): string {
Expand Down
Loading