Skip to content

Commit

Permalink
Merge pull request #109 from bhaskarblur/main
Browse files Browse the repository at this point in the history
Setup Database , Added books, categories + books by categories APIs
  • Loading branch information
Karamraj authored Oct 8, 2023
2 parents 5c46ffe + ea64b84 commit 85bb6f8
Show file tree
Hide file tree
Showing 12 changed files with 802 additions and 2 deletions.
523 changes: 523 additions & 0 deletions bookTown-Nodejs/package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions bookTown-Nodejs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
"license": "ISC",
"dependencies": {
"@types/typescript": "^2.0.0",
"bcrypt": "^5.1.1",
"bcryptjs": "^2.4.3",
"compression": "^1.7.4",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
Expand All @@ -20,6 +22,7 @@
"helmet": "^7.0.0",
"mongodb": "^6.1.0",
"mongoose": "^7.5.3",
"mongoose-paginate": "^5.0.3",
"nodemon": "^3.0.1",
"ts-node": "^10.9.1",
"typescript": "^5.2.2"
Expand Down
67 changes: 67 additions & 0 deletions bookTown-Nodejs/src/controller/booksController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const booksHelper = require('../database/booksHelper');

export async function exploreBooks(req, res) {
try {
const pageSize = req.query.pageSize ? req.query.pageSize : 20;
const page = req.query.page ? req.query.page : 1;
const offSet = pageSize * page - pageSize;

const books = await booksHelper.exploreBooks(pageSize, offSet);

if(books.length > 0) {
res.status(200).json({"flag": true, "message":"All books", "result" : books})
}
else {
res.status(404).json({"flag": false, "message":"No books"})
}
}
catch(err) {
res.status(403).json({"flag":false, "message":err.message});
}
}

export async function booksByCategory(req, res) {
try {
const pageSize = req.query.pageSize ? req.query.pageSize : 20;
const page = req.query.page ? req.query.page : 1;
const offSet = pageSize * page - pageSize;
const category = req.query.categoryId;

const books = await booksHelper.booksByCategory(pageSize, offSet, category);

if(books.length > 0) {
res.status(200).json({"flag": true, "message":"All books", "result" : books})
}
else {
res.status(404).json({"flag": false, "message":"No books"})
}
}
catch(err) {
res.status(403).json({"flag":false, "message":err.message});
}
}


export async function addBook(req, res) {
try {
const title = req.body.title;
const desc = req.body.description;
const image = req.body.coverImage;
const rating = req.body.rating;
const price = req.body.price;
const categories = JSON.parse(req.body.categories);

const books = await booksHelper.addBook(title, desc, image, rating, price,categories)

if(books._id) {
res.status(200).json({"flag": true, "message":"Book added", "result" : books})
}
else {
res.status(404).json({"flag": false, "message":"Failed to add book, check that you're sending right and all body paramteres"})
}
}
catch(err) {
res.status(403).json({"flag":false, "message":err.message});
}
}

39 changes: 39 additions & 0 deletions bookTown-Nodejs/src/controller/categoriesController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const helper = require('../database/categoriesHelper');

export async function categoriesList(req, res) {
try {
const pageSize = req.query.pageSize ? req.query.pageSize : 20;
const page = req.query.page ? req.query.page : 1;
const offSet = pageSize * page - pageSize;

const categories = await helper.categoriesList(pageSize, offSet);

if(categories.length > 0) {
res.status(200).send({"flag": true, "message":"All categories", "result" : categories})
}
else {
res.status(404).send({"flag": false, "message":"No categories"})
}
}
catch(err) {
res.status(403).send({"flag":false, "message":err.message});
}
}

export async function addCategory(req, res) {
try {
const name = req.body.categoryName;

const cat = await helper.addCategory(name);

if(cat._id) {
res.status(200).json({"flag": true, "message":"Category added", "result" : cat})
}
else {
res.status(404).json({"flag": false, "message":"Failed to add category, check that you're sending right and all body paramteres"})
}
}
catch(err) {
res.status(403).json({"flag":false, "message":err.message});
}
}
30 changes: 30 additions & 0 deletions bookTown-Nodejs/src/database/booksHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
require('dotenv').config();
const booksModel = require('../models/booksModel');


export async function exploreBooks(pageSize, offset) {

return await booksModel.find().skip(offset).limit(pageSize);

}

export async function booksByCategory(pageSize, offset, category) {

return await booksModel.find({categories : category}).skip(offset).limit(pageSize);

}

export async function addBook(title, desc, image, rating, price,category) {
try {
const create = await booksModel.create({title: title, description: desc,
coverImage: image, rating: rating, price: price, categories: category})
console.log(create);
return create;

}
catch(err) {
console.log(err);
return err;
}

}
22 changes: 22 additions & 0 deletions bookTown-Nodejs/src/database/categoriesHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
require('dotenv').config()
const catModel = require('../models/categoriesModel');

export async function categoriesList(pageSize, offset) {

return await catModel.find().skip(offset).limit(pageSize);

}

export async function addCategory(name) {
try {
const create = await catModel.create({ categoryName: name })
console.log(create);
return create;

}
catch(err) {
console.log(err);
return err;
}

}
20 changes: 20 additions & 0 deletions bookTown-Nodejs/src/database/dbHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
require('dotenv').config()
import mongoose from "mongoose";

export function initDatabase() {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true
};

try {
const uri : any = process.env.MONGODB_URI
mongoose.connect(
uri);
console.log("Database connection established!")
}
catch (error) {
console.log(error);
}
}

10 changes: 8 additions & 2 deletions bookTown-Nodejs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import cookieParser from 'cookie-parser';
import cors from 'cors';
import express from 'express';
import helmet from 'helmet';
import * as books from './routes/books';
const dbClient = require('./database/dbHelper');
const PORT = process.env.PORT || 3000;
const app= express();

Expand All @@ -18,11 +20,15 @@ app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());

app.use('/v1',books.getRouter());

app.listen(PORT, () => {
console.log("Server listening on PORT", PORT);
dbClient.initDatabase();
});

app.get('/', (req, res) => {
res.status(200).send({"Message":"Welcome to BookTown, your server is setup successfully."});

app.get('/v1/', (req, res) => {
res.status(200).send({"message":"Welcome to BookTown, your server is setup successfully."});
})
30 changes: 30 additions & 0 deletions bookTown-Nodejs/src/models/booksModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate');

const booksScheme = new mongoose.Schema({
title: {
type: String,
required: true,
},
description : {
type: String,
required: true
},
coverImage : {
type : String,
required: true,
},
price : {
type : Number,
required : true
},
rating : {
type : Number
},
categories : {
type : Array<string>
}
}, { collection: 'Books'});

booksScheme.plugin(mongoosePaginate);
module.exports = mongoose.model('Books', booksScheme);
14 changes: 14 additions & 0 deletions bookTown-Nodejs/src/models/categoriesModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate');

const categoryScheme = new mongoose.Schema(
{
categoryName : {
type : String,
required: true,
}

}, { collection: 'Categories'});

categoryScheme.plugin(mongoosePaginate);
module.exports = mongoose.model('Categories', categoryScheme);
29 changes: 29 additions & 0 deletions bookTown-Nodejs/src/routes/books.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import express from 'express';
const router = express.Router();
const controller = require('../controller/booksController');
const catController = require('../controller/categoriesController');
var endPoint = '/books';

export function getRouter() {
return router;
}

router.get(endPoint+"/explore-books", async (req, res) => {
controller.exploreBooks(req, res)
})

router.get(endPoint+"/books-by-category", async (req, res) => {
controller.booksByCategory(req, res)
})

router.get(endPoint+"/categories", async (req, res) => {
catController.categoriesList(req, res)
})

router.post(endPoint+"/add-book", async (req, res) => {
controller.addBook(req, res)
})

router.post(endPoint+"/add-category", async (req, res) => {
catController.addCategory(req, res)
})
17 changes: 17 additions & 0 deletions bookTown-Nodejs/src/utils/authHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as bcrypt from 'bcrypt';

export const password = {
encryptPassword: (password: string) =>
bcrypt.genSalt(10)
.then((salt => bcrypt.hash(password, salt)))
.then(hash => hash),

checkPassword: (password: string, hashPassword: string) =>
bcrypt.compare(password, hashPassword)
.then(resp => resp)

}

export var generateRandomNumber = function (length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));
}

0 comments on commit 85bb6f8

Please sign in to comment.