database-connector 1.1.0 → 2.0.1

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/CHANGELOG.md CHANGED
@@ -1,18 +1,53 @@
1
1
  # Changelog - Database Connector Models Refactoring
2
2
 
3
- ## [Unreleased] - 2025-12-07
3
+ ## 2025-12-08
4
4
 
5
5
  ### Added
6
+
7
+ #### Configuration & Documentation
8
+ - **Configuration Module**: Added `config.js` to allow runtime configuration of the package
9
+ - Enables consuming applications to set base URL for image path virtualization
10
+ - Configurable default image paths for products and stores
11
+ - Exports `configure()` and `getConfig()` functions from main index
12
+
13
+ - **README.md**: Added comprehensive documentation
14
+ - Installation and setup instructions
15
+ - Configuration guide with examples
16
+ - Complete model list and descriptions
17
+ - Virtual properties documentation
18
+ - Usage examples for common scenarios
19
+
20
+ - **package.json**: Updated package metadata
21
+ - Version bumped to 1.2.0
22
+ - Added package description
23
+ - Added relevant keywords for npm discoverability
24
+ - Added files array to specify package contents
25
+ - Added example script for running examples
26
+
27
+ #### Swagger/OpenAPI Documentation
6
28
  - **Swagger JSDoc Documentation**: Added comprehensive Swagger/OpenAPI documentation to all 25 models
7
29
  - Each model now includes detailed schema definitions with property types, descriptions, and examples
8
30
  - Documentation follows OpenAPI 3.0 standards for easy API documentation generation
31
+ - Component schema definitions with required fields specifications
32
+ - Property types and descriptions with nested object structures
33
+ - Enum values for restricted fields and default values
34
+ - Format specifications (date-time, etc.) and example data for each model
9
35
 
10
36
  - **Policy Model Export**: Converted `Policy.js` from schema-only export to a full standalone model
11
37
  - Now exports both `policySchema` (for embedding) and `Policy` model (for standalone use)
12
38
  - Maintains backward compatibility with existing code using `policySchema`
39
+ - Added `model` import from mongoose
13
40
 
14
41
  ### Changed
15
42
 
43
+ #### Model Updates for Configuration
44
+ - **Product Model**: Updated to use config module instead of `process.env.APP_URL`
45
+ - Virtual property `imagesss` now uses `getBaseURL()`
46
+ - Virtual property `variantImages` now uses `getBaseURL()` and `getDefaultImagePath()`
47
+
48
+ - **Store Model**: Updated to use config module instead of `process.env.APP_URL`
49
+ - Virtual property `imageUrl` now uses `getBaseURL()` and `getDefaultStoreImagePath()`
50
+
16
51
  #### Code Organization & Cleanup
17
52
 
18
53
  **Removed Unused Imports:**
@@ -88,84 +123,39 @@
88
123
  - Provided clear instructions for enabling if needed
89
124
 
90
125
  13. **Policy.js**
91
- - Added `model` import from mongoose
92
126
  - Converted to export both schema and standalone model
93
127
  - Maintains backward compatibility
94
128
 
129
+ ### Fixed
130
+ - **Environment Variables**: Resolved issue with `process.env` not working in npm packages
131
+ - Package now properly handles configuration from consuming applications
132
+ - No longer relies on environment variables being available in package context
133
+
95
134
  ### Maintained
96
- - **All Commented Code**: Preserved all commented code as requested, with improved formatting
135
+ - **All Commented Code**: Preserved all commented code with improved formatting
97
136
  - **Backward Compatibility**: All existing imports and usage patterns remain functional
98
137
  - **Schema Definitions**: No changes to actual schema structures or validations
99
138
  - **Model Exports**: All models maintain their existing export patterns
100
139
 
101
- ### Documentation
102
-
103
- #### Models with Complete Swagger Documentation:
104
- 1. Bill
105
- 2. Cart
106
- 3. Category
107
- 4. FlashDeal
108
- 5. Notification
109
- 6. Offer
110
- 7. Order
111
- 8. OrderOld (Legacy)
112
- 9. Payment
113
- 10. PaymentType
114
- 11. Plan
115
- 12. Policy
116
- 13. Product
117
- 14. ReductionOffer
118
- 15. ResetPassword
119
- 16. Sale
120
- 17. Store
121
- 18. StoreCategory
122
- 19. StoreRate
123
- 20. Subscription
124
- 21. SubscriptionOffer
125
- 22. User
126
- 23. UserAction
127
- 24. View
128
-
129
- ### Technical Details
130
-
131
- **Swagger Documentation Includes:**
132
- - Component schema definitions
133
- - Required fields specifications
134
- - Property types and descriptions
135
- - Nested object structures
136
- - Enum values for restricted fields
137
- - Default values
138
- - Format specifications (date-time, etc.)
139
- - Example data for each model
140
+ ---
141
+
142
+ ## Summary
143
+
144
+ **Models with Complete Swagger Documentation (24 total):**
145
+ Bill, Cart, Category, FlashDeal, Notification, Offer, Order, OrderOld (Legacy), Payment, PaymentType, Plan, Policy, Product, ReductionOffer, ResetPassword, Sale, Store, StoreCategory, StoreRate, Subscription, SubscriptionOffer, User, UserAction, View
140
146
 
141
147
  **Code Quality Improvements:**
142
148
  - ✅ Zero linting errors
143
- - ✅ Consistent formatting
144
- - ✅ Removed all unused dependencies
149
+ - ✅ Consistent formatting across all models
150
+ - ✅ Removed 8 unused dependencies
145
151
  - ✅ Proper documentation for all virtual properties
146
152
  - ✅ Clean, readable code structure
147
153
 
148
- ### Migration Notes
149
-
150
- **No Breaking Changes**: All changes are backward compatible. Existing code will continue to work without modifications.
151
-
152
- **Policy Model**: If you were previously importing `policySchema`:
153
- ```javascript
154
- // Old way (still works)
155
- const { policySchema } = require('./models/Policy');
154
+ **Files Modified:** 24 model files + 1 new CHANGELOG.md + 1 new config.js + 1 new README.md
156
155
 
157
- // New way (also available)
158
- const Policy = require('./models/Policy');
159
- const { policySchema } = require('./models/Policy');
160
- ```
161
-
162
- ### Files Modified
163
- - 24 model files updated with Swagger documentation and refactoring
164
- - 1 new file created (CHANGELOG.md)
165
-
166
- ---
156
+ **Total Lines of Documentation Added:** ~1,800+
167
157
 
168
- **Total Models Documented**: 24
169
- **Total Lines of Documentation Added**: ~1,800+
170
- **Unused Imports Removed**: 8
171
- **Code Quality**: Excellent
158
+ **Migration Notes:**
159
+ - No breaking changes - all changes are backward compatible
160
+ - Policy model now exports both `policySchema` and `Policy` model
161
+ - Product and Store models now use config module for URL virtualization
package/README.md ADDED
@@ -0,0 +1,194 @@
1
+ # Database Connector Package
2
+
3
+ MongoDB models package with Mongoose schemas for e-commerce application.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install database-connector
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Basic Setup
14
+
15
+ ```javascript
16
+ const { connectToDatabase, configure, User, Product, Store } = require('database-connector');
17
+
18
+ // Configure the package (IMPORTANT: Do this before using models)
19
+ configure({
20
+ baseURL: process.env.APP_URL || 'http://localhost:3000',
21
+ defaultImagePath: '/images/default.png',
22
+ defaultStoreImagePath: '/images/stores/default.jpg'
23
+ });
24
+
25
+ // Connect to database
26
+ await connectToDatabase(process.env.MONGODB_URI);
27
+
28
+ // Use models
29
+ const user = await User.findById(userId);
30
+ const products = await Product.find({ storeId });
31
+ ```
32
+
33
+ ### Configuration
34
+
35
+ **Important:** You must configure the package before using any models that have virtual properties for image URLs (Product and Store models).
36
+
37
+ ```javascript
38
+ const { configure } = require('database-connector');
39
+
40
+ configure({
41
+ baseURL: 'https://api.yourdomain.com', // Your API base URL
42
+ defaultImagePath: '/images/default.png', // Default product image
43
+ defaultStoreImagePath: '/images/stores/default.jpg' // Default store image
44
+ });
45
+ ```
46
+
47
+ #### Configuration Options
48
+
49
+ | Option | Type | Default | Description |
50
+ |--------|------|---------|-------------|
51
+ | `baseURL` | string | `process.env.APP_URL` or `'http://localhost:3000'` | Base URL for constructing image URLs |
52
+ | `defaultImagePath` | string | `'/images/default.png'` | Default image path for products without images |
53
+ | `defaultStoreImagePath` | string | `'/images/stores/default.jpg'` | Default image path for stores without images |
54
+
55
+ ### Environment Variables
56
+
57
+ The package will use `process.env.APP_URL` as the default `baseURL` if not configured explicitly. You can set this in your `.env` file:
58
+
59
+ ```env
60
+ APP_URL=https://api.yourdomain.com
61
+ MONGODB_URI=mongodb://localhost:27017/your-database
62
+ ```
63
+
64
+ ## Available Models
65
+
66
+ - **User** - User accounts and profiles
67
+ - **Store** - Store/shop information
68
+ - **Product** - Product catalog
69
+ - **Order** - Customer orders
70
+ - **Cart** - Shopping cart
71
+ - **Bill** - Billing information
72
+ - **Payment** - Payment transactions
73
+ - **Category** - Product categories
74
+ - **StoreCategory** - Store categories
75
+ - **Offer** - Special offers and promotions
76
+ - **FlashDeal** - Flash sale deals
77
+ - **Subscription** - Store subscriptions
78
+ - **Plan** - Subscription plans
79
+ - **SubscriptionOffer** - Subscription offer details
80
+ - **ReductionOffer** - Reduction/discount offers
81
+ - **Notification** - User notifications
82
+ - **View** - Product/store view tracking
83
+ - **Sale** - Sales records
84
+ - **StoreRate** - Store ratings
85
+ - **ResetPassword** - Password reset tokens
86
+ - **PaymentType** - Payment method types
87
+ - **UserAction** - User activity tracking
88
+ - **Policy** - Store/product policies
89
+
90
+ ## Virtual Properties
91
+
92
+ Some models include virtual properties that generate full URLs for images:
93
+
94
+ ### Product Model
95
+
96
+ - `imagesss` - Returns array of product images with full URLs
97
+ - `variantImages` - Returns array of variant images with full URLs
98
+ - `discounted` - Returns discounted price if offer exists
99
+
100
+ ```javascript
101
+ const product = await Product.findById(productId).populate('offer');
102
+ console.log(product.imagesss);
103
+ // ['https://api.yourdomain.com/uploads/product1.jpg', ...]
104
+ ```
105
+
106
+ ### Store Model
107
+
108
+ - `imageUrl` - Returns store image with full URL
109
+ - `rating` - Calculates average rating from ratingSum/ratingCount
110
+
111
+ ```javascript
112
+ const store = await Store.findById(storeId);
113
+ console.log(store.imageUrl);
114
+ // 'https://api.yourdomain.com/uploads/store-logo.jpg'
115
+ ```
116
+
117
+ ## Example: Complete Setup
118
+
119
+ ```javascript
120
+ const express = require('express');
121
+ const {
122
+ connectToDatabase,
123
+ configure,
124
+ User,
125
+ Product,
126
+ Store,
127
+ Order
128
+ } = require('database-connector');
129
+
130
+ const app = express();
131
+
132
+ // Configure the package FIRST
133
+ configure({
134
+ baseURL: process.env.APP_URL || 'http://localhost:3000'
135
+ });
136
+
137
+ // Connect to database
138
+ connectToDatabase(process.env.MONGODB_URI)
139
+ .then(() => console.log('Database connected'))
140
+ .catch(err => console.error('Database connection failed:', err));
141
+
142
+ // Use models in your routes
143
+ app.get('/products/:id', async (req, res) => {
144
+ try {
145
+ const product = await Product.findById(req.params.id);
146
+ res.json({
147
+ ...product.toJSON(),
148
+ // Virtual properties are automatically included with toJSON
149
+ images: product.imagesss
150
+ });
151
+ } catch (error) {
152
+ res.status(500).json({ error: error.message });
153
+ }
154
+ });
155
+
156
+ app.listen(3000);
157
+ ```
158
+
159
+ ## Swagger Documentation
160
+
161
+ All models include comprehensive Swagger/OpenAPI documentation. You can use these to generate API documentation.
162
+
163
+ ## Policy Schema
164
+
165
+ The `Policy` model can be used both as a standalone model and as an embedded schema:
166
+
167
+ ```javascript
168
+ const { Policy, policySchema } = require('database-connector');
169
+
170
+ // As standalone model
171
+ const policy = new Policy({ /* ... */ });
172
+ await policy.save();
173
+
174
+ // As embedded schema (already used in Product, Store, User models)
175
+ const product = new Product({
176
+ name: 'Product Name',
177
+ policy: {
178
+ workingTime: { openTime: '09:00', closeTime: '18:00' },
179
+ // ... other policy fields
180
+ }
181
+ });
182
+ ```
183
+
184
+ ## TypeScript Support
185
+
186
+ Type definitions are not included in this package yet. They may be added in future versions.
187
+
188
+ ## License
189
+
190
+ ISC
191
+
192
+ ## Changelog
193
+
194
+ See [CHANGELOG.md](./CHANGELOG.md) for version history and changes.
package/config.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Configuration module for database-connector package
3
+ * Allows consuming applications to set runtime configuration
4
+ */
5
+
6
+ let config = {
7
+ baseURL: process.env.APP_URL || 'http://localhost:3000',
8
+ defaultImagePath: '/images/default.png',
9
+ defaultStoreImagePath: '/images/stores/default.jpg'
10
+ };
11
+
12
+ /**
13
+ * Set the configuration for the package
14
+ * @param {Object} options - Configuration options
15
+ * @param {string} options.baseURL - Base URL for image paths (e.g., 'https://api.example.com')
16
+ * @param {string} options.defaultImagePath - Default image path for products
17
+ * @param {string} options.defaultStoreImagePath - Default image path for stores
18
+ */
19
+ function configure(options = {}) {
20
+ if (options.baseURL !== undefined) {
21
+ config.baseURL = options.baseURL;
22
+ }
23
+ if (options.defaultImagePath !== undefined) {
24
+ config.defaultImagePath = options.defaultImagePath;
25
+ }
26
+ if (options.defaultStoreImagePath !== undefined) {
27
+ config.defaultStoreImagePath = options.defaultStoreImagePath;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Get the current configuration
33
+ * @returns {Object} Current configuration
34
+ */
35
+ function getConfig() {
36
+ return { ...config };
37
+ }
38
+
39
+ /**
40
+ * Get the base URL
41
+ * @returns {string} Base URL
42
+ */
43
+ function getBaseURL() {
44
+ return config.baseURL;
45
+ }
46
+
47
+ /**
48
+ * Get the default image path
49
+ * @returns {string} Default image path
50
+ */
51
+ function getDefaultImagePath() {
52
+ return config.defaultImagePath;
53
+ }
54
+
55
+ /**
56
+ * Get the default store image path
57
+ * @returns {string} Default store image path
58
+ */
59
+ function getDefaultStoreImagePath() {
60
+ return config.defaultStoreImagePath;
61
+ }
62
+
63
+ module.exports = {
64
+ configure,
65
+ getConfig,
66
+ getBaseURL,
67
+ getDefaultImagePath,
68
+ getDefaultStoreImagePath
69
+ };
package/models/Policy.js CHANGED
@@ -126,7 +126,7 @@ const { Schema, model } = require('mongoose');
126
126
  * ringing:
127
127
  * type: boolean
128
128
  */
129
- exports.policySchema = new Schema(
129
+ const policySchema = new Schema(
130
130
  {
131
131
  workingTime: {
132
132
  type: {
@@ -211,4 +211,4 @@ exports.policySchema = new Schema(
211
211
  {}
212
212
  );
213
213
 
214
- module.exports = model('Policy', planSchema);
214
+ module.exports = model('Policy', policySchema);
package/models/Product.js CHANGED
@@ -1,5 +1,6 @@
1
1
  const mongoose = require('mongoose');
2
2
  const { policySchema } = require('database-connector/models/Policy');
3
+ const { getBaseURL, getDefaultImagePath } = require('../config');
3
4
 
4
5
  /**
5
6
  * @swagger
@@ -264,7 +265,7 @@ productSchema.virtual('imagesss').get(function () {
264
265
  console.log(images);
265
266
  console.log('images');
266
267
  return images.map(function (image) {
267
- return `${process.env.APP_URL}/${image}`;
268
+ return `${getBaseURL()}/${image}`;
268
269
  });
269
270
  }
270
271
  });
@@ -286,9 +287,9 @@ productSchema.virtual('variantImages').get(function () {
286
287
  console.log(variants);
287
288
  return variants.map(function (variant) {
288
289
  if (variant.img != null) {
289
- return `${process.env.APP_URL}/${variant.img}`;
290
+ return `${getBaseURL()}/${variant.img}`;
290
291
  } else {
291
- return `${process.env.APP_URL}/images/default.png`;
292
+ return `${getBaseURL()}${getDefaultImagePath()}`;
292
293
  }
293
294
  });
294
295
  }
package/models/Store.js CHANGED
@@ -1,5 +1,6 @@
1
1
  const mongoose = require('mongoose');
2
2
  const { policySchema } = require('database-connector/models/Policy');
3
+ const { getBaseURL, getDefaultStoreImagePath } = require('../config');
3
4
 
4
5
  /**
5
6
  * @swagger
@@ -342,12 +343,12 @@ const storeSchema = new mongoose.Schema(
342
343
 
343
344
  { timestamps: true, toJSON: { virtuals: true } }
344
345
  );
345
- //virtual image url
346
+ // Virtual: image URL with base path
346
347
  storeSchema.virtual('imageUrl').get(function () {
347
348
  if (this.image != null) {
348
- return `${process.env.APP_URL}/${this.image}`;
349
+ return `${getBaseURL()}/${this.image}`;
349
350
  }
350
- return `${process.env.APP_URL}/images/stores/default.jpg`;
351
+ return `${getBaseURL()}${getDefaultStoreImagePath()}`;
351
352
  });
352
353
  //virtual rating
353
354
  storeSchema.virtual('rating').get(function () {
package/models/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const mongoose = require('mongoose');
2
+ const config = require('../config');
2
3
 
3
4
  const connectToDatabase = async (databaseUrl) => {
4
5
  try {
@@ -40,6 +41,8 @@ const UserAction = require('./UserAction.js');
40
41
 
41
42
  module.exports = {
42
43
  connectToDatabase,
44
+ configure: config.configure,
45
+ getConfig: config.getConfig,
43
46
  PaymentType,
44
47
  Policy,
45
48
  ReductionOffer,
package/package.json CHANGED
@@ -1,15 +1,36 @@
1
1
  {
2
2
  "name": "database-connector",
3
- "version": "1.1.0",
3
+ "version": "2.0.1",
4
+ "description": "MongoDB models package with Mongoose schemas for e-commerce applications. Includes User, Product, Store, Order and more with built-in validation and virtual properties.",
4
5
  "main": "models/index.js",
5
6
  "scripts": {
6
7
  "test": "echo \"Error: no test specified\" && exit 1"
7
8
  },
8
- "keywords": [],
9
+ "keywords": [
10
+ "mongoose",
11
+ "mongodb",
12
+ "models",
13
+ "schemas",
14
+ "ecommerce",
15
+ "database",
16
+ "user",
17
+ "product",
18
+ "store",
19
+ "order"
20
+ ],
9
21
  "author": "",
10
22
  "license": "ISC",
11
- "description": "",
12
23
  "dependencies": {
13
24
  "mongoose": "^6.2.10"
25
+ },
26
+ "files": [
27
+ "models/",
28
+ "config.js",
29
+ "README.md",
30
+ "CHANGELOG.md"
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": ""
14
35
  }
15
36
  }