From 0a30139fe8e9edba494fdfa57147da587c3b9354 Mon Sep 17 00:00:00 2001 From: mahdi Date: Sun, 15 Sep 2024 19:38:22 +0330 Subject: [PATCH] feat: Additional dependencies such as qiu and logger are removed along with the document. Added support for the load method from the object instead of the `.confmodule` file. --- README.md | 9 +-- docs/CHANGELOG.md | 8 +++ docs/documents/guides/1.getting-started.md | 72 ---------------------- docs/documents/guides/2.configuration.md | 53 ---------------- docs/documents/overview.md | 20 +----- examples/app.ts | 2 +- lib/core/router/request.ts | 2 - lib/core/server.ts | 6 +- lib/helper/index.ts | 4 +- lib/helper/load.ts | 23 ++++--- lib/index.ts | 10 +-- package.json | 6 +- pnpm-lock.yaml | 18 ------ test/unit/core/server.spec.ts | 2 - 14 files changed, 33 insertions(+), 202 deletions(-) diff --git a/README.md b/README.md index eab73af..40c1acd 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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) \ No newline at end of file +For any questions or further assistance, please reach out to us at [bitsgenix@gmail.com](mailto:bitsgenix@gmail.com). \ No newline at end of file diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5410dc5..7864b76 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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 \ No newline at end of file diff --git a/docs/documents/guides/1.getting-started.md b/docs/documents/guides/1.getting-started.md index e030fff..7989867 100644 --- a/docs/documents/guides/1.getting-started.md +++ b/docs/documents/guides/1.getting-started.md @@ -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`. @@ -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. @@ -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. \ No newline at end of file diff --git a/docs/documents/guides/2.configuration.md b/docs/documents/guides/2.configuration.md index e89e69c..e2b9287 100644 --- a/docs/documents/guides/2.configuration.md +++ b/docs/documents/guides/2.configuration.md @@ -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) @@ -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. diff --git a/docs/documents/overview.md b/docs/documents/overview.md index ea93345..bfe57c0 100644 --- a/docs/documents/overview.md +++ b/docs/documents/overview.md @@ -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 @@ -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. \ No newline at end of file diff --git a/examples/app.ts b/examples/app.ts index 6b1d056..c45e35b 100644 --- a/examples/app.ts +++ b/examples/app.ts @@ -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'); }); diff --git a/lib/core/router/request.ts b/lib/core/router/request.ts index b046416..262ba91 100644 --- a/lib/core/router/request.ts +++ b/lib/core/router/request.ts @@ -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 { return new Promise((resolve, reject) => { diff --git a/lib/core/server.ts b/lib/core/server.ts index b511cdd..dd9eb57 100644 --- a/lib/core/server.ts +++ b/lib/core/server.ts @@ -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'; @@ -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 | string) { + await LoadModules.load(conf); } } diff --git a/lib/helper/index.ts b/lib/helper/index.ts index 4cb1f8e..173a77d 100644 --- a/lib/helper/index.ts +++ b/lib/helper/index.ts @@ -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 { return ( @@ -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[] { diff --git a/lib/helper/load.ts b/lib/helper/load.ts index 1d2f04b..896bc7f 100644 --- a/lib/helper/load.ts +++ b/lib/helper/load.ts @@ -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 | 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) { @@ -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 { 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) { diff --git a/lib/index.ts b/lib/index.ts index d33c4d0..ff8c53a 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -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'; @@ -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; \ No newline at end of file +export var Gmid = Gmids.set; diff --git a/package.json b/package.json index 0f609da..759e032 100644 --- a/package.json +++ b/package.json @@ -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", @@ -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" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d004b8e..41c3bca 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,13 +7,6 @@ settings: importers: .: - dependencies: - '@medishn/gland-logger': - specifier: ^1.0.3 - version: 1.0.3 - '@medishn/gland-qiu': - specifier: ^1.0.1 - version: 1.0.1 devDependencies: '@types/chai': specifier: ^4.3.19 @@ -59,13 +52,6 @@ packages: '@jridgewell/trace-mapping@0.3.9': resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} - '@medishn/gland-logger@1.0.3': - resolution: {integrity: sha512-+2V04pNSgr9rdH2rcNV9uj4dl+lUevc1ipNP/nXcc6EsBsN+9C1JWR3mbWuaT8AKKDPa61pLm6+2kT1ZU1C4ag==} - - '@medishn/gland-qiu@1.0.1': - resolution: {integrity: sha512-gJ6s+FY4z9Z32A08tjpLBoiDq4EhsRJkOBrSA5xmSj5XUESCQLXUCpaOaLkgre0noJ0vk9c8jTJcwotTBIM2hQ==} - engines: {node: '>= 20'} - '@sinonjs/commons@3.0.1': resolution: {integrity: sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==} @@ -502,10 +488,6 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.0 - '@medishn/gland-logger@1.0.3': {} - - '@medishn/gland-qiu@1.0.1': {} - '@sinonjs/commons@3.0.1': dependencies: type-detect: 4.0.8 diff --git a/test/unit/core/server.spec.ts b/test/unit/core/server.spec.ts index ed1109a..6ceeaa7 100644 --- a/test/unit/core/server.spec.ts +++ b/test/unit/core/server.spec.ts @@ -98,8 +98,6 @@ describe('WebServer', () => { }); describe('load()', () => { it('should call LoadModules.load with the correct path', async () => { - await server.load(); - expect(loadModulesLoadStub.calledOnceWith('./*.ts')).to.be.true; loadModulesLoadStub.resetHistory(); await server.load('./modules/*.ts'); expect(loadModulesLoadStub.calledOnceWith('./modules/*.ts')).to.be.true;