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

add searchPostsByTag query #10

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
19 changes: 19 additions & 0 deletions src/controllers/post.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
deletePost,
getPostById,
getPostsByUser,
searchPostByTag,
} from '../services/post.service';
import AppError from '../utils/appError';
class PostController {
Expand Down Expand Up @@ -80,6 +81,24 @@ class PostController {
next(err);
}
};

public getPostsByTag = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { tag } = req.query;
if (typeof tag !== 'string') {
return [];
}

const posts = await searchPostByTag(tag);
return res.status(200).json(posts);
} catch (err) {
next(err);
}
};
}

export const postController = new PostController();
99 changes: 48 additions & 51 deletions src/entities/post.entity.ts
Original file line number Diff line number Diff line change
@@ -1,83 +1,80 @@
import { Column, Entity, ManyToMany, ManyToOne, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import Model from "./model.entity";
import { User } from "./user.entity";


import {
Column,
Entity,
ManyToMany,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
} from 'typeorm';
import Model from './model.entity';
import { User } from './user.entity';

@Entity()
export class Post extends Model{
export class Post extends Model {
@PrimaryGeneratedColumn('uuid')
id!: string;

@PrimaryGeneratedColumn("uuid")
id!: string;
@Column('text')
contentText!: string;

@Column("text")
contentText!: string;
@OneToMany(() => PostImage, (image) => image.post)
contentImages!: PostImage[];

@OneToMany(() => PostImage, (image) => image.post)
contentImages!: PostImage[]
@ManyToOne(() => User)
postedBy!: User;

@ManyToOne(() => User, )
postedBy!: User;

@OneToMany(() => Comment, (comment) => comment.post)
comments!: Comment[];
@OneToMany(() => Comment, (comment) => comment.post)
comments!: Comment[];

@OneToMany(() => Like, (like) => like.post)
likes!: Like[]
@OneToMany(() => Like, (like) => like.post)
likes!: Like[];

@Column({
type: 'varchar',
array: true,
default: ["All"]
})
tags!: string[];
}


@Entity()
export class PostImage extends Model{

@PrimaryGeneratedColumn("increment")
id!: string;
export class PostImage extends Model {
@PrimaryGeneratedColumn('increment')
id!: string;

@ManyToOne(() => Post, (post) => post.contentImages)
post!: Post;
@ManyToOne(() => Post, (post) => post.contentImages)
post!: Post;

@Column()
url!: string;

@Column()
url!: string;
}


@Entity()
export class Comment extends Model{

@Column("text")
content!: string;

@ManyToOne(() => Post, (post) => post.comments)
post!: Post;

@ManyToOne(() => User)
user!: User;

export class Comment extends Model {
@Column('text')
content!: string;

@ManyToOne(() => Post, (post) => post.comments)
post!: Post;

@ManyToOne(() => User)
user!: User;
}


@Entity()
export class Like extends Model{

@PrimaryGeneratedColumn("increment")
export class Like extends Model {
@PrimaryGeneratedColumn('increment')
id!: string;

@ManyToOne(() => Post, (post) => post.likes)
post!: Post;

@ManyToOne(() => User,)
@ManyToOne(() => User)
user!: User;

@Column("boolean")
@Column('boolean')
liked!: boolean;

@Column("timestamp")
@Column('timestamp')
likedAt!: Date;

}


1 change: 1 addition & 0 deletions src/routes/post.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ postRouter.get('/feed', postController.getFeed);
postRouter.post('/new', postController.create);
postRouter.get('/posts', postController.getPostsByUser);
postRouter.delete('/:postId', postController.deletePost);
postRouter.get('/posts/tag', postController.getPostsByTag);

// Comment
postRouter.post('/:postId/comment', commentController.commentOnPost);
Expand Down
38 changes: 17 additions & 21 deletions src/serializers/postSerializers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,20 @@ import { findUserById } from '../services/user.service';
import UserSerializer from './userSerializer';
import AppError from '../utils/appError';

export class PostImageSerializer extends Serializer<PostImage, any>{

serialize(instance: PostImage): string {
return instance.url;
}

deserialize(data: string): PostImage {
let image = new PostImage();
image.url = data;
return image;
}

deserializePromise(data: any): Promise<PostImage> {
throw new Error("Method not implemented.");
}
export class PostImageSerializer extends Serializer<PostImage, any> {
serialize(instance: PostImage): string {
return instance.url;
}

deserialize(data: string): PostImage {
let image = new PostImage();
image.url = data;
return image;
}

deserializePromise(data: any): Promise<PostImage> {
throw new Error('Method not implemented.');
}
}

export class PostSerializer extends Serializer<Post, any> {
Expand All @@ -37,6 +34,7 @@ export class PostSerializer extends Serializer<Post, any> {
likes: instance.likes,
comments: instance.comments,
postedBy: this.userSerializer.serialize(instance.postedBy),
tags: instance.tags,
};
}

Expand All @@ -46,6 +44,7 @@ export class PostSerializer extends Serializer<Post, any> {
post.contentImages = this.imageSerializer.deserializeMany(
data.content_images
);
post.tags = data['tags'].length > 0 ? data['tags'] : [];
return post;
}

Expand All @@ -60,15 +59,12 @@ export class PostSerializer extends Serializer<Post, any> {
(post.contentText = data.contentText),
(post.comments = data.comments),
(post.likes = data.likes);
post.id = data.id;
post.id = data.id;
post.tags = data['tags'].length > 0 ? data['tags'] : ["All"];
return post;
}

protected getValidations(): ValidationChain[] {
return [
body('tags').notEmpty(),
body('content_text').notEmpty(),
body('content_images').notEmpty(),
];
return [body('content_text').notEmpty(), body('content_images').notEmpty()];
}
}
22 changes: 14 additions & 8 deletions src/services/post.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,13 @@ export const getPostById = async (postId: string) => {

export const getPostsByUser = async (userId: string) => {
return await postRepository
.createQueryBuilder("post")
.where("post.postedBy = :userId", { userId })
.leftJoinAndSelect("post.comments", "comments")
.leftJoinAndSelect("post.likes", "likes")
.leftJoinAndSelect("post.contentImages", "contentImages")
.leftJoinAndSelect("post.postedBy", "postedBy")
.getMany();

.createQueryBuilder('post')
.where('post.postedBy = :userId', { userId })
.leftJoinAndSelect('post.comments', 'comments')
.leftJoinAndSelect('post.likes', 'likes')
.leftJoinAndSelect('post.contentImages', 'contentImages')
.leftJoinAndSelect('post.postedBy', 'postedBy')
.getMany();

// return await postRepository.find({ where: { postedBy: { id: userId } } });
};
Expand All @@ -32,3 +31,10 @@ export const deletePost = async (postId: string) => {
await likeRepository.delete({ post: { id: postId } });
return await postRepository.delete(postId);
};

export const searchPostByTag = async (tag: string) => {
return await postRepository
.createQueryBuilder('post')
.where(':tag = ANY(post.tags)', { tag })
.getMany();
};