Skip to content

Commit

Permalink
completed client side implementation (mongodb)
Browse files Browse the repository at this point in the history
  • Loading branch information
ksmooi committed Oct 28, 2024
1 parent f111aa3 commit 01d07c0
Show file tree
Hide file tree
Showing 3 changed files with 305 additions and 0 deletions.
75 changes: 75 additions & 0 deletions src/apps/mongodb_app/client/apiService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import axios, { AxiosInstance } from 'axios';

class ApiService {
private client: AxiosInstance;

constructor(baseURL: string) {
this.client = axios.create({
baseURL,
headers: {
'Content-Type': 'application/json',
},
});
}

// Create a new post
public async createPost(data: { title: string; content: string; author: string }) {
try {
const response = await this.client.post('/api/posts', data);
return response.data;
} catch (error: any) {
if (error.response) {
// Server responded with a status other than 2xx
throw new Error(`${error.response.data.message}: ${error.response.data.error}`);
} else if (error.request) {
// No response received
throw new Error('No response from server. Please check if the server is running.');
} else {
// Other errors
throw new Error(`Error creating post: ${error.message}`);
}
}
}

// Get all posts
public async getAllPosts() {
try {
const response = await this.client.get('/api/posts');
return response.data;
} catch (error: any) {
throw new Error(error.response?.data?.message || 'Error fetching posts');
}
}

// Get a post by ID
public async getPostById(id: string) {
try {
const response = await this.client.get(`/api/posts/${id}`);
return response.data;
} catch (error: any) {
throw new Error(error.response?.data?.message || 'Error fetching post');
}
}

// Update a post by ID
public async updatePost(id: string, data: { title?: string; content?: string; author?: string }) {
try {
const response = await this.client.put(`/api/posts/${id}`, data);
return response.data;
} catch (error: any) {
throw new Error(error.response?.data?.message || 'Error updating post');
}
}

// Delete a post by ID
public async deletePost(id: string) {
try {
const response = await this.client.delete(`/api/posts/${id}`);
return response.data;
} catch (error: any) {
throw new Error(error.response?.data?.message || 'Error deleting post');
}
}
}

export default ApiService;
218 changes: 218 additions & 0 deletions src/apps/mongodb_app/client/blogClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
// src/apps/blog_apps/client/blogClient.ts
import inquirer from 'inquirer';
import ApiService from './apiService';

interface Post {
_id: string;
title: string;
content: string;
author: string;
createdAt: string;
updatedAt: string;
}

class BlogClient {
private apiService: ApiService;

constructor(apiService: ApiService) {
this.apiService = apiService;
}

public async start() {
console.log('Welcome to the Blog Application CLI Client!\n');
let exit = false;
while (!exit) {
const { action } = await inquirer.prompt([
{
type: 'list',
name: 'action',
message: 'Select an action:',
choices: [
'Create a New Post',
'View All Posts',
'View a Post by ID',
'Update a Post',
'Delete a Post',
'Exit',
],
},
]);

switch (action) {
case 'Create a New Post':
await this.createPost();
break;
case 'View All Posts':
await this.viewAllPosts();
break;
case 'View a Post by ID':
await this.viewPostById();
break;
case 'Update a Post':
await this.updatePost();
break;
case 'Delete a Post':
await this.deletePost();
break;
case 'Exit':
exit = true;
console.log('Goodbye!');
break;
}
}
}

private async createPost() {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'title',
message: 'Enter the post title:',
validate: (input) => (input ? true : 'Title cannot be empty.'),
},
{
type: 'input',
name: 'content',
message: 'Enter the post content:',
validate: (input) => (input ? true : 'Content cannot be empty.'),
},
{
type: 'input',
name: 'author',
message: 'Enter the author name:',
validate: (input) => (input ? true : 'Author cannot be empty.'),
},
]);

try {
const newPost = await this.apiService.createPost(answers);
console.log('\nPost created successfully!');
console.log(newPost);
} catch (error: any) {
console.log(`\n${error.message}`);
}
}

private async viewAllPosts() {
try {
const posts: Post[] = await this.apiService.getAllPosts();
if (posts.length === 0) {
console.log('\nNo posts found.');
return;
}
console.log('\nAll Blog Posts:\n');
posts.forEach((post, index) => {
console.log(
`${index + 1}. ${post.title} by ${post.author} (ID: ${post._id})`
);
console.log(` Created At: ${post.createdAt}`);
console.log(` Updated At: ${post.updatedAt}\n`);
});
} catch (error: any) {
console.log(`\n${error.message}`);
}
}

private async viewPostById() {
const { id } = await inquirer.prompt([
{
type: 'input',
name: 'id',
message: 'Enter the Post ID:',
validate: (input) => (input ? true : 'Post ID cannot be empty.'),
},
]);

try {
const post: Post = await this.apiService.getPostById(id);
console.log('\nPost Details:\n');
console.log(`Title: ${post.title}`);
console.log(`Author: ${post.author}`);
console.log(`Content: ${post.content}`);
console.log(`Created At: ${post.createdAt}`);
console.log(`Updated At: ${post.updatedAt}\n`);
} catch (error: any) {
console.log(`\n${error.message}`);
}
}

private async updatePost() {
const { id } = await inquirer.prompt([
{
type: 'input',
name: 'id',
message: 'Enter the Post ID to update:',
validate: (input) => (input ? true : 'Post ID cannot be empty.'),
},
]);

try {
const post: Post = await this.apiService.getPostById(id);
if (!post) {
console.log('\nPost not found.');
return;
}

const answers = await inquirer.prompt([
{
type: 'input',
name: 'title',
message: `Enter new title (${post.title}):`,
default: post.title,
},
{
type: 'input',
name: 'content',
message: `Enter new content:`,
default: post.content,
},
{
type: 'input',
name: 'author',
message: `Enter new author (${post.author}):`,
default: post.author,
},
]);

const updatedPost = await this.apiService.updatePost(id, answers);
console.log('\nPost updated successfully!');
console.log(updatedPost);
} catch (error: any) {
console.log(`\n${error.message}`);
}
}

private async deletePost() {
const { id } = await inquirer.prompt([
{
type: 'input',
name: 'id',
message: 'Enter the Post ID to delete:',
validate: (input) => (input ? true : 'Post ID cannot be empty.'),
},
]);

const confirm = await inquirer.prompt([
{
type: 'confirm',
name: 'confirmDelete',
message: `Are you sure you want to delete the post with ID ${id}?`,
default: false,
},
]);

if (!confirm.confirmDelete) {
console.log('\nDeletion cancelled.');
return;
}

try {
await this.apiService.deletePost(id);
console.log('\nPost deleted successfully!');
} catch (error: any) {
console.log(`\n${error.message}`);
}
}
}

export default BlogClient;
12 changes: 12 additions & 0 deletions src/apps/mongodb_app/client/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// npx ts-node src/apps/mongodb_app/client/client.ts

import BlogClient from './blogClient';
import ApiService from './apiService';

const main = async () => {
const apiService = new ApiService('http://192.168.1.150:5001');
const blogClient = new BlogClient(apiService);
await blogClient.start();
};

main();

0 comments on commit 01d07c0

Please sign in to comment.