From: Dessalines Date: Tue, 26 Mar 2019 18:00:18 +0000 (-0700) Subject: Adding a few endpoints. X-Git-Url: http://these/git/%22https:/image.com/readmes/%7B%60%24%7BarchiveUrl%7D/%7Bthis.getImage%28%29%7D?a=commitdiff_plain;h=25dcb8f4f4f80e401d1d3154923e2dcd05664c76;p=lemmy.git Adding a few endpoints. - Adding CreatePost, CreateComment, CreateCommunity --- diff --git a/server/migrations/2019-03-03-163336_create_post/up.sql b/server/migrations/2019-03-03-163336_create_post/up.sql index a617ea33..f22192f3 100644 --- a/server/migrations/2019-03-03-163336_create_post/up.sql +++ b/server/migrations/2019-03-03-163336_create_post/up.sql @@ -1,8 +1,10 @@ create table post ( id serial primary key, name varchar(100) not null, - url text not null, + url text, -- These are both optional, a post can just have a title + body text, attributed_to text not null, + community_id int references community on update cascade on delete cascade not null, published timestamp not null default now(), updated timestamp ); diff --git a/server/src/actions/comment.rs b/server/src/actions/comment.rs index 98d5322c..ceedf294 100644 --- a/server/src/actions/comment.rs +++ b/server/src/actions/comment.rs @@ -2,7 +2,9 @@ extern crate diesel; use schema::{comment, comment_like}; use diesel::*; use diesel::result::Error; +use serde::{Deserialize, Serialize}; use {Crud, Likeable}; +use actions::post::Post; // WITH RECURSIVE MyTree AS ( // SELECT * FROM comment WHERE parent_id IS NULL @@ -11,7 +13,8 @@ use {Crud, Likeable}; // ) // SELECT * FROM MyTree; -#[derive(Queryable, Identifiable, PartialEq, Debug)] +#[derive(Queryable, Associations, Identifiable, PartialEq, Debug, Serialize, Deserialize)] +#[belongs_to(Post)] #[table_name="comment"] pub struct Comment { pub id: i32, @@ -96,20 +99,38 @@ impl Likeable for CommentLike { } } +impl Comment { + pub fn from_post(conn: &PgConnection, post: &Post) -> Result, Error> { + use schema::community::dsl::*; + Comment::belonging_to(post) + .load::(conn) + } +} + #[cfg(test)] mod tests { use establish_connection; use super::*; use actions::post::*; + use actions::community::*; use Crud; #[test] fn test_crud() { let conn = establish_connection(); + + let new_community = CommunityForm { + name: "test community".to_string(), + updated: None + }; + + let inserted_community = Community::create(&conn, &new_community).unwrap(); let new_post = PostForm { name: "A test post".into(), - url: "https://test.com".into(), + url: None, + body: None, attributed_to: "test_user.com".into(), + community_id: inserted_community.id, updated: None }; @@ -167,6 +188,7 @@ mod tests { let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap(); Comment::delete(&conn, inserted_child_comment.id).unwrap(); Post::delete(&conn, inserted_post.id).unwrap(); + Community::delete(&conn, inserted_community.id).unwrap(); assert_eq!(expected_comment, read_comment); assert_eq!(expected_comment, inserted_comment); diff --git a/server/src/actions/community.rs b/server/src/actions/community.rs index 44d7b749..97600620 100644 --- a/server/src/actions/community.rs +++ b/server/src/actions/community.rs @@ -117,6 +117,13 @@ impl Joinable for CommunityUser { } } +impl Community { + pub fn list_all(conn: &PgConnection) -> Result, Error> { + use schema::community::dsl::*; + community.load::(conn) + } +} + #[cfg(test)] mod tests { use establish_connection; @@ -183,6 +190,7 @@ mod tests { let updated_community = Community::update(&conn, inserted_community.id, &new_community).unwrap(); let ignored_community = CommunityFollower::ignore(&conn, &community_follower_form).unwrap(); let left_community = CommunityUser::leave(&conn, &community_user_form).unwrap(); + let loaded_count = Community::list_all(&conn).unwrap().len(); let num_deleted = Community::delete(&conn, inserted_community.id).unwrap(); User_::delete(&conn, inserted_user.id).unwrap(); @@ -193,6 +201,7 @@ mod tests { assert_eq!(expected_community_user, inserted_community_user); assert_eq!(1, ignored_community); assert_eq!(1, left_community); + assert_eq!(1, loaded_count); assert_eq!(1, num_deleted); } diff --git a/server/src/actions/post.rs b/server/src/actions/post.rs index 889fcf03..71846dff 100644 --- a/server/src/actions/post.rs +++ b/server/src/actions/post.rs @@ -2,15 +2,18 @@ extern crate diesel; use schema::{post, post_like}; use diesel::*; use diesel::result::Error; +use serde::{Deserialize, Serialize}; use {Crud, Likeable}; -#[derive(Queryable, Identifiable, PartialEq, Debug)] +#[derive(Queryable, Identifiable, PartialEq, Debug, Serialize, Deserialize)] #[table_name="post"] pub struct Post { pub id: i32, pub name: String, - pub url: String, + pub url: Option, + pub body: Option, pub attributed_to: String, + pub community_id: i32, pub published: chrono::NaiveDateTime, pub updated: Option } @@ -19,8 +22,10 @@ pub struct Post { #[table_name="post"] pub struct PostForm { pub name: String, - pub url: String, + pub url: Option, + pub body: Option, pub attributed_to: String, + pub community_id: i32, pub updated: Option } @@ -92,14 +97,24 @@ mod tests { use establish_connection; use super::*; use Crud; + use actions::community::*; #[test] fn test_crud() { let conn = establish_connection(); + + let new_community = CommunityForm { + name: "test community_2".to_string(), + updated: None + }; + + let inserted_community = Community::create(&conn, &new_community).unwrap(); let new_post = PostForm { name: "A test post".into(), - url: "https://test.com".into(), + url: None, + body: None, attributed_to: "test_user.com".into(), + community_id: inserted_community.id, updated: None }; @@ -108,8 +123,10 @@ mod tests { let expected_post = Post { id: inserted_post.id, name: "A test post".into(), - url: "https://test.com".into(), + url: None, + body: None, attributed_to: "test_user.com".into(), + community_id: inserted_community.id, published: inserted_post.published, updated: None }; @@ -134,6 +151,7 @@ mod tests { let updated_post = Post::update(&conn, inserted_post.id, &new_post).unwrap(); let like_removed = PostLike::remove(&conn, &post_like_form).unwrap(); let num_deleted = Post::delete(&conn, inserted_post.id).unwrap(); + Community::delete(&conn, inserted_community.id).unwrap(); assert_eq!(expected_post, read_post); assert_eq!(expected_post, inserted_post); diff --git a/server/src/schema.rs b/server/src/schema.rs index 4ab54bc4..28c4e8ca 100644 --- a/server/src/schema.rs +++ b/server/src/schema.rs @@ -51,8 +51,10 @@ table! { post (id) { id -> Int4, name -> Varchar, - url -> Text, + url -> Nullable, + body -> Nullable, attributed_to -> Text, + community_id -> Int4, published -> Timestamp, updated -> Nullable, } @@ -85,6 +87,7 @@ joinable!(comment -> post (post_id)); joinable!(comment_like -> comment (comment_id)); joinable!(community_follower -> community (community_id)); joinable!(community_user -> community (community_id)); +joinable!(post -> community (community_id)); joinable!(post_like -> post (post_id)); allow_tables_to_appear_in_same_query!( diff --git a/server/src/websocket_server/server.rs b/server/src/websocket_server/server.rs index 760bd78c..22484397 100644 --- a/server/src/websocket_server/server.rs +++ b/server/src/websocket_server/server.rs @@ -13,10 +13,13 @@ use std::str::FromStr; use {Crud, Joinable, establish_connection}; use actions::community::*; use actions::user::*; +use actions::post::*; +use actions::comment::*; + #[derive(EnumString,ToString,Debug)] pub enum UserOperation { - Login, Register, Logout, CreateCommunity, Join, Edit, Reply, Vote, Delete, NextPage, Sticky + Login, Register, Logout, CreateCommunity, ListCommunities, CreatePost, GetPost, GetCommunity, CreateComment, Join, Edit, Reply, Vote, Delete, NextPage, Sticky } @@ -73,12 +76,6 @@ impl actix::Message for StandardMessage { type Result = String; } -#[derive(Serialize, Deserialize)] -pub struct StandardResponse { - op: String, - response: T -} - /// List of available rooms pub struct ListRooms; @@ -118,12 +115,75 @@ pub struct LoginResponse { #[derive(Serialize, Deserialize)] pub struct CreateCommunity { name: String, + auth: String } #[derive(Serialize, Deserialize)] pub struct CreateCommunityResponse { op: String, - data: Community + community: Community +} + +#[derive(Serialize, Deserialize)] +pub struct ListCommunities; + +#[derive(Serialize, Deserialize)] +pub struct ListCommunitiesResponse { + op: String, + communities: Vec +} + +#[derive(Serialize, Deserialize)] +pub struct CreatePost { + name: String, + url: Option, + body: Option, + community_id: i32, + auth: String +} + +#[derive(Serialize, Deserialize)] +pub struct CreatePostResponse { + op: String, + post: Post +} + + +#[derive(Serialize, Deserialize)] +pub struct GetPost { + id: i32 +} + +#[derive(Serialize, Deserialize)] +pub struct GetPostResponse { + op: String, + post: Post, + comments: Vec +} + +#[derive(Serialize, Deserialize)] +pub struct GetCommunity { + id: i32 +} + +#[derive(Serialize, Deserialize)] +pub struct GetCommunityResponse { + op: String, + community: Community +} + +#[derive(Serialize, Deserialize)] +pub struct CreateComment { + content: String, + parent_id: Option, + post_id: i32, + auth: String +} + +#[derive(Serialize, Deserialize)] +pub struct CreateCommentResponse { + op: String, + comment: Comment } /// `ChatServer` manages chat rooms and responsible for coordinating chat @@ -249,7 +309,6 @@ impl Handler for ChatServer { let data: &Value = &json["data"]; let op = &json["op"].as_str().unwrap(); - let auth = &json["auth"].as_str(); let user_operation: UserOperation = UserOperation::from_str(&op).unwrap(); let res: String = match user_operation { @@ -263,18 +322,27 @@ impl Handler for ChatServer { }, UserOperation::CreateCommunity => { let create_community: CreateCommunity = serde_json::from_str(&data.to_string()).unwrap(); - match auth { - Some(auth) => { - create_community.perform(auth) - }, - None => serde_json::to_string( - &ErrorMessage { - op: UserOperation::CreateCommunity.to_string(), - error: "Not logged in.".to_string() - } - ) - .unwrap() - } + create_community.perform() + }, + UserOperation::ListCommunities => { + let list_communities: ListCommunities = ListCommunities; + list_communities.perform() + }, + UserOperation::CreatePost => { + let create_post: CreatePost = serde_json::from_str(&data.to_string()).unwrap(); + create_post.perform() + }, + UserOperation::GetPost => { + let get_post: GetPost = serde_json::from_str(&data.to_string()).unwrap(); + get_post.perform() + }, + UserOperation::GetCommunity => { + let get_community: GetCommunity = serde_json::from_str(&data.to_string()).unwrap(); + get_community.perform() + }, + UserOperation::CreateComment => { + let create_comment: CreateComment = serde_json::from_str(&data.to_string()).unwrap(); + create_comment.perform() }, _ => { let e = ErrorMessage { @@ -286,68 +354,29 @@ impl Handler for ChatServer { // _ => "no".to_string() }; - - - // let data: &Value = &json["data"]; - // let res = StandardResponse {op: "nope".to_string(), response: "hi".to_string()}; - // let out = serde_json::to_string(&res).unwrap(); MessageResult(res) } } -// /// Handler for `ListRooms` message. -// impl Handler for ChatServer { -// type Result = MessageResult; - -// fn handle(&mut self, _: ListRooms, _: &mut Context) -> Self::Result { -// let mut rooms = Vec::new(); - -// for key in self.rooms.keys() { -// rooms.push(key.to_owned()) -// } - -// MessageResult(rooms) -// } -// } - -// /// Join room, send disconnect message to old room -// /// send join message to new room -// impl Handler for ChatServer { -// type Result = (); - -// fn handle(&mut self, msg: Join, _: &mut Context) { -// let Join { id, name } = msg; -// let mut rooms = Vec::new(); - -// // remove session from all rooms -// for (n, sessions) in &mut self.rooms { -// if sessions.remove(&id) { -// rooms.push(n.to_owned()); -// } -// } -// // send message to other users -// for room in rooms { -// self.send_room_message(&room, "Someone disconnected", 0); -// } - -// if self.rooms.get_mut(&name).is_none() { -// self.rooms.insert(name.clone(), HashSet::new()); -// } -// self.send_room_message(&name, "Someone connected", id); -// self.rooms.get_mut(&name).unwrap().insert(id); -// } - -// } pub trait Perform { fn perform(&self) -> String; -} - -pub trait PerformAuth { - fn perform(&self, auth: &str) -> String; + fn op_type(&self) -> UserOperation; + fn error(&self, error_msg: &str) -> String { + serde_json::to_string( + &ErrorMessage { + op: self.op_type().to_string(), + error: error_msg.to_string() + } + ) + .unwrap() + } } impl Perform for Login { + fn op_type(&self) -> UserOperation { + UserOperation::Login + } fn perform(&self) -> String { let conn = establish_connection(); @@ -355,52 +384,38 @@ impl Perform for Login { // Fetch that username / email let user: User_ = match User_::find_by_email_or_username(&conn, &self.username_or_email) { Ok(user) => user, - Err(e) => return serde_json::to_string( - &ErrorMessage { - op: UserOperation::Login.to_string(), - error: "Couldn't find that username or email".to_string() - } - ) - .unwrap() + Err(e) => return self.error("Couldn't find that username or email") }; // Verify the password let valid: bool = verify(&self.password, &user.password_encrypted).unwrap_or(false); if !valid { - return serde_json::to_string( - &ErrorMessage { - op: UserOperation::Login.to_string(), - error: "Password incorrect".to_string() - } - ) - .unwrap() + return self.error("Password incorrect") } // Return the jwt serde_json::to_string( &LoginResponse { - op: UserOperation::Login.to_string(), + op: self.op_type().to_string(), jwt: user.jwt() } ) .unwrap() } + } impl Perform for Register { + fn op_type(&self) -> UserOperation { + UserOperation::Register + } fn perform(&self) -> String { let conn = establish_connection(); // Make sure passwords match if &self.password != &self.password_verify { - return serde_json::to_string( - &ErrorMessage { - op: UserOperation::Register.to_string(), - error: "Passwords do not match.".to_string() - } - ) - .unwrap(); + return self.error("Passwords do not match."); } // Register the new user @@ -416,20 +431,14 @@ impl Perform for Register { let inserted_user = match User_::create(&conn, &user_form) { Ok(user) => user, Err(e) => { - return serde_json::to_string( - &ErrorMessage { - op: UserOperation::Register.to_string(), - error: "User already exists.".to_string() // overwrite the diesel error - } - ) - .unwrap() + return self.error("User already exists."); } }; // Return the jwt serde_json::to_string( &LoginResponse { - op: UserOperation::Register.to_string(), + op: self.op_type().to_string(), jwt: inserted_user.jwt() } ) @@ -438,28 +447,25 @@ impl Perform for Register { } } -impl PerformAuth for CreateCommunity { - fn perform(&self, auth: &str) -> String { +impl Perform for CreateCommunity { + fn op_type(&self) -> UserOperation { + UserOperation::CreateCommunity + } + + fn perform(&self) -> String { let conn = establish_connection(); - let claims = match Claims::decode(&auth) { + let claims = match Claims::decode(&self.auth) { Ok(claims) => claims.claims, Err(e) => { - return serde_json::to_string( - &ErrorMessage { - op: UserOperation::CreateCommunity.to_string(), - error: "Community user already exists.".to_string() // overwrite the diesel error - } - ) - .unwrap(); + return self.error("Not logged in."); } }; let user_id = claims.id; let iss = claims.iss; - // Register the new user let community_form = CommunityForm { name: self.name.to_owned(), updated: None @@ -468,13 +474,7 @@ impl PerformAuth for CreateCommunity { let inserted_community = match Community::create(&conn, &community_form) { Ok(community) => community, Err(e) => { - return serde_json::to_string( - &ErrorMessage { - op: UserOperation::CreateCommunity.to_string(), - error: "Community already exists.".to_string() // overwrite the diesel error - } - ) - .unwrap() + return self.error("Community already exists."); } }; @@ -486,28 +486,192 @@ impl PerformAuth for CreateCommunity { let inserted_community_user = match CommunityUser::join(&conn, &community_user_form) { Ok(user) => user, Err(e) => { - return serde_json::to_string( - &ErrorMessage { - op: UserOperation::CreateCommunity.to_string(), - error: "Community user already exists.".to_string() // overwrite the diesel error - } - ) - .unwrap() + return self.error("Community user already exists."); } }; + serde_json::to_string( + &CreateCommunityResponse { + op: self.op_type().to_string(), + community: inserted_community + } + ) + .unwrap() + } +} + +impl Perform for ListCommunities { + fn op_type(&self) -> UserOperation { + UserOperation::ListCommunities + } + + fn perform(&self) -> String { + + let conn = establish_connection(); + + let communities: Vec = Community::list_all(&conn).unwrap(); // Return the jwt serde_json::to_string( - &CreateCommunityResponse { - op: UserOperation::CreateCommunity.to_string(), - data: inserted_community + &ListCommunitiesResponse { + op: self.op_type().to_string(), + communities: communities + } + ) + .unwrap() + } +} + +impl Perform for CreatePost { + fn op_type(&self) -> UserOperation { + UserOperation::CreatePost + } + + fn perform(&self) -> String { + + let conn = establish_connection(); + + let claims = match Claims::decode(&self.auth) { + Ok(claims) => claims.claims, + Err(e) => { + return self.error("Not logged in."); + } + }; + + let user_id = claims.id; + let iss = claims.iss; + + + let post_form = PostForm { + name: self.name.to_owned(), + url: self.url.to_owned(), + body: self.body.to_owned(), + community_id: self.community_id, + attributed_to: format!("{}/{}", iss, user_id), + updated: None + }; + + let inserted_post = match Post::create(&conn, &post_form) { + Ok(post) => post, + Err(e) => { + return self.error("Couldn't create Post"); + } + }; + + serde_json::to_string( + &CreatePostResponse { + op: self.op_type().to_string(), + post: inserted_post + } + ) + .unwrap() + } +} + + +impl Perform for GetPost { + fn op_type(&self) -> UserOperation { + UserOperation::GetPost + } + + fn perform(&self) -> String { + + let conn = establish_connection(); + + let post = match Post::read(&conn, self.id) { + Ok(post) => post, + Err(e) => { + return self.error("Couldn't find Post"); + } + }; + + let comments = Comment::from_post(&conn, &post).unwrap(); + + // Return the jwt + serde_json::to_string( + &GetPostResponse { + op: self.op_type().to_string(), + post: post, + comments: comments } ) .unwrap() + } +} + +impl Perform for GetCommunity { + fn op_type(&self) -> UserOperation { + UserOperation::GetCommunity + } + + fn perform(&self) -> String { + + let conn = establish_connection(); + let community = match Community::read(&conn, self.id) { + Ok(community) => community, + Err(e) => { + return self.error("Couldn't find Community"); + } + }; + + // Return the jwt + serde_json::to_string( + &GetCommunityResponse { + op: self.op_type().to_string(), + community: community + } + ) + .unwrap() } } + +impl Perform for CreateComment { + fn op_type(&self) -> UserOperation { + UserOperation::CreateComment + } + + fn perform(&self) -> String { + + let conn = establish_connection(); + + let claims = match Claims::decode(&self.auth) { + Ok(claims) => claims.claims, + Err(e) => { + return self.error("Not logged in."); + } + }; + + let user_id = claims.id; + let iss = claims.iss; + + let comment_form = CommentForm { + content: self.content.to_owned(), + parent_id: self.parent_id.to_owned(), + post_id: self.post_id, + attributed_to: format!("{}/{}", iss, user_id), + updated: None + }; + + let inserted_comment = match Comment::create(&conn, &comment_form) { + Ok(comment) => comment, + Err(e) => { + return self.error("Couldn't create Post"); + } + }; + + serde_json::to_string( + &CreateCommentResponse { + op: self.op_type().to_string(), + comment: inserted_comment + } + ) + .unwrap() + } +} + + + // impl Handler for ChatServer { // type Result = MessageResult; @@ -644,3 +808,49 @@ impl PerformAuth for CreateCommunity { // ) // } // } +// +// +// +// /// Handler for `ListRooms` message. +// impl Handler for ChatServer { +// type Result = MessageResult; + +// fn handle(&mut self, _: ListRooms, _: &mut Context) -> Self::Result { +// let mut rooms = Vec::new(); + +// for key in self.rooms.keys() { +// rooms.push(key.to_owned()) +// } + +// MessageResult(rooms) +// } +// } + +// /// Join room, send disconnect message to old room +// /// send join message to new room +// impl Handler for ChatServer { +// type Result = (); + +// fn handle(&mut self, msg: Join, _: &mut Context) { +// let Join { id, name } = msg; +// let mut rooms = Vec::new(); + +// // remove session from all rooms +// for (n, sessions) in &mut self.rooms { +// if sessions.remove(&id) { +// rooms.push(n.to_owned()); +// } +// } +// // send message to other users +// for room in rooms { +// self.send_room_message(&room, "Someone disconnected", 0); +// } + +// if self.rooms.get_mut(&name).is_none() { +// self.rooms.insert(name.clone(), HashSet::new()); +// } +// self.send_room_message(&name, "Someone connected", id); +// self.rooms.get_mut(&name).unwrap().insert(id); +// } + +// } diff --git a/ui/src/components/community.tsx b/ui/src/components/community.tsx new file mode 100644 index 00000000..b0322635 --- /dev/null +++ b/ui/src/components/community.tsx @@ -0,0 +1,72 @@ +import { Component, linkEvent } from 'inferno'; +import { Subscription } from "rxjs"; +import { retryWhen, delay, take } from 'rxjs/operators'; +import { UserOperation, Community as CommunityI, CommunityResponse, Post } from '../interfaces'; +import { WebSocketService, UserService } from '../services'; +import { msgOp } from '../utils'; + +interface State { + community: CommunityI; + posts: Array; +} + +export class Community extends Component { + + private subscription: Subscription; + private emptyState: State = { + community: { + id: null, + name: null, + published: null + }, + posts: [] + } + + constructor(props, context) { + super(props, context); + + this.state = this.emptyState; + + console.log(this.props.match.params.id); + + this.subscription = WebSocketService.Instance.subject + .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10)))) + .subscribe( + (msg) => this.parseMessage(msg), + (err) => console.error(err), + () => console.log('complete') + ); + + let communityId = Number(this.props.match.params.id); + WebSocketService.Instance.getCommunity(communityId); + } + + componentWillUnmount() { + this.subscription.unsubscribe(); + } + + render() { + return ( +
+
+
+ {this.state.community.name} +
+
+
+ ) + } + + parseMessage(msg: any) { + console.log(msg); + let op: UserOperation = msgOp(msg); + if (msg.error) { + alert(msg.error); + return; + } else if (op == UserOperation.GetCommunity) { + let res: CommunityResponse = msg; + this.state.community = res.community; + this.setState(this.state); + } + } +} diff --git a/ui/src/components/create-community.tsx b/ui/src/components/create-community.tsx index 159147b6..0a0edae6 100644 --- a/ui/src/components/create-community.tsx +++ b/ui/src/components/create-community.tsx @@ -11,20 +11,20 @@ interface State { communityForm: CommunityForm; } -let emptyState: State = { - communityForm: { - name: null, - } -} - export class CreateCommunity extends Component { private subscription: Subscription; + private emptyState: State = { + communityForm: { + name: null, + } + } + constructor(props, context) { super(props, context); - this.state = emptyState; - + this.state = this.emptyState; + this.subscription = WebSocketService.Instance.subject .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10)))) .subscribe( @@ -89,7 +89,8 @@ export class CreateCommunity extends Component { return; } else { if (op == UserOperation.CreateCommunity) { - let community: Community = msg.data; + let community: Community = msg.community; + this.props.history.push(`/community/${community.id}`); } } } diff --git a/ui/src/components/create-post.tsx b/ui/src/components/create-post.tsx index bb6e60e2..9ddf8c97 100644 --- a/ui/src/components/create-post.tsx +++ b/ui/src/components/create-post.tsx @@ -1,56 +1,141 @@ import { Component, linkEvent } from 'inferno'; - -import { LoginForm, PostForm, UserOperation } from '../interfaces'; +import { Subscription } from "rxjs"; +import { retryWhen, delay, take } from 'rxjs/operators'; +import { PostForm, Post, PostResponse, UserOperation, Community, ListCommunitiesResponse } from '../interfaces'; import { WebSocketService, UserService } from '../services'; import { msgOp } from '../utils'; interface State { postForm: PostForm; + communities: Array; } -let emptyState: State = { - postForm: { - name: null, - url: null, - attributed_to: null - } -} export class CreatePost extends Component { + private subscription: Subscription; + private emptyState: State = { + postForm: { + name: null, + auth: null, + community_id: null + }, + communities: [] + } + constructor(props, context) { super(props, context); - this.state = emptyState; + this.state = this.emptyState; - WebSocketService.Instance.subject.subscribe( - (msg) => this.parseMessage(msg), - (err) => console.error(err), - () => console.log('complete') - ); + this.subscription = WebSocketService.Instance.subject + .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10)))) + .subscribe( + (msg) => this.parseMessage(msg), + (err) => console.error(err), + () => console.log('complete') + ); + + WebSocketService.Instance.listCommunities(); } + componentWillUnmount() { + this.subscription.unsubscribe(); + } render() { return (
- create post - {/* {this.postForm()} */} + {this.postForm()}
) } + postForm() { + return ( +
+
+

Create a Post

+
+ +
+ +
+
+
+ +
+