Skip to content

Commit

Permalink
implemented query and filters for users, userById, posts comments
Browse files Browse the repository at this point in the history
  • Loading branch information
enochval committed Jun 5, 2024
1 parent 6902084 commit 16449fa
Show file tree
Hide file tree
Showing 16 changed files with 238 additions and 53 deletions.
6 changes: 3 additions & 3 deletions src/albums/albums.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Parent, ResolveField, Resolver } from "@nestjs/graphql";
import { Args, Parent, ResolveField, Resolver } from "@nestjs/graphql";
import { PhotosService } from "./photos/photos.service";
import { Photo } from "src/graphql";

Expand All @@ -8,9 +8,9 @@ export class AlbumResolver {
constructor(private readonly photosService: PhotosService) {}

@ResolveField('photos')
async getAlbumPhotos(@Parent() album): Promise<Photo[]> {
async getAlbumPhotos(@Parent() album, @Args() args): Promise<Photo[]> {
const { id } = album
return await this.photosService.getPhotosByAlbumId(id)
return await this.photosService.getPhotosByAlbumId(id, args)
}

}
10 changes: 8 additions & 2 deletions src/albums/albums.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class AlbumsService {
this.baseUrl = this.configService.get<string>('api.baseurl')
}

async getUserAlbums(id: number): Promise<Album[]> {
async getUserAlbums(id: number, args: any): Promise<Album[]> {
const { data } = await firstValueFrom(
this.httpService.get<any[]>(`${this.baseUrl}/albums`).pipe(
catchError((err: AxiosError) => {
Expand All @@ -26,6 +26,12 @@ export class AlbumsService {
})
)
)
return data.filter(o => o.userId === id)
const userAlbums = data.filter(o => o.userId === id)

if (args.first) {
return userAlbums.slice(0, args.first)
}

return userAlbums;
}
}
10 changes: 8 additions & 2 deletions src/albums/photos/photos.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class PhotosService {
this.baseUrl = this.configService.get<string>('api.baseurl')
}

async getPhotosByAlbumId(albumId: number): Promise<Photo[]> {
async getPhotosByAlbumId(albumId: number, args: any): Promise<Photo[]> {
const { data } = await firstValueFrom(
this.httpService.get<any[]>(`${this.baseUrl}/photos`).pipe(
catchError((err: AxiosError) => {
Expand All @@ -27,6 +27,12 @@ export class PhotosService {
)
)

return data.filter(o => o.albumId === albumId)
const photos: Photo[] = data.filter(o => o.albumId === albumId)

if (args.first) {
return photos.slice(0, args.first)
}

return photos;
}
}
4 changes: 2 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { AppService } from './app.service';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { join } from 'path';
import { AuthorModule } from './users/users.module';
import { UserModule } from './users/users.module';
import { PostsModule } from './posts/posts.module';
import { ConfigModule } from '@nestjs/config';
import { AlbumsModule } from './albums/albums.module';
Expand All @@ -27,7 +27,7 @@ import configuration from './config/configuration';
// outputAs: 'class'
// },
}),
AuthorModule,
UserModule,
PostsModule,
AlbumsModule,
TodosModule
Expand Down
17 changes: 13 additions & 4 deletions src/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
/* eslint-disable */

export class User {
id: number;
id?: Nullable<number>;
name?: Nullable<string>;
username?: Nullable<string>;
email?: Nullable<string>;
Expand Down Expand Up @@ -43,41 +43,50 @@ export class Company {

export class Post {
id: number;
title: string;
title?: Nullable<string>;
body?: Nullable<string>;
comments?: Nullable<Nullable<Comment>[]>;
user?: Nullable<User>;
}

export class Comment {
id: number;
name?: Nullable<string>;
email?: Nullable<string>;
body?: Nullable<string>;
post?: Nullable<Post>;
}

export class Album {
id: number;
title?: Nullable<string>;
photos?: Nullable<Nullable<Photo>[]>;
user?: Nullable<User>;
}

export class Photo {
id: number;
title?: Nullable<string>;
url?: Nullable<string>;
thumbnailUrl?: Nullable<string>;
album?: Nullable<Album>;
}

export class Todo {
id: number;
title?: Nullable<string>;
completed?: Nullable<boolean>;
user?: Nullable<User>;
}

export abstract class IQuery {
abstract users(): Nullable<Nullable<User>[]> | Promise<Nullable<Nullable<User>[]>>;
abstract users(first?: Nullable<number>, userId?: Nullable<number>): Nullable<Nullable<User>[]> | Promise<Nullable<Nullable<User>[]>>;

abstract userById(id: number): Nullable<User> | Promise<Nullable<User>>;

abstract posts(first?: Nullable<number>, postId?: Nullable<number>, userId?: Nullable<number>): Nullable<Nullable<Post>[]> | Promise<Nullable<Nullable<Post>[]>>;

abstract user(id: number): Nullable<User> | Promise<Nullable<User>>;
abstract comments(first?: Nullable<number>, commentId?: Nullable<number>, postId?: Nullable<number>): Nullable<Nullable<Comment>[]> | Promise<Nullable<Nullable<Comment>[]>>;
}

type Nullable<T> = T | null;
23 changes: 23 additions & 0 deletions src/posts/comments/comments.resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Args, Parent, Query, ResolveField, Resolver } from "@nestjs/graphql";
import { CommentsService } from "./comments.service";
import { Comment, Post } from "src/graphql";
import { PostsService } from "../posts.service";

@Resolver('Comment')
export class CommentsResolver {

constructor(
private readonly commentsService: CommentsService,
private readonly postsService: PostsService
) {}

@Query('comments')
async getComments(@Args() args: any): Promise<Comment[]> {
return await this.commentsService.getComments(args)
}

@ResolveField('post')
async getCommentPost(@Parent() comment): Promise<Post> {
return await this.postsService.getPost(comment.postId)
}
}
18 changes: 18 additions & 0 deletions src/posts/comments/comments.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CommentsService } from './comments.service';

describe('CommentsService', () => {
let service: CommentsService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CommentsService],
}).compile();

service = module.get<CommentsService>(CommentsService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
48 changes: 48 additions & 0 deletions src/posts/comments/comments.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { HttpService } from '@nestjs/axios';
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AxiosError } from 'axios';
import { catchError, firstValueFrom } from 'rxjs';
import { Comment } from 'src/graphql';

@Injectable()
export class CommentsService {
private readonly logger: Logger = new Logger(CommentsService.name)
private baseUrl: string

constructor(
private readonly httpService: HttpService,
private readonly configService: ConfigService
){
this.baseUrl = this.configService.get<string>('api.baseurl')
}

async getComments(args: any): Promise<Comment[]> {
const slashCommentId = `${args.commentId ? '/'+args.commentId : ''}`
const queryPostId = `${args.postId ? '?postId=' + args.postId : ''}`
const uri = `${this.baseUrl}/comments${slashCommentId}${queryPostId}`

const { data } = await firstValueFrom(
this.httpService.get<any|Comment[]>(uri).pipe(
catchError((err: AxiosError) => {
this.logger.error(err.response.data)
throw new BadRequestException("An error happened!")
})
)
)

if (args.commentId) {
const res: Array<Comment> = []
res.push(data)
return res
}

let rsp: Array<Comment> = data

if (args.first) {
rsp = rsp.slice(0, args.first)
}

return rsp
}
}
9 changes: 6 additions & 3 deletions src/posts/posts.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Module } from '@nestjs/common';
import { Module, forwardRef } from '@nestjs/common';
import { PostsService } from './posts.service';
import { HttpModule } from '@nestjs/axios';
import { PostsResolver } from './posts.resolver';
import { UserModule } from 'src/users/users.module';
import { CommentsService } from './comments/comments.service';
import { CommentsResolver } from './comments/comments.resolver';

@Module({
imports: [HttpModule],
providers: [PostsService, PostsResolver],
imports: [HttpModule, forwardRef(() => UserModule)],
providers: [PostsService, PostsResolver, CommentsService, CommentsResolver],
exports: [PostsService]
})
export class PostsModule {}
23 changes: 19 additions & 4 deletions src/posts/posts.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
import { Parent, ResolveField, Resolver } from "@nestjs/graphql";
import { Args, Parent, Query, ResolveField, Resolver } from "@nestjs/graphql";
import { PostsService } from "./posts.service";
import { Post, User } from "src/graphql";
import { UserService } from "src/users/users.service";

@Resolver('Post')
export class PostsResolver {

constructor(private readonly postsService: PostsService){}
constructor(
private readonly postsService: PostsService,
private readonly userService: UserService
){}

@Query('posts')
async getPosts(@Args() args: any): Promise<Post[]> {
return await this.postsService.getPosts(args)
}

@ResolveField('user')
async getPostUser(@Parent() post): Promise<User> {
return await this.userService.getUserById(post.userId)
}

@ResolveField('comments')
async getPosts(@Parent() post): Promise<Comment[]> {
async getPostComments(@Parent() post, @Args() args): Promise<Comment[]> {
const { id } = post
return await this.postsService.getPostComments(id)
return await this.postsService.getPostComments(id, args)
}
}
42 changes: 35 additions & 7 deletions src/posts/posts.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { HttpService } from '@nestjs/axios';
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AxiosError, AxiosResponse } from 'axios';
import { AxiosError } from 'axios';
import { catchError, firstValueFrom } from 'rxjs';
import { Post } from 'src/graphql';

Expand All @@ -17,16 +17,33 @@ export class PostsService {
this.baseUrl = this.configService.get<string>('api.baseurl')
}

async getPosts(): Promise<Post[]> {
async getPosts(args: any): Promise<Post[]> {
const slashPostId = `${args.commentId ? '/'+args.commentId : ''}`
const queryUserId = `${args.userId ? '?userId=' + args.userId : ''}`
const uri = `${this.baseUrl}/posts${slashPostId}${queryUserId}`

const { data } = await firstValueFrom(
this.httpService.get<Post[]>(`${this.baseUrl}/posts`).pipe(
this.httpService.get<any|Post[]>(uri).pipe(
catchError((err: AxiosError) => {
this.logger.error(err.response.data)
throw new BadRequestException("An error happened!")
})
)
)
return data

if (args.postId) {
const posts: Array<Post> = []
posts.push(data)
return posts
}

let rsp: Array<any> = data

if (args.first) {
rsp = rsp.slice(0, args.first)
}

return rsp
}

async getPost(id: number): Promise<Post> {
Expand All @@ -41,7 +58,7 @@ export class PostsService {
return data
}

async getUserPosts(userId: number): Promise<Post[]> {
async getUserPosts(userId: number, args: any): Promise<Post[]> {
const { data } = await firstValueFrom(
this.httpService.get<any[]>(`${this.baseUrl}/posts`).pipe(
catchError((err: AxiosError) => {
Expand All @@ -50,10 +67,16 @@ export class PostsService {
})
)
)
return data.filter(a => a.userId === userId)
const userPosts = data.filter(a => a.userId === userId)

if (args.first) {
return userPosts.slice(0, args.first)
}

return userPosts
}

async getPostComments(postId: number): Promise<Comment[]> {
async getPostComments(postId: number, args: any): Promise<Comment[]> {
const { data } = await firstValueFrom(
this.httpService.get<Comment[]>(`${this.baseUrl}/post/${postId}/comments`)
.pipe(
Expand All @@ -63,6 +86,11 @@ export class PostsService {
})
)
)

if (args.first) {
return data.slice(0, args.first)
}

return data
}
}
Loading

0 comments on commit 16449fa

Please sign in to comment.