speedly 1.2.45 → 1.2.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,280 +1,171 @@
1
- # Speedly
1
+ **Overview**
2
2
 
3
- A powerful Node.js/TypeScript utility library that provides essential modules for rapid web application development, including authentication, database operations, file uploading, validation, and translation services.
3
+ - **Project**: `speedly` a lightweight express utility framework that bundles auth middlewares, database model handlers, file uploader helpers, request validators, API documentation loader and small utilities to speed up building REST APIs.
4
+ - **Entry point exports**: `auth`, `db`, `uploader`, `validator`, `models`, `modules`, `utils`, `document` (see below for details and examples).
4
5
 
5
- ## Features
6
+ **Quick Start**
6
7
 
7
- - 🔐 **Authentication System** - JWT-based authentication with role-based access control
8
- - 🗄️ **Database Management** - MongoDB/Mongoose integration with advanced query building
9
- - 📤 **File Upload Handler** - Multer-based file upload with automatic directory management
10
- - ✅ **Request Validation** - Yup-based schema validation for requests
11
- - 🌐 **Translation Service** - Multi-provider translation with caching support
12
- - 📦 **Dual Module Support** - Both CommonJS and ES Module exports
8
+ - **Install**: add the project to your workspace or import the package in your service.
9
+ - **Basic server skeleton**:
13
10
 
14
- ## Installation
15
-
16
- ```bash
17
- npm install speedly
18
- ```
19
-
20
- ## Quick Start
21
-
22
- ```typescript
23
- import { auth, db, uploader, validator } from 'speedly';
24
-
25
- // Initialize your Express app with Speedly modules
26
11
  ```
12
+ import express from 'express'
13
+ import { auth, db, uploader, validator, models, modules, utils, document } from './src'
27
14
 
28
- ## Modules
29
-
30
- ### 🔐 Authentication (`auth`)
15
+ const app = express();
16
+ app.use(express.json());
31
17
 
32
- Provides JWT-based authentication with customizable role management and middleware support.
18
+ // Mount example module router
19
+ app.use('/api/translation', modules.translation);
33
20
 
34
- ```typescript
35
- import { auth } from 'speedly';
21
+ // Swagger docs (served at /docs)
22
+ document(app, require('path').join(process.cwd(), 'src/modules'));
36
23
 
37
- // Configure authentication
38
- const authConfig = {
39
- admin: {
40
- role: 'ADMIN',
41
- model: '../models/admin'
42
- },
43
- jwtSecretEnv: 'JWT_KEY',
44
- customValidator: (req, key) => {
45
- // Custom validation logic
46
- return true;
47
- }
48
- };
49
-
50
- const authMiddleware = auth(authConfig);
51
-
52
- // Use in Express routes
53
- app.use('/admin', authMiddleware.useAuth);
24
+ app.listen(3000);
54
25
  ```
55
26
 
56
- ### 🗄️ Database (`db`)
57
-
58
- Advanced MongoDB operations with query building, pagination, and pipeline support.
59
-
60
- ```typescript
61
- import { db } from 'speedly';
62
-
63
- // Configure database
64
- const dbConfig = {
65
- dbType: "mongodb",
66
- path: "../models",
67
- dbEnv: "DB_URL",
68
- pagination: {
69
- quantity: 10,
70
- detailed: true
71
- }
72
- };
27
+ **Exports Reference**
28
+
29
+ **`auth`**
30
+
31
+ - **Type**: default export (object)
32
+ - **Purpose**: Provides simple express middlewares for access control. Each function returns an Express middleware that inspects the request using a configurable `customValidator` (from `getConfig('auth')`) and either allows, forbids or rejects the request.
33
+ - **API**:
34
+ - `auth.user()` → middleware that enforces a `user` access type.
35
+ - `auth.admin(config?)` middleware for admin access. Optionally pass `{ permission }` to require a specific admin permission (the middleware names themselves include the permission, e.g. `auth:admin:PERM`).
36
+ - `auth.any()` → middleware that accepts any authenticated-type logic configured by the `customValidator`.
37
+ - **Notes**: `auth` reads default options from `getConfig('auth')`. The `customValidator` should return truthy to allow or falsy to forbid; `null` is treated as unauthorized.
38
+
39
+ **`db`**
40
+
41
+ - **Type**: default export (factory function)
42
+ - **Purpose**: Creates Express middlewares that operate on a Mongoose model (or other model loaded from the `models` path). Designed to simplify CRUD endpoints by composing handler builders like `.find()`, `.create()`, `.findByIdAndUpdate()`, etc.
43
+ - **How to use**: call `db(collectionName, config?)` to get a model handler factory, then chain action methods and use the returned function as an Express middleware.
44
+ - **Common methods returned by `db('collection')`**:
45
+ - `.find(match = {})`
46
+ - `.create(body = {})`
47
+ - `.updateOne(match, body)`
48
+ - `.updateMany(match, body)`
49
+ - `.deleteOne(match)`
50
+ - `.deleteMany(match)`
51
+ - `.findOne(match)`
52
+ - `.findOneAndUpdate(match, body)`
53
+ - `.aggregate(pipeline)`
54
+ - `.findById(id)`
55
+ - `.findByIdAndUpdate(id, body)`
56
+ - `.findByIdAndDelete(id)`
57
+ - **Query behavior**: The produced middleware reads query params like `search`, `filters`, `sort`, `page`, `limit`, and `select` to modify results. Pagination behaviour can be controlled via `getConfig('db')` (e.g., `pagination.quantity`, `pagination.detailed`).
58
+ - **Config**: second argument allows overriding `{ path, type: 'internal'|'external', message }`. When `type` is `internal` the loader resolves models relative to the library; when `external` it resolves from the host app and `configs.path`.
59
+ - **Example**:
73
60
 
74
- // Use database operations
75
- // Supports complex queries, aggregation pipelines, and automatic pagination
76
61
  ```
62
+ // GET /api/translation -> finds translations
63
+ app.get('/api/translation', db('translation', { type: 'internal' }).find());
77
64
 
78
- ### 📤 File Upload (`uploader`)
79
-
80
- Multer-based file upload system with automatic directory creation and validation.
81
-
82
- ```typescript
83
- import { uploader } from 'speedly';
84
-
85
- // Configure uploader
86
- const uploadConfig = {
87
- saveInDb: false,
88
- prefix: "img_",
89
- limit: 5,
90
- format: /png|jpg|webp|jpeg/i
91
- };
92
-
93
- const upload = uploader("/uploads/images", uploadConfig);
94
-
95
- // Use in Express routes
96
- app.post('/upload', upload.single('file'), (req, res) => {
97
- // File uploaded successfully
98
- res.json({ mediaId: req.mediaId });
99
- });
65
+ // POST /api/translation -> create translation documents
66
+ app.post('/api/translation', db('translation', { type: 'internal' }).create());
100
67
  ```
101
68
 
102
- ### ✅ Validation (`validator`)
69
+ **`uploader`**
70
+
71
+ - **Type**: default export (factory)
72
+ - **Purpose**: Provides file uploading middlewares built on `multer` and convenience helpers that optionally save media metadata to a `media` collection.
73
+ - **Signature**: `uploader(destination = '/image', config?)` returns an object with methods `{ single, array, fields, any, none }` which are wrappers around multer handlers.
74
+ - **Config options** (defaults obtained from `getConfig('uploader')`):
75
+ - `saveInDb` (boolean) — whether to persist metadata in a `media` collection
76
+ - `prefix` (string) — prefix for saved filenames
77
+ - `limit` (number) — max upload size in MB
78
+ - `format` (RegExp) — allowed file extensions
79
+ - `path` (string) — base path to save files (default `../../../public` in library defaults)
80
+ - **Returned helpers**:
81
+ - `single(fieldName)` — middleware saving a single file and setting the file URL into `req.body[fieldName]`. If `saveInDb` is true it will store a doc in `media` and set `req.mediaId`.
82
+ - `array(fieldName, maxCount)` — accept multiple files and set an array of URLs into `req.body[fieldName]`.
83
+ - `fields(fieldsArray)` — accept mixed fields (multer-style field definitions).
84
+ - `any()` and `none()` — passthrough multer helpers.
85
+ - **Example**:
103
86
 
104
- Type-safe request validation using Yup schemas.
105
-
106
- ```typescript
107
- import { validator } from 'speedly';
108
- import * as yup from 'yup';
109
-
110
- // Define validation schema
111
- const userSchema = {
112
- body: yup.object({
113
- name: yup.string().required(),
114
- email: yup.string().email().required(),
115
- age: yup.number().min(18)
116
- }),
117
- params: yup.object({
118
- id: yup.string().required()
119
- }),
120
- query: yup.object({
121
- page: yup.number().default(1)
122
- })
123
- };
124
-
125
- // Use validation middleware
126
- app.post('/users/:id', validator(userSchema), (req, res) => {
127
- // req.body, req.params, req.query are now validated and typed
87
+ ```
88
+ app.post('/upload', uploader('/images').single('photo'), (req,res) => {
89
+ res.json({ url: req.body.photo });
128
90
  });
129
91
  ```
130
92
 
131
- ## Configuration
132
-
133
- Speedly uses a configuration system that allows you to customize each module. Create configuration files or use environment variables:
93
+ **`validator`**
134
94
 
135
- ### Environment Variables
95
+ - **Type**: default export (generic factory)
96
+ - **Purpose**: A small wrapper around `yup` to validate `req.body`, `req.params`, and `req.query`. On failure it forwards an error object to `next()` with `status: 405` and a message.
97
+ - **Signature**: `validator({ body?: yup.Schema, params?: yup.Schema, query?: yup.Schema })` returns an Express `RequestHandler`.
98
+ - **Behavior**: strips unknown fields, assigns validated values back to `req.body`, `req.params`, and `req.query`. The created middleware is annotated with `__validationSchema` (used by automatic documentation generator).
99
+ - **Example**:
136
100
 
137
- ```bash
138
- # Database
139
- DB_URL=mongodb://localhost:27017/myapp
140
-
141
- # JWT Secret
142
- JWT_KEY=your-secret-key
143
-
144
- # Translation API (optional)
145
- ONE_API_TOKEN=your-translation-api-token
146
- ```
147
-
148
- ### Configuration Files
149
-
150
- Create module-specific configuration by using the `getConfig` utility:
151
-
152
- ```typescript
153
- // Example configuration structure
154
- const config = {
155
- auth: {
156
- jwtSecretEnv: 'JWT_KEY',
157
- admin: { role: 'ADMIN' }
158
- },
159
- db: {
160
- dbType: 'mongodb',
161
- pagination: { quantity: 20 }
162
- },
163
- uploader: {
164
- limit: 10,
165
- format: /png|jpg|jpeg|webp|gif/i
166
- },
167
- translate: {
168
- one_api_token: process.env.ONE_API_TOKEN
169
- }
170
- };
171
- ```
172
-
173
- ## Advanced Usage
174
-
175
- ### Database Queries with Pipelines
176
-
177
- ```typescript
178
- // Complex aggregation pipeline example
179
- const queryState = {
180
- action: 'aggregate',
181
- match: { status: 'active' },
182
- pipeline: [
183
- { $lookup: { from: 'users', localField: 'userId', foreignField: '_id', as: 'user' } },
184
- { $unwind: '$user' },
185
- { $sort: { createdAt: -1 } }
186
- ]
187
- };
188
101
  ```
189
-
190
- ### Translation with Caching
191
-
192
- The translation module automatically caches translations and supports multiple providers:
193
-
194
- ```typescript
195
- import { translator } from 'speedly/dist/util/translator';
196
-
197
- // Translate text with automatic caching
198
- const translatedText = await translator("Hello World", "fa");
102
+ import * as yup from 'yup';
103
+ const schema = { body: yup.object({ text: yup.string().required() }) };
104
+ app.post('/translate', validator(schema), handler);
199
105
  ```
200
106
 
201
- ## API Reference
107
+ **`models`**
202
108
 
203
- ### Authentication Module
109
+ - **Type**: object containing Mongoose models
110
+ - **Currently included**:
111
+ - `translation` — Mongoose model with fields `{ text: String, lang: String, translatedText: String }` and timestamps.
112
+ - **Purpose**: Direct access to low-level models for custom operations (e.g., prefetch, caching or complex queries).
204
113
 
205
- - `auth(config)` - Creates authentication middleware
206
- - `useAuth` - Express middleware for route protection
114
+ **`modules`**
207
115
 
208
- ### Database Module
116
+ - **Type**: object of `express.Router` instances keyed by module name
117
+ - **Included**:
118
+ - `translation` — router defined in `src/modules/translation/translation.routes.ts` with routes:
119
+ - `GET /` → `db('translation', {type:'internal'}).find()`
120
+ - `POST /` → guarded by a simple body `auth` check inside the route and then `create()`
121
+ - `PUT /:id` → `auth.admin()` + `validator(...)` + `findByIdAndUpdate()`
122
+ - **Mounting**: `app.use('/api/translation', modules.translation)`
209
123
 
210
- - Supports MongoDB operations with Mongoose
211
- - Built-in pagination and query building
212
- - Aggregation pipeline support
124
+ **`utils`**
213
125
 
214
- ### Uploader Module
126
+ - **Type**: object of helper utilities
127
+ - **Included**:
128
+ - `translator` — a small translation helper that attempts multiple external translation providers and caches successful translations to the `translation` model. Signature: `translator(text = 'unspecified text', lang = 'fa') => Promise<string>`.
129
+ - **Behavior**: Normalizes text, looks up local cache (`translation` model), attempts external services (a worker proxy and optionally `one-api`), writes the result to DB, and returns the translated text. Falls back to the formatted original text on failure.
215
130
 
216
- - `uploader(destination, config)` - Creates multer upload middleware
217
- - Automatic directory creation
218
- - File format validation
131
+ **`document`**
219
132
 
220
- ### Validator Module
133
+ - **Type**: default export (function)
134
+ - **Purpose**: Scans `src/modules` routers and mounts a Swagger UI at `/docs` with automatically generated OpenAPI paths and basic security scheme.
135
+ - **Signature**: `document(app: Express, baseDir?: string)` — `baseDir` defaults to `path.join(process.cwd(), 'src/module')` in the loader. Use a correct path to your modules folder (e.g., `path.join(process.cwd(), 'src/modules')`).
136
+ - **What it detects**: routes, http methods, `yup` validation schemas (to document request bodies), and auth middlewares (to add security hints and descriptions).
221
137
 
222
- - `validator(schemas)` - Creates validation middleware
223
- - Type-safe validation with Yup
224
- - Supports body, params, and query validation
138
+ **Configuration & Environment**
225
139
 
226
- ## Dependencies
140
+ - Use `getConfig(key)` (internal) to supply runtime options for `auth`, `db`, `uploader`, and `translate` providers. Typical environment keys used by the modules:
141
+ - `JWT_KEY` (used by auth-related configs)
142
+ - `DB_URL` (database connection string if using external db config)
143
+ - `one_api_token` (optional token for the alternate translator provider)
227
144
 
228
- - **Express.js** - Web framework
229
- - **Mongoose** - MongoDB object modeling
230
- - **Multer** - File upload handling
231
- - **Yup** - Schema validation
232
- - **jsonwebtoken** - JWT authentication
233
- - **axios** - HTTP client
234
- - **translate** - Translation services
145
+ **Examples**
235
146
 
236
- ## Development
147
+ - Mounting everything in a small app:
237
148
 
238
- ### Building the Project
239
-
240
- ```bash
241
- # Build both CommonJS and ES modules
242
- npm run build
243
-
244
- # Build CommonJS only
245
- npm run build:cjs
246
-
247
- # Build ES modules only
248
- npm run build:esm
249
-
250
- # Development mode
251
- npm run dev
252
149
  ```
253
-
254
- ### Project Structure
255
-
150
+ import express from 'express';
151
+ import { modules, document } from './src';
152
+ import path from 'path';
153
+
154
+ const app = express();
155
+ app.use(express.json());
156
+ app.use('/api/translation', modules.translation);
157
+ document(app, path.join(process.cwd(), 'src/modules'));
158
+ app.listen(3000);
256
159
  ```
257
- src/
258
- ├── auth/ # Authentication module
259
- ├── db/ # Database operations
260
- ├── uploader/ # File upload handling
261
- ├── validator/ # Request validation
262
- ├── util/ # Utility functions
263
- └── model/ # Data models
264
- ```
265
-
266
- ## TypeScript Support
267
-
268
- Speedly is written in TypeScript and provides full type definitions. The package exports both CommonJS and ES modules for maximum compatibility.
269
-
270
- ## License
271
-
272
- MIT © MAHSERIN
273
160
 
274
- ## Contributing
161
+ **Developer Notes**
275
162
 
276
- Contributions are welcome! Please feel free to submit a Pull Request.
163
+ - `db` middleware attaches pagination, `search` and `filters` behavior using `req.query`. Use `type: 'internal'` when you want the model path resolved inside the package, or `external` to resolve from the consumer app.
164
+ - `validator` attaches `__validationSchema` to middlewares which `document` uses to generate OpenAPI schemas.
165
+ - `uploader` writes files to disk under the configured `path` and returns public URLs prefixed with `/static`.
277
166
 
278
- ## Support
167
+ If you'd like, I can also:
279
168
 
280
- For questions and support, please open an issue on the GitHub repository.
169
+ - add usage examples/tests around each exported function
170
+ - add API reference tables per-method for `db` handlers
171
+ - generate a small example express app under `examples/` using these exports
@@ -126,6 +126,54 @@ function routeAnalyzer(route, routerName) {
126
126
  };
127
127
  }
128
128
  }
129
+ // Response
130
+ doc.responses = {
131
+ "200": {
132
+ content: {
133
+ "application/json": {
134
+ schema: {
135
+ type: "object",
136
+ properties: {
137
+ message: { type: "string", example: "find successfully" },
138
+ content: {
139
+ oneOf: [
140
+ {
141
+ type: "array",
142
+ items: {
143
+ type: "object",
144
+ properties: {
145
+ id: { type: "string" },
146
+ name: { type: "string" },
147
+ },
148
+ },
149
+ },
150
+ {
151
+ type: "object",
152
+ properties: {
153
+ id: { type: "string" },
154
+ name: { type: "string" },
155
+ },
156
+ },
157
+ ],
158
+ },
159
+ },
160
+ },
161
+ },
162
+ },
163
+ },
164
+ "400": {
165
+ content: {
166
+ "application/json": {
167
+ schema: {
168
+ type: "object",
169
+ properties: {
170
+ message: { type: "string", example: "module not found" },
171
+ },
172
+ },
173
+ },
174
+ },
175
+ },
176
+ };
129
177
  // Auth
130
178
  const auth = getAuthStatus(detail.middlewares);
131
179
  if (auth.type === "required") {
@@ -126,6 +126,54 @@ function routeAnalyzer(route, routerName) {
126
126
  };
127
127
  }
128
128
  }
129
+ // Response
130
+ doc.responses = {
131
+ "200": {
132
+ content: {
133
+ "application/json": {
134
+ schema: {
135
+ type: "object",
136
+ properties: {
137
+ message: { type: "string", example: "find successfully" },
138
+ content: {
139
+ oneOf: [
140
+ {
141
+ type: "array",
142
+ items: {
143
+ type: "object",
144
+ properties: {
145
+ id: { type: "string" },
146
+ name: { type: "string" },
147
+ },
148
+ },
149
+ },
150
+ {
151
+ type: "object",
152
+ properties: {
153
+ id: { type: "string" },
154
+ name: { type: "string" },
155
+ },
156
+ },
157
+ ],
158
+ },
159
+ },
160
+ },
161
+ },
162
+ },
163
+ },
164
+ "400": {
165
+ content: {
166
+ "application/json": {
167
+ schema: {
168
+ type: "object",
169
+ properties: {
170
+ message: { type: "string", example: "module not found" },
171
+ },
172
+ },
173
+ },
174
+ },
175
+ },
176
+ };
129
177
  // Auth
130
178
  const auth = getAuthStatus(detail.middlewares);
131
179
  if (auth.type === "required") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "speedly",
3
- "version": "1.2.45",
3
+ "version": "1.2.47",
4
4
  "main": "dist/cjs/index.js",
5
5
  "module": "dist/esm/index.js",
6
6
  "types": "dist/esm/index.d.ts",