Skip to content

Commit

Permalink
Merge pull request #9 from AnkanSaha/dev
Browse files Browse the repository at this point in the history
Added - Added A Separate File for Connection to use New Features in c…
  • Loading branch information
AnkanSaha authored Jun 7, 2023
2 parents 508c0a2 + 615ba5c commit e3c21f2
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 32 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ const Connector = new mongoAlways.Mongo('MongoDB_URL', 'Log: true/false'); // Lo
## Methods
```javascript

Connector.connect() // Connects to MongoDB
Connector.SingleConnect() // Connects to MongoDB once and you can disconnect using Connector.disconnect()
Connector.alwaysConnect() // Connects to MongoDB and automatically reconnects if disconnected & you can't disconnect
Connector.disconnect() // Disconnects from MongoDB if connected whenever you want (Only works with SingleConnect())

```

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mongo-always",
"version": "2.3.5",
"version": "2.3.7",
"description": "mongo-always is a simple package that helps you to connect to your MongoDB database with Mongoose. It also helps you to keep your connection alive.",
"main": "./lib/Start.js",
"types":"./lib/Start.d.ts",
Expand Down
8 changes: 8 additions & 0 deletions src/Connect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { connect } from "mongoose"; // import the mongoose module

export default async function connectDB(MongoURL) {
await connect(MongoURL, {
useNewUrlParser: true,
useUnifiedTopology: true
}); // connect to the database
}; // create a function to connect to the database
87 changes: 60 additions & 27 deletions src/Start.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { connect, connection } from "mongoose"; // import the mongoose module
import connectDB from "./Connect"; // import the Connect function from the Connect.js file

// global types
type str = string;
Expand All @@ -7,12 +8,13 @@ type bool = boolean;
// class to run on start/* The above class is a TypeScript implementation of a MongoDB connection
// handler that can connect to a local or cloud server and listen for
// connection events. */

export class Mongo {
/* These are private properties of the `Mongo` class in TypeScript. */
private MongoURL: str;
private Log: bool;
private ConnectionState: str;
private MongoURL: str; // string value to store the URL of the MongoDB database to connect to
private Log: bool; // boolean value to check if the logging is enabled or not
private ConnectionState: str; // string value to check if the connection is to cloud or local
private connection: typeof connection; // mongoose connection type
private Connect: (MongoURL:str) => Promise<void>; // function to connect to the database

/**
* This is a constructor function that initializes properties for a MongoDB connection, including
Expand All @@ -25,39 +27,58 @@ export class Mongo {
* If set to false, no logging will occur.
*/
constructor(
MongoURL: str = "mongodb://localhost:27017/test",
Log: bool = true
MongoURL: str = "mongodb://localhost:27017/test", // default value is 'mongodb://localhost:27017/test'
Log: bool = true, // default value is true
) {
this.MongoURL = MongoURL;
this.Log = Log;
this.ConnectionState = "Local";
}
this.MongoURL = MongoURL; // assign the MongoURL property
this.Log = Log; // assign the Log property
this.ConnectionState = "Local"; // assign the ConnectionState property
this.connection = connection; // assign the connection property
this.Connect = connectDB; // assign the Connect property
} // end of constructor

/* The `connect()` method is a method of the `Mongo` class that connects to a MongoDB database using
the `connect()` function from the `mongoose` module. It also checks if the connection is to a cloud
or local server by checking if the `MongoURL` property includes the string "mongodb+srv". Finally,
it calls the `listen()` method to listen for events related to the database connection. */
// method to connect to the database
async connect() {
connect(this.MongoURL); // connect to the database
async SingleConnect() {
this.Connect(this.MongoURL); // connect to the database
this.MongoURL.includes("mongodb+srv")
? (this.ConnectionState = "Cloud")
: "Local"; // check if the connection is to cloud or local

this.Log === true
? console.log(
`MongoDB connected successfully with ${this.ConnectionState} Server`
)
: null;
} // end of SingleConnect method

// method to connect to the database and listen for events
async alwaysConnect(): Promise<void> {
this.Connect(this.MongoURL); // connect to the database
this.MongoURL.includes("mongodb+srv")
? (this.ConnectionState = "Cloud")
: "Local"; // check if the connection is to cloud or local
// listen for events
this.listen(); // listen for events
} // end of connect method
} // end of alwaysConnect method


/* The `private listen()` method is a method of the `Mongo` class that listens for events related to
the MongoDB database connection. It uses the `connection.on()` method from the `mongoose` module
to listen for three events: `connected`, `error`, and `disconnected`. */
private listen() {
connection.on("connected", async (): Promise<void> => {
this.connection.on("connected", async (): Promise<void> => {
this.Log === true
? console.log(
`MongoDB connected successfully with ${this.ConnectionState} Server`
)
: null;
}); // listen for connected event

connection.on("error", async (): Promise<void> => {
this.connection.on("error", async (): Promise<void> => {
this.Log === true
? console.log(" Error: MongoDB connection failed")
: null;
Expand All @@ -68,18 +89,30 @@ it calls the `listen()` method to listen for events related to the database conn
)
: null;
});
connection.on("disconnected", async (): Promise<void> => {
this.Log === true
? console.log(
`MongoDB disconnected with ${this.ConnectionState} Server and trying to reconnect`
)
: null;
await connect(this.MongoURL); // connect to the database
this.Log === true
? console.log(
`MongoDB reconnected successfully with ${this.ConnectionState} Server`
)
: null;
this.connection.on("disconnected", async (): Promise<void> => {
// check if the connection is to cloud or local
this.Log === true
? console.log(
`MongoDB disconnected with ${this.ConnectionState} Server and trying to reconnect`
)
: null;
await connect(this.MongoURL); // connect to the database
this.Log === true
? console.log(
`MongoDB reconnected successfully with ${this.ConnectionState} Server`
)
: null;
});
} // end of listen method

// method to disconnect from the database
async disconnect(): Promise<void> {
this.connection.close(); // disconnect from the database

this.Log === true
? console.log(
`MongoDB Disconnected successfully with ${this.ConnectionState} Server`
)
: null;
} // end of disconnect method
} // end of alwaysRun class
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

Expand Down

0 comments on commit e3c21f2

Please sign in to comment.