Skip to content

Commit

Permalink
Merge pull request #7 from abhi3700/posts
Browse files Browse the repository at this point in the history
Add Posts module (with tests)
  • Loading branch information
abhi3700 authored Nov 1, 2024
2 parents 17390c1 + aec9664 commit 95eb339
Show file tree
Hide file tree
Showing 9 changed files with 458 additions and 37 deletions.
96 changes: 96 additions & 0 deletions api-requests/posts.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
@host=https://dummyjson.com/posts

###
# @name GetAllPosts
GET {{host}}
Accept: application/json
Content-Type: application/json

###
# @name GetPostById
@id=1
GET {{host}}/{{id}}
Accept: application/json
Content-Type: application/json


###
# @name SearchPosts
@search=love
GET {{host}}/search?q={{search}}
Accept: application/json
Content-Type: application/json


###
# @name LimitAndSkipPosts
GET {{host}}?limit=10&skip=10&select=title,reactions,userId
Accept: application/json
Content-Type: application/json

###
# @name SortPosts
GET {{host}}?sortBy=title&order=desc
Accept: application/json
Content-Type: application/json


###
# @name GetAllPostsTags
GET {{host}}/tags
Accept: application/json
Content-Type: application/json

###
# @name GetPostsByTags
@tags=nature
GET {{host}}/tag/{{tags}}
Accept: application/json
Content-Type: application/json

###
# @name GetPostsByUserId
@userId=1
GET {{host}}/user/{{userId}}
Accept: application/json
Content-Type: application/json

###
# @name GetPostComments
@id=1
GET {{host}}/{{id}}/comments
Accept: application/json
Content-Type: application/json


###
# @name AddPost
POST {{host}}/add
Accept: application/json
Content-Type: application/json

{
"title": "test title",
"body": "test body",
"userId": 1,
"tags": ["nature", "photography"]
}

###
# @name UpdatePost
@id=1
PUT {{host}}/{{id}}
Accept: application/json
Content-Type: application/json

{
"title": "updated title",
"body": "updated body"
}

###
# @name DeletePost
@id=1
DELETE {{host}}/{{id}}
Accept: application/json
Content-Type: application/json
6 changes: 3 additions & 3 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,14 @@ impl DummyJsonClient {
expires_in_mins,
};

let url = format!("{}/login", *AUTH_BASE_URL);
let url = format!("{}/login", AUTH_BASE_URL.as_str());
let response = self.client.post(url).json(&payload).send().await?;
response.json().await
}

/// Get the current user
pub async fn get_user(&self, access_token: &str) -> Result<User, reqwest::Error> {
let url = format!("{}/me", *AUTH_BASE_URL);
let url = format!("{}/me", AUTH_BASE_URL.as_str());
let response = self
.client
.get(url)
Expand All @@ -127,7 +127,7 @@ impl DummyJsonClient {
"expiresInMins": expires_in_mins,
});

let url = format!("{}/refresh", *AUTH_BASE_URL);
let url = format!("{}/refresh", AUTH_BASE_URL.as_str());
let response = self.client.post(url).json(&payload).send().await?;
response.json().await
}
Expand Down
12 changes: 6 additions & 6 deletions src/carts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ pub struct DeleteCartResponse {
impl DummyJsonClient {
/// Get all carts
pub async fn get_all_carts(&self) -> Result<GetAllCartsResponse, reqwest::Error> {
let url = &*CARTS_BASE_URL;
let url = CARTS_BASE_URL.as_str();
self.client.get(url).send().await?.json::<GetAllCartsResponse>().await
}

/// Get cart by id
pub async fn get_cart_by_id(&self, id: u32) -> Result<Cart, reqwest::Error> {
let url = format!("{}/{}", &*CARTS_BASE_URL, id);
let url = format!("{}/{}", CARTS_BASE_URL.as_str(), id);
self.client.get(url).send().await?.json::<Cart>().await
}

Expand All @@ -84,13 +84,13 @@ impl DummyJsonClient {
&self,
user_id: u32,
) -> Result<GetAllCartsResponse, reqwest::Error> {
let url = format!("{}/user/{}", &*CARTS_BASE_URL, user_id);
let url = format!("{}/user/{}", CARTS_BASE_URL.as_str(), user_id);
self.client.get(url).send().await?.json::<GetAllCartsResponse>().await
}

/// Add cart
pub async fn add_cart(&self, payload: AddCartPayload) -> Result<Cart, reqwest::Error> {
let url = format!("{}/add", &*CARTS_BASE_URL);
let url = format!("{}/add", CARTS_BASE_URL.as_str());
self.client.post(url).json(&payload).send().await?.json::<Cart>().await
}

Expand All @@ -100,13 +100,13 @@ impl DummyJsonClient {
id: u32,
payload: UpdateCartPayload,
) -> Result<Cart, reqwest::Error> {
let url = format!("{}/{}", &*CARTS_BASE_URL, id);
let url = format!("{}/{}", CARTS_BASE_URL.as_str(), id);
self.client.put(url).json(&payload).send().await?.json::<Cart>().await
}

/// Delete cart
pub async fn delete_cart(&self, cart_id: u32) -> Result<DeleteCartResponse, reqwest::Error> {
let url = format!("{}/{}", &*CARTS_BASE_URL, cart_id);
let url = format!("{}/{}", CARTS_BASE_URL.as_str(), cart_id);
self.client.delete(url).send().await?.json::<DeleteCartResponse>().await
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
mod auth;
mod carts;
mod posts;
mod products;
mod recipes;
mod todos;

pub use auth::*;
pub use carts::*;
pub use posts::*;
pub use products::*;
pub use recipes::*;
use reqwest::Client;
Expand Down
203 changes: 203 additions & 0 deletions src/posts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
use crate::{DummyJsonClient, ProductCategory, API_BASE_URL};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};

static POSTS_BASE_URL: Lazy<String> = Lazy::new(|| format!("{}/posts", API_BASE_URL));

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Post {
pub id: u32,
#[serde(flatten)]
pub other_fields: AddPost,
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct AddPost {
pub title: Option<String>,
pub body: Option<String>,
pub tags: Option<Vec<String>>,
pub reactions: Option<Reaction>,
pub views: Option<u32>,
#[serde(rename = "userId")]
pub user_id: Option<u32>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Reaction {
pub likes: u32,
pub dislikes: u32,
}

#[derive(Deserialize, Debug)]
pub struct GetAllPosts {
pub posts: Vec<Post>,
pub total: u32,
pub skip: u32,
pub limit: u32,
}

#[derive(Deserialize, Debug)]
pub struct PostComment {
pub id: u32,
pub body: String,
#[serde(rename = "postId")]
pub post_id: u32,
pub likes: u32,
pub user: UserProfile,
}

#[derive(Deserialize, Debug)]
pub struct UserProfile {
pub id: u32,
pub username: String,
#[serde(rename = "fullName")]
pub full_name: String,
}

#[derive(Deserialize, Debug)]
pub struct PostCommentsResponse {
pub comments: Vec<PostComment>,
pub total: u32,
pub skip: u32,
pub limit: u32,
}

impl DummyJsonClient {
/// Get all posts
pub async fn get_all_posts(&self) -> Result<GetAllPosts, reqwest::Error> {
self.client
.get(POSTS_BASE_URL.as_str())
.send()
.await?
.json::<GetAllPosts>()
.await
}

/// Get post by id
pub async fn get_post_by_id(&self, id: u32) -> Result<Post, reqwest::Error> {
self.client
.get(format!("{}/{}", POSTS_BASE_URL.as_str(), id))
.send()
.await?
.json::<Post>()
.await
}

/// Search posts
pub async fn search_posts(&self, query: &str) -> Result<GetAllPosts, reqwest::Error> {
self.client
.get(format!("{}/search?q={}", POSTS_BASE_URL.as_str(), query))
.send()
.await?
.json::<GetAllPosts>()
.await
}

/// Limit and skip posts
pub async fn limit_and_skip_posts(
&self,
limit: u32,
skip: u32,
selects: &str,
) -> Result<GetAllPosts, reqwest::Error> {
self.client
.get(format!(
"{}/?limit={}&skip={}&select={}",
POSTS_BASE_URL.as_str(),
limit,
skip,
selects
))
.send()
.await?
.json::<GetAllPosts>()
.await
}

/// Sort posts
pub async fn sort_posts(
&self,
sort_by: &str,
// TODO: Change to enum
order: &str,
) -> Result<GetAllPosts, reqwest::Error> {
self.client
.get(format!("{}/?sortBy={}&order={}", POSTS_BASE_URL.as_str(), sort_by, order))
.send()
.await?
.json::<GetAllPosts>()
.await
}

/// Get all posts tags
pub async fn get_all_posts_tags(&self) -> Result<Vec<ProductCategory>, reqwest::Error> {
self.client
.get(format!("{}/tags", POSTS_BASE_URL.as_str()))
.send()
.await?
.json::<Vec<ProductCategory>>()
.await
}

/// Get posts by tags
pub async fn get_posts_by_tags(&self, tag: &str) -> Result<GetAllPosts, reqwest::Error> {
self.client
.get(format!("{}/tag/{}", POSTS_BASE_URL.as_str(), tag))
.send()
.await?
.json::<GetAllPosts>()
.await
}

/// Get posts by user id
pub async fn get_posts_by_user_id(&self, user_id: u32) -> Result<GetAllPosts, reqwest::Error> {
self.client
.get(format!("{}/user/{}", POSTS_BASE_URL.as_str(), user_id))
.send()
.await?
.json::<GetAllPosts>()
.await
}

/// Get post comments
pub async fn get_post_comments(&self, id: u32) -> Result<PostCommentsResponse, reqwest::Error> {
self.client
.get(format!("{}/{}/comments", POSTS_BASE_URL.as_str(), id))
.send()
.await?
.json::<PostCommentsResponse>()
.await
}

/// Add post
pub async fn add_post(&self, post: &AddPost) -> Result<Post, reqwest::Error> {
self.client
.post(format!("{}/add", POSTS_BASE_URL.as_str()))
.json(post)
.send()
.await?
.json::<Post>()
.await
}

/// Update post
pub async fn update_post(&self, id: u32, post: &AddPost) -> Result<AddPost, reqwest::Error> {
self.client
.put(format!("{}/{}", POSTS_BASE_URL.as_str(), id))
.json(post)
.send()
.await?
.json::<AddPost>()
.await
}

/// Delete post
pub async fn delete_post(&self, id: u32) -> Result<Post, reqwest::Error> {
self.client
.delete(format!("{}/{}", POSTS_BASE_URL.as_str(), id))
.send()
.await?
.json::<Post>()
.await
}
}
Loading

0 comments on commit 95eb339

Please sign in to comment.