Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
turivishal committed Oct 5, 2022
1 parent abb85c6 commit e6e6481
Show file tree
Hide file tree
Showing 26 changed files with 2,469 additions and 594 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ npm start
> [email protected] start
> node app.js
info: We are working on DEVELOPMENT environment and Listening on port 3000...
info: MongoDB connection succeeded!
info: We are working on DEVELOPMENT environment and Listening on port 3000... {"timestamp":"2022-10-05 16:57:19:551"}
info: MongoDB connection succeeded! {"timestamp":"2022-10-05 16:57:19:574"}
```
8) Open the link http://localhost:3000/api-docs in browser and it will open the swagger

Expand Down
6 changes: 1 addition & 5 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
require('dotenv').config();
const config = require('config');
const winston = require('winston');
const express = require('express');
const app = express();

// LOAD INITIALIZER
require('./util/general.helper').bootstrap('../initializer', [app, config, winston]);
require('./initializer');
6 changes: 4 additions & 2 deletions app/product/product.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ const ProductService = require("./product.service");
* operationId: productCreate
* tags:
* - Product
* consumes:
* - multipart/form-data
* produces:
* - application/json
* parameters:
* - $ref: '#/components/parameters/acceptLanguage'
* requestBody:
Expand Down Expand Up @@ -126,6 +126,8 @@ module.exports.search = async (req, res, next) => {
* operationId: productEdit
* tags:
* - Product
* produces:
* - application/json
* parameters:
* - $ref: '#/components/parameters/acceptLanguage'
* - name: productId
Expand Down
4 changes: 2 additions & 2 deletions app/product/product.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ module.exports = (router) => {
router.post(`/${route}`, Validate.request(Model, 'create'), controller.create);
router.get(`/${route}/:id`, Validate.validateObjectId(['id']), controller.read);
router.post(`/${route}/search`, Validate.request(Model, 'search'), controller.search);
router.put(`/${route}/:id`, [Validate.request(Model, 'update'), Validate.validateObjectId(['id'])], controller.update);
router.put(`/${route}/status/:id`, [Validate.request(Model, 'delete'), Validate.validateObjectId(['id'])], controller.delete);
router.put(`/${route}/:id`, [Validate.validateObjectId(['id']), Validate.request(Model, 'update')], controller.update);
router.put(`/${route}/status/:id`, [Validate.validateObjectId(['id']), Validate.request(Model, 'delete')], controller.delete);

}
4 changes: 2 additions & 2 deletions app/product/product.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ module.exports.create = async (data) => {

// READ
module.exports.read = async (id) => {
let responseData = await Product.Schema.findOne({ _id: Product.ObjectId(id) }, Product.SearchViewFields).lean();
let responseData = await Product.Schema.findById(id, Product.SearchViewFields).lean();
// FIND ONE
if (!responseData) return {
'status': false,
Expand Down Expand Up @@ -81,7 +81,7 @@ async function searchFilterAggregate(data) {

// UPDATE
module.exports.update = async (id, data) => {
let responseData = await MongoRepository.findOneAndUpdate(Product.Schema, { _id: id }, { $set: data }, { returnOriginal: false, new: true, useFindAndModify: false });
let responseData = await MongoRepository.findOneAndUpdate(Product.Schema, { _id: id }, { $set: data }, { returnOriginal: false, new: true });
if (!responseData) return {
'statusCode': 404,
'messageKey': `${msgpath}.not_found`,
Expand Down
1 change: 0 additions & 1 deletion app/product/product.validate.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const Joi = require("joi");
Joi.objectId = require('joi-objectid')(Joi)
const { MessageReader } = require("../../util/message.helper");
const MongoRepository = require("../../util/mongo.repository.helper");

Expand Down
19 changes: 6 additions & 13 deletions config/development.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,25 @@ mongodb:
post: 27017
db_name: "ProductLocal"
uris: "mongodb://localhost:27017/ProductLocal"
options:
useUnifiedTopology: true
useNewUrlParser: true
useCreateIndex: true
options: {}
collection_prefix: "product"
log:
enable: true
level: "error"
exception:
enable: true
dir: "logs"
filename: "uncaughtExceptions.log"
console_options:
colorize: true
prettyPrint: true
path: "logs/uncaughtExceptions.log"
level: "error"
rejection:
enable: true
logging:
enable: true
dir: "logs"
filename: "logfile.log"
db:
enable: false
collection: "product_log"
path: "logs/logfile.log"
level: "info"
options:
useUnifiedTopology: true
routes:
request:
raw:
Expand All @@ -48,7 +41,7 @@ routes:
limit: "100mb"
corsRoot:
check: false
origin: "domain.com"
origin: ["domain.com"] ## update your domain name, multiple allowed
cors:
origin: "*"
methods: "GET,HEAD,PUT,PATCH,POST,DELETE"
Expand Down
19 changes: 6 additions & 13 deletions config/production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,25 @@ mongodb:
post: 27017
db_name: "ProductProd"
uris: "mongodb://localhost:27017/ProductProd"
options:
useUnifiedTopology: true
useNewUrlParser: true
useCreateIndex: true
options: {}
collection_prefix: "product"
log:
enable: true
level: "error"
exception:
enable: true
dir: "logs"
filename: "uncaughtExceptions.log"
console_options:
colorize: true
prettyPrint: true
path: "logs/uncaughtExceptions.log"
level: "error"
rejection:
enable: true
logging:
enable: true
dir: "logs"
filename: "logfile.log"
db:
enable: false
collection: "product_log"
path: "logs/logfile.log"
level: "info"
options:
useUnifiedTopology: true
routes:
request:
raw:
Expand All @@ -48,7 +41,7 @@ routes:
limit: "100mb"
corsRoot:
check: false
origin: "domain.com"
origin: ["domain.com"] ## update your domain name, multiple allowed
cors:
origin: "*"
methods: "GET,HEAD,PUT,PATCH,POST,DELETE"
Expand Down
10 changes: 5 additions & 5 deletions initializer/db.initializer.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
const mongoose = require('mongoose');
const winston = require('winston').loggers.get('general');

module.exports = (app, config, winston) => {
module.exports = (app, config) => {

const mongodb = config.get('mongodb');

mongoose.connect(mongodb.uris, mongodb.options)
.then()
.catch(err => {
winston.log("error", "MongoDB connection failed, " + err);
// winston.info("MongoDB connection failed, error: " + JSON.stringify(err, undefined, 2));
winston.error("MongoDB connection failed, " + err);
//@ winston.info("MongoDB connection failed, error: " + JSON.stringify(err, undefined, 2));
});

mongoose.connection.once('open', () => {
// winston.info("MongoDB connection succeeded!");
//@ winston.info("MongoDB connection succeeded!");
});

mongoose.connection.on('connected', () => {
Expand All @@ -21,7 +22,6 @@ module.exports = (app, config, winston) => {

mongoose.connection.on('error', (err) => {
mongoose.disconnect();
// winston.info("MongoDB connection failed, error: " + err);
});

mongoose.connection.on('disconnected', () => {
Expand Down
2 changes: 1 addition & 1 deletion initializer/global.initializer.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = (app, config, winston) => {
module.exports = () => {

// SET RESPONSE HELPER
global.Response = require("../util/response.helper");
Expand Down
25 changes: 14 additions & 11 deletions initializer/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
module.exports = [
require("./global.initializer"),
require("./logging.initializer"),
require("./swagger.initializer"),
require("./language.initializer"),
require("./route.initializer"),
require("./db.initializer"),

// Put this at last step ...
require("./server.initializer")
];
const config = require('config');
const express = require('express');
const app = express();

require("./global.initializer")(app, config);
require("./validation.initializer")(app, config);
require("./logging.initializer")(app, config);
require("./swagger.initializer")(app, config);
require("./language.initializer")(app, config);
require("./route.initializer")(app, config);
require("./db.initializer")(app, config);

// Put this at last step ...
require("./server.initializer")(app, config);
3 changes: 1 addition & 2 deletions initializer/language.initializer.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@

module.exports = async (app, config, winston) => {
module.exports = async (app, config) => {

app.use((req, res, next) => {

Expand Down
67 changes: 21 additions & 46 deletions initializer/logging.initializer.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,26 @@
const fs = require('fs');
// require('winston-mongodb');
require('express-async-errors');

module.exports = (app, config, winston) => {

if (!config.get('log.enable')) return false;

// EXCEPTION
if (config.get('log.exception.enable')) {
const exception = config.get('log.exception');
!fs.existsSync(exception.dir) && fs.mkdirSync(exception.dir);
winston.handleExceptions(
new winston.transports.Console(exception.console_options),
new winston.transports.File({ filename: `${exception.dir}/${exception.filename}` })
);
}
const winston = require("winston");

module.exports = (app, config) => {

//@ { error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6 }
const log = config.get('log');
winston.loggers.add('general', {
format: winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:SSS' }),
winston.format.json()
),
transports: [
new winston.transports.Console({ level: log.logging.level, format: winston.format.simple() }),
new winston.transports.File({ filename: log.logging.path, level: log.logging.level }),
new winston.transports.File({ filename: log.exception.path, level: log.exception.level })
],
level: log.level,
silent: !config.get('log.enable'),
exitOnError: false
});

// UNHANDLED REJECTION
if (config.get('log.rejection.enable'))
process.on('unhandledRejection', (ex) => {
throw ex;
});

// LOGGING
if (config.get('log.logging.enable')) {
const logging = config.get('log.logging');
!fs.existsSync(logging.dir) && fs.mkdirSync(logging.dir);
winston.add(winston.transports.File, { filename: `${logging.dir}/${logging.filename}` });
}

// MONGO LOG CONNECTION
if (config.get('log.db.enable')) {
const db = config.get('log.db');
winston.add(winston.transports.MongoDB, {
db: config.get('mongodb.uris'),
collection: db.collection,
level: db.level,
options: db.options
});
}

// process.on('uncaughtException', function(error) {
// if(!error.isOperational) process.exit(1);
// });

// process.on('unhandledRejection', function(reason, p){
// console.log(reason, p);
// });
if (config.get('log.rejection.enable')) process.on('unhandledRejection', (ex) => { throw ex; });

}
21 changes: 16 additions & 5 deletions initializer/route.initializer.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
const express = require('express');
const router = express.Router();
const error = require('../middleware/error');
var cors = require('cors')
const cors = require('cors');
const compression = require('compression');

module.exports = async (app, config, winston) => {
// ENDS WITH ORIGIN CHECK
function endsWith(origin, origins) {
return origins.map((o) => origin.endsWith(o)).includes(true);
}

module.exports = async (app, config) => {

const routes = config.get('routes');

// ENABLE CORS
const corsMiddleware = cors(routes.cors);
if (routes.corsRoot && routes.corsRoot.check) {
app.use((req, res, next) => {
if (req.header('origin') && req.header('origin').endsWith(routes.corsRoot.origin))
if (req.header('origin') && endsWith(req.header('origin'), routes.corsRoot.origin))
return corsMiddleware(req, res, next);
else return next();
});
Expand All @@ -26,11 +32,16 @@ module.exports = async (app, config, winston) => {
app.use(express.urlencoded(routes.request.form_urlencoded.urlencoded_options));
}

// LOAD APP ROUTES
require('../util/general.helper').bootstrap('../app/app.route', [router]);
// SECURITY
app.disable('x-powered-by');
app.use(compression({ threshold: 0 })); // level: 6

// SET ROUTE
app.use('/api', router);

// LOAD APP ROUTES
require('../util/general.helper').bootstrap('../app/app.route', [router]);

// ERROR
app.use(error);

Expand Down
8 changes: 5 additions & 3 deletions initializer/server.initializer.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
module.exports = async (app, config, winston) => {
const winston = require('winston').loggers.get('general');

module.exports = async (app, config) => {

const port = process.env.PORT || config.get('server.port');
await app.listen(port, () => {
winston.info(`We are working on ${config.get('mode').toUpperCase()} environment and Listening on port ${port}...`)
})
.on("error", (err) => {
winston.log("error", err.message);
winston.error(err.message);
});

}
2 changes: 1 addition & 1 deletion initializer/swagger.initializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const router = express.Router();
const swaggerUi = require('swagger-ui-express');
const swaggerJSDoc = require('swagger-jsdoc');

module.exports = async (app, config, winston) => {
module.exports = async (app) => {

let jsDoc = swaggerJSDoc({
swaggerDefinition: {
Expand Down
5 changes: 5 additions & 0 deletions initializer/validation.initializer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const Joi = require('joi');

module.exports = () => {
Joi.objectId = require('joi-objectid')(Joi);
}
Loading

0 comments on commit e6e6481

Please sign in to comment.