Skip to content

Commit

Permalink
added mutations for crud operation in posts module
Browse files Browse the repository at this point in the history
  • Loading branch information
enochval committed Jun 13, 2024
1 parent 4c59a7c commit 258fa26
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 8 deletions.
8 changes: 4 additions & 4 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ import configuration from './config/configuration';
typePaths: ['./**/*.graphql'],
playground: true,
introspection: true,
// definitions: {
// path: join(process.cwd(), 'src/graphql.ts'),
// outputAs: 'class'
// },
definitions: {
path: join(process.cwd(), 'src/graphql.ts'),
outputAs: 'class'
},
}),
UserModule,
PostsModule,
Expand Down
22 changes: 21 additions & 1 deletion src/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,20 @@
/* tslint:disable */
/* eslint-disable */

export class CreatePostInput {
title: string;
body: string;
userId: number;
}

export class UpdatePostInput {
title?: Nullable<string>;
body?: Nullable<string>;
userId?: Nullable<number>;
}

export class User {
id?: Nullable<number>;
id: number;
name?: Nullable<string>;
username?: Nullable<string>;
email?: Nullable<string>;
Expand Down Expand Up @@ -95,4 +107,12 @@ export abstract class IQuery {
abstract todos(first?: Nullable<number>, todoId?: Nullable<number>, userId?: Nullable<number>): Nullable<Nullable<Todo>[]> | Promise<Nullable<Nullable<Todo>[]>>;
}

export abstract class IMutation {
abstract createPost(post: CreatePostInput): Nullable<Post> | Promise<Nullable<Post>>;

abstract updatePost(postId: number, post: UpdatePostInput): Nullable<Post> | Promise<Nullable<Post>>;

abstract deletePost(postId: number): Nullable<string> | Promise<Nullable<string>>;
}

type Nullable<T> = T | null;
40 changes: 40 additions & 0 deletions src/jsonplaceholder/jsonplaceholder.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,44 @@ export class JsonplaceholderService<T> {

return rsp
}

async handlePostRequest<P>(uri: string, payload: P): Promise<T> {
const url = `${this.baseUrl}${uri}`
const { data } = await firstValueFrom(
this.httpService.post<T>(url, payload).pipe(
catchError((err: AxiosError) => {
this.logger.error(err.response.data)
throw new BadRequestException("An error happened!")
})
)
)

return data
}

async handlePatchRequest<P>(uri: string, payload: P): Promise<T> {
const url = `${this.baseUrl}${uri}`
const { data } = await firstValueFrom(
this.httpService.patch<T>(url, payload).pipe(
catchError((err: AxiosError) => {
this.logger.error(err.response.data)
throw new BadRequestException("An error happened!")
})
)
)
return data
}

async handleDeleteRequest(uri: string): Promise<any> {
const url = `${this.baseUrl}${uri}`
const { data } = await firstValueFrom(
this.httpService.delete<any>(url).pipe(
catchError((err: AxiosError) => {
this.logger.error(err.response.data)
throw new BadRequestException("An error happened!")
})
)
)
return data
}
}
18 changes: 18 additions & 0 deletions src/posts/dto/create-post.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { IsNotEmpty, IsNumber, IsPositive, IsString } from "class-validator"


export class CreatePostDTO {

@IsString()
@IsNotEmpty()
title: string

@IsString()
@IsNotEmpty()
body: string

@IsPositive()
@IsNotEmpty()
@IsNumber()
userId: number
}
22 changes: 20 additions & 2 deletions src/posts/posts.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Args, Parent, Query, ResolveField, Resolver } from "@nestjs/graphql";
import { Args, Mutation, Parent, Query, ResolveField, Resolver } from "@nestjs/graphql";
import { PostsService } from "./posts.service";
import { Post, User, Comment } from "src/graphql";
import { UserService } from "src/users/users.service";
import { CommentsService } from "./comments/comments.service";
import { CreatePostDTO } from "./dto/create-post.dto";

@Resolver('Post')
export class PostsResolver {
Expand All @@ -11,7 +12,7 @@ export class PostsResolver {
private readonly postsService: PostsService,
private readonly userService: UserService,
private readonly commentsService: CommentsService
){}
) { }

@Query('posts')
async getPosts(@Args() args: any): Promise<Post[]> {
Expand All @@ -27,4 +28,21 @@ export class PostsResolver {
async getPostComments(@Parent() post, @Args() args): Promise<Comment[]> {
return await this.commentsService.getPostComments(post.id, args)
}

@Mutation()
async createPost(@Args('post') post: CreatePostDTO): Promise<Post> {
return this.postsService.createPost(post)
}

@Mutation()
async updatePost(
@Args('postId') postId: number,
@Args('post') post: Partial<CreatePostDTO>): Promise<Post> {
return this.postsService.updatePost(postId, post)
}

@Mutation()
async deletePost(@Args('postId') postId: number): Promise<string> {
return await this.postsService.deletePost(postId)
}
}
20 changes: 20 additions & 0 deletions src/posts/posts.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { Post } from 'src/graphql';
import { JsonplaceholderService } from 'src/jsonplaceholder/jsonplaceholder.service';
import { CreatePostDTO } from './dto/create-post.dto';

@Injectable()
export class PostsService {
Expand All @@ -25,4 +26,23 @@ export class PostsService {
const uri: string = `/posts/${id}`
return await this.jsonplaceholderService.handleGetRequest(uri)
}

async createPost(post: CreatePostDTO): Promise<Post> {
return await this.jsonplaceholderService.handlePostRequest<CreatePostDTO>(
'/posts', post
)
}

async updatePost(id: number, post: Partial<CreatePostDTO>): Promise<Post> {
return await this.jsonplaceholderService.handlePatchRequest<Partial<CreatePostDTO>>(
`/posts/${id}`, post
)
}

async deletePost(id: number): Promise<string> {
await this.jsonplaceholderService.handleDeleteRequest(
`/posts/${id}`
)
return `Post with ID ${id} is successfully deleted.`
}
}
20 changes: 19 additions & 1 deletion src/users/users.graphql
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
type User {
id: Int
id: Int!
name: String
username: String
email: String
Expand Down Expand Up @@ -69,6 +69,18 @@ type Todo {
user: User
}

input CreatePostInput {
title: String!
body: String!
userId: Int!
}

input UpdatePostInput {
title: String
body: String
userId: Int
}

type Query {
users(first: Int, userId: Int): [User]
userById(id: Int!): User
Expand All @@ -77,4 +89,10 @@ type Query {
albums(first: Int, albumId: Int, userId: Int): [Album]
photos(first: Int, photoId: Int, albumId: Int): [Photo]
todos(first: Int, todoId: Int, userId: Int): [Todo]
}

type Mutation {
createPost(post: CreatePostInput!): Post
updatePost(postId: Int!, post: UpdatePostInput!): Post
deletePost(postId: Int!): String
}

0 comments on commit 258fa26

Please sign in to comment.