Skip to content

Commit

Permalink
feat: Additional dependencies such as qiu and logger are removed alon…
Browse files Browse the repository at this point in the history
…g with the document.

Added support for the load method from the object instead of the `.confmodule` file.
  • Loading branch information
m-mdy-m committed Sep 15, 2024
1 parent 9400d96 commit 0a30139
Show file tree
Hide file tree
Showing 14 changed files with 33 additions and 202 deletions.
9 changes: 1 addition & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
- **Modular Configuration**: Load and configure modules dynamically.
- **Middleware Support**: Easily add and manage middleware functions.
- **Routing**: Define routes using decorators for different HTTP methods.
- **Logging**: Integrate with the internal logger for customizable logging.
- **SQL Query Runner**: Utilize the internal query runner to interact with SQL databases.

## Installation

Expand Down Expand Up @@ -119,9 +117,4 @@ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file

## Contact

For any questions or further assistance, please reach out to us at [bitsgenix@gmail.com](mailto:bitsgenix@gmail.com).

## Links

- [Gland Logger](https://github.com/medishen/gland-logger)
- [Gland Qiu](https://github.com/medishen/gland-qiu)
For any questions or further assistance, please reach out to us at [bitsgenix@gmail.com](mailto:bitsgenix@gmail.com).
8 changes: 8 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,11 @@ Initial release with the following features:

### Documentation
- Added detailed documentation including FAQ, contributing guidelines, and security policy.

## [1.0.2] - 2024-09-15

### Added
- Currently, the load method accepts arguments in the form of objects and there is no need to load a file.

### Changed
- logger and qiu dependencies are removed along with their documents
72 changes: 0 additions & 72 deletions docs/documents/guides/1.getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,6 @@ To install `gland`, run the following command in your project directory:
npm install @medishn/gland
```

This will install `@medishn/gland` along with its internal dependencies:

- `@medishn/gland-logger` – for logging
- `@medishn/gland-qiu` – for SQL database querying

## Basic Application Setup

The following is a step-by-step guide to setting up a basic application using `gland`.
Expand Down Expand Up @@ -83,72 +78,6 @@ ts-node app.ts

Your web server will be running at `http://localhost:3000/`, and visiting this URL should return the message "Hello, world!".

## Using the Built-in Logger

`gland` integrates with the `@medishn/gland-logger` package, providing flexible logging capabilities. You can log messages to the console or files, and configure options like log level and file rotation.

### Example: Basic Logger Setup

In your application, configure the logger like this:

```typescript
import gland from '@medishn/gland';

const app = new gland();

// Logger options
const options = {
level: 'info', // Set the log level
transports: ['file', 'console'], // Log to both file and console
file: 'combined.log', // Log file path
rotation: {
maxSize: 1024 * 1024, // 1 MB max file size for rotation
},
};

const logger = new app.logger(options);

// Use the logger
logger.log('Server started', 'info'); // Logs an informational message
logger.log('An error occurred', 'error'); // Logs an error message
```

Logs will be written to the console and to the file specified in the `file` option (`combined.log` in this example).

## Using SQL Database Queries with Qiu

`gland` also includes `Qiu`, a query runner for interacting with SQL databases like MySQL, PostgreSQL, and MariaDB.

### Example: Connecting to a PostgreSQL Database

In your application, initialize the `Qiu` query runner and connect to a PostgreSQL database:

```typescript
import gland from '@medishn/gland';

const app = new gland();

// Initialize the Qiu query runner
const db = new app.Qiu('pg', 'postgresql://username:password@localhost:5432/mydatabase');

// Set the database to use
db.use('mydatabase');

// Run a query to fetch all users
async function getUsers() {
const users = await db.exec('SELECT * FROM users;');
console.log(users);
}

getUsers();
```

You can easily switch between different SQL databases by changing the database connection string in the `Qiu` constructor. For example, to use MySQL:

```typescript
const db = new app.Qiu('mysql', 'mysql://username:password@localhost:3306/mydatabase');
```

## Adding Middleware

`gland` supports middleware, which allows you to intercept and process requests before they reach your route handlers. You can define global middleware that applies to all routes or route-specific middleware.
Expand Down Expand Up @@ -183,6 +112,5 @@ Explore the [API Documentation](./api) for detailed information about the availa

### Next Steps

- Explore the [Examples](../examples) folder for more use cases.
- Learn how to add your own [Custom Middleware](./4.middleware.md).
- Dive into the [Routing System](./3.routing.md) for advanced routing features.
53 changes: 0 additions & 53 deletions docs/documents/guides/2.configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ This guide provides a detailed overview of the configuration options available i
- [Configuration Options](#configuration-options)
- [Server Configuration](#server-configuration)
- [Example](#example)
- [Logging Configuration](#logging-configuration)
- [Example](#example-1)
- [Database Configuration (Qiu)](#database-configuration-qiu)
- [Example](#example-2)
- [Loading Configuration](#loading-configuration)
- [Best Practices](#best-practices)

Expand Down Expand Up @@ -75,55 +71,6 @@ pattern=*.js
cacheModules=false
logLevel=debug
```

### Logging Configuration

Logging configuration defines how logs are captured, where they are stored, and how they are formatted. `gland` uses the `@medishn/gland-logger` package for logging, which can log to both the console and files with support for log rotation.

| Option | Type | Description | Default Value |
|------------------|---------|--------------------------------------------------------------------------------------|---------------|
| `logLevel` | String | Defines the log level (`info`, `warn`, `error`, `debug`). | `'info'` |
| `transports` | Array | Specifies where to log (`console`, `file`). | `['console']` |
| `file` | String | Path to the log file (e.g., `combined.log`). | `null` |
| `rotation` | Object | Configuration for log rotation, including `maxSize` for file size limits. | `null` |

#### Example

```json
{
"logLevel": "debug",
"transports": ["file", "console"],
"file": "app.log",
"rotation": {
"maxSize": 1048576 // 1MB
}
}
```

This configuration logs to both the console and a file (`app.log`). Log files are rotated when they exceed 1 MB in size.

### Database Configuration (Qiu)

`gland` includes built-in support for SQL databases via `Qiu`, which allows you to run SQL queries for databases like MySQL, PostgreSQL, and MariaDB.

| Option | Type | Description | Default Value |
|-------------|---------|----------------------------------------------------------------|---------------|
| `driver` | String | Database driver (`pg`, `mysql`, `mariadb`). | `'pg'` |
| `url` | String | Database connection URL (e.g., `postgresql://...`). | `null` |
| `dbName` | String | Name of the database to use. | `null` |

#### Example

```json
{
"driver": "mysql",
"url": "mysql://user:password@localhost:3306/mydatabase",
"dbName": "mydatabase",
}
```

In this example, `Qiu` connects to a MySQL database hosted locally, using a connection pool of 10 connections.

### Loading Configuration

You can load the configuration file (`.confmodule`) in your main application file using the `load()` method.
Expand Down
20 changes: 1 addition & 19 deletions docs/documents/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,7 @@

4. **Integrated Logger**: `gland` comes with an integrated logger from the `@medishn/gland-logger` package, allowing for seamless logging with customizable log levels. Whether logging to the console or implementing more advanced logging strategies, the logger provides robust support for tracking and debugging.

5. **SQL Database Support**: `gland` natively integrates with SQL databases (MySQL, PostgreSQL, MariaDB) via `@medishn/gland-qiu`. This query runner supports database interaction and simplifies common operations with SQL databases, making it easier to connect, query, and manage your database.

6. **Configuration through `.confmodule`**: The framework provides an easy-to-use configuration system that allows you to load routes, configure logging levels, and set middleware through a configuration module. This approach ensures flexibility and scalability for projects of any size.

7. **Task Queue**: `gland` includes an internal task queue system, allowing asynchronous tasks to be handled efficiently. This is ideal for handling complex tasks in the background without blocking the main event loop.

8. **Performance-Focused**: Optimized for performance, `gland` can process a high volume of requests with minimal overhead. Recent benchmarks show exceptional performance with low average response times, even under heavy loads.
5. **Performance-Focused**: Optimized for performance, `gland` can process a high volume of requests with minimal overhead. Recent benchmarks show exceptional performance with low average response times, even under heavy loads.

## Use Cases

Expand Down Expand Up @@ -63,18 +57,6 @@ export class Test {
}
```

## Internal Components

### **Logger (`@medishn/gland-logger`)**
`gland` uses an internal logger for detailed logging and debugging. The logger is highly customizable, allowing you to control log levels and output formatting. It supports features like file rotation and caching.

For more information, visit the [gland-logger repository](https://github.com/medishen/gland-logger).

### **SQL Query Runner (`@medishn/gland-qiu`)**
For applications requiring SQL database support, `gland` provides `Qiu`, an integrated SQL query runner that simplifies database interactions. It supports MySQL, PostgreSQL, and MariaDB.

For more details, see the [gland-qiu repository](https://github.com/medishen/gland-qiu).

## Conclusion

`@medishn/gland` is a versatile and efficient framework that helps developers build modern web applications with ease. Its modular design, performance optimizations, and built-in support for logging and database management make it an excellent choice for both small projects and large-scale enterprise applications.
2 changes: 1 addition & 1 deletion examples/app.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'path';
import gland from '../dist';
const g = new gland();
g.load(path.join(__dirname, '.confmodule'));
g.load({ path: path.join(__dirname, 'router') });
g.init(3000, () => {
console.log('server run on port 3000');
});
2 changes: 0 additions & 2 deletions lib/core/router/request.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { Factory } from '@medishn/gland-logger';
import { IncomingMessage } from 'http';
const logger = new Factory({ transports: ['console'], level: 'warn' });
const PROTO = IncomingMessage.prototype;
PROTO.json = function (): Promise<object | undefined> {
return new Promise((resolve, reject) => {
Expand Down
6 changes: 3 additions & 3 deletions lib/core/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { IncomingMessage, Server, ServerResponse, METHODS } from 'http';
import { Parser } from '../helper/Parser';
import { Gland, ListenArgs, NxtFunction } from '../types';
import { Gland, ListenArgs, ModuleConfig, NxtFunction } from '../types';
import { ServerUtils } from '../helper';
import { WebContext } from './context';
import { Router } from './router';
Expand Down Expand Up @@ -113,7 +113,7 @@ export class WebServer extends Server implements Gland.APP {
init(...args: ListenArgs): this {
return this.listen(...args);
}
async load(paths: string = './*.ts') {
await LoadModules.load(paths);
async load(conf: Partial<ModuleConfig> | string) {
await LoadModules.load(conf);
}
}
4 changes: 1 addition & 3 deletions lib/helper/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { METHODS } from 'http';
import { Gland } from '../types';
import { MidsFn } from '../types';
import { Factory } from '@medishn/gland-logger';
const logger = new Factory({ timestampFormat: 'locale', level: 'info', transports: ['console'] });
export namespace ServerUtils {
export function getMethod(): Array<string> {
return (
Expand All @@ -25,7 +23,7 @@ export namespace ServerUtils {
};
}
static log(opts: Gland.ListenOptions) {
logger.log(Tools.logMsg(opts), 'info');
console.log(Tools.logMsg(opts));
}
}
export function normalize(middleware: MidsFn | MidsFn[]): MidsFn[] {
Expand Down
23 changes: 16 additions & 7 deletions lib/helper/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,21 @@ export namespace LoadModules {

let config: ModuleConfig = defaultConfig;

export async function load(confPath: string) {
const configFile = path.resolve(confPath);
config = { ...defaultConfig, ...(await parseConfig(configFile)) };
const baseDir = path.join(path.dirname(configFile), config.path);
export async function load(conf: Partial<ModuleConfig> | string) {
let baseDir: string = '';
if (typeof conf === 'string') {
const configFile = path.resolve(conf);
const fileConfig = await parseConfig(configFile);
config = { ...defaultConfig, ...fileConfig };
baseDir = path.join(path.dirname(conf), config.path);
} else if (typeof conf === 'object') {
config = { ...defaultConfig, ...conf };
if (path.isAbsolute(config.path!)) {
baseDir = config.path!;
} else {
throw new Error(`Error: The directory '${conf.path}' does not exist or is invalid. Please provide a valid path.`);
}
}
const files = await findModules(baseDir, config.pattern!, config.recursive!);
const BATCH_SIZE = 10;
for (let i = 0; i < files.length; i += BATCH_SIZE) {
Expand Down Expand Up @@ -82,11 +93,9 @@ export namespace LoadModules {
}
return config;
}

// Queue-based file search with cache and worker thread support for faster searching
export async function findModules(directory: string, pattern: string, recursive: boolean): Promise<string[]> {
let fileList: string[] = [];
const queue: string[] = [directory]; // Use a queue to avoid recursive depth limits
const queue: string[] = [directory];
const fileCache: { [key: string]: boolean } = {};

while (queue.length) {
Expand Down
10 changes: 1 addition & 9 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { WebServer } from './core/server';
import { Qiu } from '@medishn/gland-qiu';
import { Factory } from '@medishn/gland-logger';
import { Context } from './types';
import { Route } from './core/decorators';
import { Delete, Get, Head, Options, Patch, Post, Put, All } from './core/router/index';
Expand All @@ -12,12 +10,6 @@ export default class gland extends WebServer {
constructor() {
super();
}
get Qiu() {
return Qiu;
}
get logger() {
return Factory;
}
}
export { Get, Post, Put, Delete, Patch, Head, Options, Route, mid, mids, All };
export var Gmid = Gmids.set;
export var Gmid = Gmids.set;
6 changes: 1 addition & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@medishn/gland",
"version": "1.0.1",
"version": "1.0.2",
"description": "Glands is a lightweight framework for Node.js designed for simplicity.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down Expand Up @@ -55,9 +55,5 @@
"sinon": "^19.0.0",
"ts-node": "^10.9.2",
"typescript": "^5.5.4"
},
"dependencies": {
"@medishn/gland-logger": "^1.0.3",
"@medishn/gland-qiu": "^1.0.1"
}
}
18 changes: 0 additions & 18 deletions pnpm-lock.yaml

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

Loading

0 comments on commit 0a30139

Please sign in to comment.