Skip to content

Commit

Permalink
converted project to use ES6 modules
Browse files Browse the repository at this point in the history
  • Loading branch information
MohammedArab1 committed Jun 11, 2024
1 parent 3335425 commit 1136c7e
Show file tree
Hide file tree
Showing 8 changed files with 1,076 additions and 115 deletions.
41 changes: 22 additions & 19 deletions API/src/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
require("dotenv").config();
const express = require("express");
const cors = require("cors");
// require("dotenv").config();
import dotenv from 'dotenv';
dotenv.config()
import express, { json } from "express";
import cors from "cors";
const app = express();
const HadithModel = require("../../V1/DB/models/hadith");
const BookNamesModel = require("../../V1/DB/models/bookName");
const HadithModelV2 = require("../../V2/DB/models/hadithV2.js")
const BookNamesModelV2 = require("../../V2/DB/models/bookNameV2.js")
const utils = require("./utils.js");
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
import HadithModel from "../../V1/DB/models/hadith.js";
import BookNamesModel from "../../V1/DB/models/bookName.js";
import HadithModelV2 from "../../V2/DB/models/hadithV2.js";
import BookNamesModelV2 from "../../V2/DB/models/bookNameV2.js";
import { compareAlphabetically, escapeRegExp, returnBookIds } from "./utils.js";
import swaggerJsdoc from 'swagger-jsdoc';
import { serve, setup } from 'swagger-ui-express';
// import server from "./graphql.js";

const invalidId =
"no hadith with given id. Please make sure you have an ID within the appropriate range. Use endpoint /api/allbooks for min and max id range for any given book";
const invalidBook =
"The book you have provided does not exist. Please use endpoint /api/allbooks for a list of all books.";

app.use(express.json());
app.use(json());
app.use(cors());

app.get("/", (req, res) => {
Expand All @@ -34,7 +37,7 @@ var allBooksHandler= (model) => {
return async (request, response) => {
const bookNames = await model.find({}, { _id: 0, __v: 0 });
bookNames.sort((a, b) => {
return utils.compareAlphabetically(a.bookId, b.bookId);
return compareAlphabetically(a.bookId, b.bookId);
});
return response.json(bookNames);
}
Expand Down Expand Up @@ -117,7 +120,7 @@ var queryHandler = (model) => {
};
return response.status(400).json(error);
} else {
const escapedQuery = utils.escapeRegExp(query);
const escapedQuery = escapeRegExp(query);
const $regex = new RegExp(escapedQuery, "i");
const englishQueryResults = await model.find(
{ englishText: { $regex } },
Expand Down Expand Up @@ -188,7 +191,7 @@ app.get("/api/v2/query", queryHandler(HadithModelV2))
//The following endpoint takes a query and fetches from a particular book. Can handle both english and arabic queries
var queryPerBookHandler = (model) =>{
return async (request, response) => {
const listOfBooks = await utils.returnBookIds();
const listOfBooks = await returnBookIds();
const query = request.query.q;
if (!query) {
const error = {
Expand All @@ -200,7 +203,7 @@ var queryPerBookHandler = (model) =>{
} else if (!listOfBooks.includes(request.params.bookId)) {
return response.status(400).json({ error: invalidBook });
} else {
const escapedQuery = utils.escapeRegExp(query);
const escapedQuery = escapeRegExp(query);
const $regex = new RegExp(escapedQuery);
const englishQueryResults = await model.find(
{ englishText: { $regex }, bookId: request.params.bookId },
Expand Down Expand Up @@ -302,7 +305,7 @@ app.get("/api/v2/query/:bookId", queryPerBookHandler(HadithModelV2))
//Returns all the hadiths from a specific book
var bookHandler = (model) => {
return async (request, response) => {
const listOfBooks = await utils.returnBookIds();
const listOfBooks = await returnBookIds();
if (!listOfBooks.includes(request.params.bookId)) {
return response.status(400).json({ error: invalidBook });
} else {
Expand Down Expand Up @@ -362,7 +365,7 @@ app.get("/api/v2/:bookId",bookHandler(HadithModelV2))
// Returns a random hadith from a given book
var randomBookHadithHandler = (model) => {
return async (request, response) => {
const listOfBooks = await utils.returnBookIds();
const listOfBooks = await returnBookIds();
const filter = { bookId: request.params.bookId };
if (!listOfBooks.includes(request.params.bookId)) {
return response.status(400).json({ error: invalidBook });
Expand Down Expand Up @@ -419,7 +422,7 @@ app.get("/api/v2/:bookId/random",randomBookHadithHandler(HadithModelV2))
// returns a specific hadith (not very useful in my opinion but needs refining)
var oneHadithHandler = (model) => {
return async (request, response) => {
const listOfBooks = await utils.returnBookIds();
const listOfBooks = await returnBookIds();
if (isNaN(request.params.id)) {
return response.status(400).json({ error: "Invalid Id" });
} else {
Expand Down Expand Up @@ -506,7 +509,7 @@ const options = {
apis: ['./API/src/index*.js'], // files containing annotations as above
};
const openapiSpecification = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(openapiSpecification));
app.use('/api-docs', serve, setup(openapiSpecification));

const dev = process.argv.indexOf('--dev');
if (dev > -1){
Expand Down
27 changes: 13 additions & 14 deletions API/src/utils.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
const BookNamesModel = require("../../V1/DB/models/bookName")
import BookNamesModel from '../../V1/DB/models/bookName.js';

const escapeRegExp = (string) => {
return string.toString().replace(/[.*+?^${}|()[\]\\]/g, "\\$&"); // $& means the whole matched string
export const escapeRegExp = (string) => {
return string.toString().replace(/[.*+?^${}|()[\]\\]/g, '\\$&'); // $& means the whole matched string
};
const returnBookIds = async () => {
const bookNames = await BookNamesModel.find({});
return bookNames.map((book) => {
return book["bookId"];
});
export const returnBookIds = async () => {
const bookNames = await BookNamesModel.find({});
return bookNames.map((book) => {
return book['bookId'];
});
};


const compareAlphabetically = (a, b) => {
a = a.toLowerCase();
b = b.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
export const compareAlphabetically = (a, b) => {
a = a.toLowerCase();
b = b.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
};

module.exports = { escapeRegExp, returnBookIds, compareAlphabetically };
// export default { escapeRegExp, returnBookIds, compareAlphabetically };
59 changes: 32 additions & 27 deletions V1/DB/models/bookName.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
require('dotenv').config()
const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
// require('dotenv').config();
import dotenv from 'dotenv';
dotenv.config()
import { connect, model, Schema } from 'mongoose';
const url = process.env.MONGODB_URI;

mongoose.connect(url)
.then(result => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connecting to MongoDB:', error.message)
})
connect(url)
.then((result) => {
console.log('connected to MongoDB');
})
.catch((error) => {
console.log('error connecting to MongoDB:', error.message);
});

const bookName = new mongoose.Schema({
bookId: String,
BookName: String,
author:String,
idRangeMin:Number,
idRangeMax:Number
}, {
strict:false
})
const bookName = new Schema(
{
bookId: String,
BookName: String,
author: String,
idRangeMin: Number,
idRangeMax: Number,
},
{
strict: false,
}
);

bookName.set('toJson', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
}
})
bookName.set('toJson', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
},
});

module.exports = mongoose.model('bookNames', bookName, 'bookNames')
export default model('bookNames', bookName, 'bookNames');
14 changes: 8 additions & 6 deletions V1/DB/models/hadith.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
require('dotenv').config()
const mongoose = require('mongoose')
const random = require('mongoose-simple-random')
// require('dotenv').config()
import dotenv from 'dotenv';
dotenv.config()
import { connect, Schema, model } from 'mongoose'
import random from 'mongoose-simple-random'
const url = process.env.MONGODB_URI

mongoose.connect(url)
connect(url)
.then(result => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connecting to MongoDB:', error.message)
})

const hadithSchema = new mongoose.Schema({
const hadithSchema = new Schema({
id: Number,
bookId: String,
book:String,
Expand Down Expand Up @@ -40,4 +42,4 @@ mongoose.connect(url)
}
})

module.exports = mongoose.model('AllBooks', hadithSchema, 'AllBooks')
export default model('AllBooks', hadithSchema, 'AllBooks')
59 changes: 32 additions & 27 deletions V2/DB/models/bookNameV2.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
require('dotenv').config()
const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
// require('dotenv').config();
import dotenv from 'dotenv';
dotenv.config()
import { connect, model, Schema } from 'mongoose';
const url = process.env.MONGODB_URI;

mongoose.connect(url)
.then(result => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connecting to MongoDB:', error.message)
})
connect(url)
.then((result) => {
console.log('connected to MongoDB');
})
.catch((error) => {
console.log('error connecting to MongoDB:', error.message);
});

const bookNameV2 = new mongoose.Schema({
bookId: String,
BookName: String,
author:String,
idRangeMin:Number,
idRangeMax:Number
}, {
strict:false
})
const bookNameV2 = new Schema(
{
bookId: String,
BookName: String,
author: String,
idRangeMin: Number,
idRangeMax: Number,
},
{
strict: false,
}
);

bookNameV2.set('toJson', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
}
})
bookNameV2.set('toJson', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
},
});

module.exports = mongoose.model('bookNamesV2', bookNameV2, 'bookNamesV2')
export default model('bookNamesV2', bookNameV2, 'bookNamesV2');
14 changes: 8 additions & 6 deletions V2/DB/models/hadithV2.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
require('dotenv').config()
const mongoose = require('mongoose')
const random = require('mongoose-simple-random')
// require('dotenv').config()
import dotenv from 'dotenv';
dotenv.config()
import { connect, Schema, model } from 'mongoose'
import random from 'mongoose-simple-random'
const url = process.env.MONGODB_URI

mongoose.connect(url)
connect(url)
.then(result => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connecting to MongoDB:', error.message)
})

const hadithSchemaV2 = new mongoose.Schema({
const hadithSchemaV2 = new Schema({
id: Number,
bookId: String,
book:String,
Expand Down Expand Up @@ -40,4 +42,4 @@ mongoose.connect(url)
}
})

module.exports = mongoose.model('AllBooksV2', hadithSchemaV2, 'AllBooksV2')
export default model('AllBooksV2', hadithSchemaV2, 'AllBooksV2')
Loading

0 comments on commit 1136c7e

Please sign in to comment.