]> Untitled Git - lemmy-ui.git/blobdiff - src/shared/components/private_message/create-private-message.tsx
Use http client (#1081)
[lemmy-ui.git] / src / shared / components / private_message / create-private-message.tsx
index 9cbe47a9f737d723825167036e2b9554f264726f..817cfd880d001181958b56edce97c340af245040 100644 (file)
@@ -1,26 +1,19 @@
-import { None, Option, Some } from "@sniptt/monads";
 import { Component } from "inferno";
 import {
+  CreatePrivateMessage as CreatePrivateMessageI,
   GetPersonDetails,
   GetPersonDetailsResponse,
   GetSiteResponse,
-  SortType,
-  UserOperation,
-  wsJsonToRes,
-  wsUserOp,
 } from "lemmy-js-client";
-import { Subscription } from "rxjs";
 import { i18n } from "../../i18next";
 import { InitialFetchRequest } from "../../interfaces";
-import { UserService, WebSocketService } from "../../services";
+import { FirstLoadService } from "../../services/FirstLoadService";
+import { HttpService, RequestState } from "../../services/HttpService";
 import {
-  auth,
   getRecipientIdFromProps,
-  isBrowser,
+  myAuth,
   setIsoData,
   toast,
-  wsClient,
-  wsSubscribe,
 } from "../../utils";
 import { HtmlTags } from "../common/html-tags";
 import { Spinner } from "../common/icon";
@@ -28,149 +21,126 @@ import { PrivateMessageForm } from "./private-message-form";
 
 interface CreatePrivateMessageState {
   siteRes: GetSiteResponse;
-  recipientDetailsRes: Option<GetPersonDetailsResponse>;
-  recipient_id: number;
-  loading: boolean;
+  recipientRes: RequestState<GetPersonDetailsResponse>;
+  recipientId: number;
+  isIsomorphic: boolean;
 }
 
 export class CreatePrivateMessage extends Component<
   any,
   CreatePrivateMessageState
 > {
-  private isoData = setIsoData(this.context, GetPersonDetailsResponse);
-  private subscription: Subscription;
-  private emptyState: CreatePrivateMessageState = {
+  private isoData = setIsoData(this.context);
+  state: CreatePrivateMessageState = {
     siteRes: this.isoData.site_res,
-    recipientDetailsRes: None,
-    recipient_id: getRecipientIdFromProps(this.props),
-    loading: true,
+    recipientRes: { state: "empty" },
+    recipientId: getRecipientIdFromProps(this.props),
+    isIsomorphic: false,
   };
 
   constructor(props: any, context: any) {
     super(props, context);
-    this.state = this.emptyState;
     this.handlePrivateMessageCreate =
       this.handlePrivateMessageCreate.bind(this);
 
-    this.parseMessage = this.parseMessage.bind(this);
-    this.subscription = wsSubscribe(this.parseMessage);
-
-    if (UserService.Instance.myUserInfo.isNone() && isBrowser()) {
-      toast(i18n.t("not_logged_in"), "danger");
-      this.context.router.history.push(`/login`);
-    }
-
     // Only fetch the data if coming from another route
-    if (this.isoData.path == this.context.router.route.match.url) {
+    if (FirstLoadService.isFirstLoad) {
       this.state = {
         ...this.state,
-        recipientDetailsRes: Some(
-          this.isoData.routeData[0] as GetPersonDetailsResponse
-        ),
-        loading: false,
+        recipientRes: this.isoData.routeData[0],
+        isIsomorphic: true,
       };
-    } else {
-      this.fetchPersonDetails();
     }
   }
 
-  fetchPersonDetails() {
-    let form = new GetPersonDetails({
-      person_id: Some(this.state.recipient_id),
-      sort: Some(SortType.New),
-      saved_only: Some(false),
-      username: None,
-      page: None,
-      limit: None,
-      community_id: None,
-      auth: auth(false).ok(),
+  async componentDidMount() {
+    if (!this.state.isIsomorphic) {
+      await this.fetchPersonDetails();
+    }
+  }
+
+  async fetchPersonDetails() {
+    this.setState({
+      recipientRes: { state: "loading" },
+    });
+
+    this.setState({
+      recipientRes: await HttpService.client.getPersonDetails({
+        person_id: this.state.recipientId,
+        sort: "New",
+        saved_only: false,
+        auth: myAuth(),
+      }),
     });
-    WebSocketService.Instance.send(wsClient.getPersonDetails(form));
   }
 
-  static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
-    let person_id = Some(Number(req.path.split("/").pop()));
-    let form = new GetPersonDetails({
+  static fetchInitialData(
+    req: InitialFetchRequest
+  ): Promise<RequestState<any>>[] {
+    const person_id = Number(req.path.split("/").pop());
+    const form: GetPersonDetails = {
       person_id,
-      sort: Some(SortType.New),
-      saved_only: Some(false),
-      username: None,
-      page: None,
-      limit: None,
-      community_id: None,
+      sort: "New",
+      saved_only: false,
       auth: req.auth,
-    });
+    };
     return [req.client.getPersonDetails(form)];
   }
 
   get documentTitle(): string {
-    return this.state.recipientDetailsRes.match({
-      some: res =>
-        `${i18n.t("create_private_message")} - ${res.person_view.person.name}`,
-      none: "",
-    });
+    if (this.state.recipientRes.state == "success") {
+      const name_ = this.state.recipientRes.data.person_view.person.name;
+      return `${i18n.t("create_private_message")} - ${name_}`;
+    } else {
+      return "";
+    }
   }
 
-  componentWillUnmount() {
-    if (isBrowser()) {
-      this.subscription.unsubscribe();
+  renderRecipientRes() {
+    switch (this.state.recipientRes.state) {
+      case "loading":
+        return (
+          <h5>
+            <Spinner large />
+          </h5>
+        );
+      case "success": {
+        const res = this.state.recipientRes.data;
+        return (
+          <div className="row">
+            <div className="col-12 col-lg-6 offset-lg-3 mb-4">
+              <h5>{i18n.t("create_private_message")}</h5>
+              <PrivateMessageForm
+                onCreate={this.handlePrivateMessageCreate}
+                recipient={res.person_view.person}
+              />
+            </div>
+          </div>
+        );
+      }
     }
   }
 
   render() {
     return (
-      <div className="container">
+      <div className="container-lg">
         <HtmlTags
           title={this.documentTitle}
           path={this.context.router.route.match.url}
-          description={None}
-          image={None}
         />
-        {this.state.loading ? (
-          <h5>
-            <Spinner large />
-          </h5>
-        ) : (
-          this.state.recipientDetailsRes.match({
-            some: res => (
-              <div className="row">
-                <div className="col-12 col-lg-6 offset-lg-3 mb-4">
-                  <h5>{i18n.t("create_private_message")}</h5>
-                  <PrivateMessageForm
-                    privateMessageView={None}
-                    onCreate={this.handlePrivateMessageCreate}
-                    recipient={res.person_view.person}
-                  />
-                </div>
-              </div>
-            ),
-            none: <></>,
-          })
-        )}
+        {this.renderRecipientRes()}
       </div>
     );
   }
 
-  handlePrivateMessageCreate() {
-    toast(i18n.t("message_sent"));
+  async handlePrivateMessageCreate(form: CreatePrivateMessageI) {
+    const res = await HttpService.client.createPrivateMessage(form);
 
-    // Navigate to the front
-    this.context.router.history.push("/");
-  }
+    if (res.state == "success") {
+      toast(i18n.t("message_sent"));
 
-  parseMessage(msg: any) {
-    let op = wsUserOp(msg);
-    console.log(msg);
-    if (msg.error) {
-      toast(i18n.t(msg.error), "danger");
-      this.setState({ loading: false });
-      return;
-    } else if (op == UserOperation.GetPersonDetails) {
-      let data = wsJsonToRes<GetPersonDetailsResponse>(
-        msg,
-        GetPersonDetailsResponse
-      );
-      this.setState({ recipientDetailsRes: Some(data), loading: false });
+      // Navigate to the front
+      this.context.router.history.push("/");
     }
   }
 }