nodecraft-toolkit 0.0.0-stage → 1.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/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+
2
+ MIT License
3
+
4
+ Copyright (c) 2026 Chhavi
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
package/README.md CHANGED
@@ -1,3 +1,481 @@
1
- # Temporary Holding Version
1
+ # NodeCraft Toolkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A reusable Node.js backend development toolkit that provides commonly used utilities for core Node.js operations, HTTP responses, Express middleware, database operations, and input validation.
4
+
5
+ NodeCraft Toolkit helps developers avoid rewriting common backend code by providing simple, reusable, and organized utility functions.
6
+
7
+ ## Features
8
+
9
+ - **Core Utilities:** CLI argument parsing, file system helpers, streams, and event management.
10
+ - **HTTP Helpers:** Standardized JSON success and error responses.
11
+ - **Express Middleware:** Request logging, async error handling, authentication, and error handling.
12
+ - **Database Utilities:** Pagination, reusable CRUD service, and database error handling.
13
+ - **Validation:** Input validation and environment variable validation.
14
+ - **Easy Integration:** Modular exports and simple CommonJS syntax.
15
+
16
+ ## Requirements
17
+
18
+ - Node.js 18 or higher
19
+ - npm
20
+ - Express (optional, required only for Express-related functionality)
21
+ - Prisma (optional, required only for the Prisma example)
22
+
23
+ ## Installation
24
+
25
+ Install the package using npm:
26
+
27
+ ```bash
28
+ npm install nodecraft-toolkit
29
+ ```
30
+
31
+ For Express-related functionality, install Express:
32
+
33
+ ```bash
34
+ npm install express
35
+ ```
36
+
37
+ For the Prisma example, install Prisma and Prisma Client:
38
+
39
+ ```bash
40
+ npm install @prisma/client
41
+ npm install -D prisma
42
+ ```
43
+
44
+ ## Clone the Repository
45
+
46
+ To access the source code and examples:
47
+
48
+ ```bash
49
+ git clone https://github.com/Chhavi-2407/nodecraft-toolkit.git
50
+ cd nodecraft-toolkit
51
+ npm install
52
+ ```
53
+
54
+ ## Usage
55
+
56
+ Import the required utilities from the package:
57
+
58
+ ```javascript
59
+ const toolkit = require("nodecraft-toolkit");
60
+
61
+ const { core, http, express, database, validation } = toolkit;
62
+ ```
63
+
64
+ The package is divided into five main modules.
65
+
66
+ ## 1. Core Utilities
67
+
68
+ Provides utilities for common Node.js operations.
69
+
70
+ ### CLI Argument Parser
71
+
72
+ Parse command-line arguments into a structured object.
73
+
74
+ ```javascript
75
+ const { core } = require("nodecraft-toolkit");
76
+
77
+ const args = core.parseArgs(process.argv.slice(2));
78
+
79
+ console.log(args);
80
+ ```
81
+
82
+ ### File System Helpers
83
+
84
+ Provides reusable asynchronous file operations.
85
+
86
+ ```javascript
87
+ const { core } = require("nodecraft-toolkit");
88
+
89
+ async function fileOperations() {
90
+ await core.writeFile("demo.txt", "Hello NodeCraft!");
91
+
92
+ const content = await core.readFile("demo.txt");
93
+ console.log(content);
94
+
95
+ await core.appendFile("demo.txt", "\nNew content");
96
+
97
+ const exists = await core.fileExists("demo.txt");
98
+ console.log(exists);
99
+ }
100
+
101
+ fileOperations();
102
+ ```
103
+
104
+ ### Event Manager
105
+
106
+ Provides a simple wrapper around Node.js EventEmitter.
107
+
108
+ ```javascript
109
+ const { core } = require("nodecraft-toolkit");
110
+
111
+ const events = new core.EventManager();
112
+
113
+ events.on("userCreated", (user) => {
114
+ console.log("New user:", user);
115
+ });
116
+
117
+ events.emit("userCreated", {
118
+ id: 1,
119
+ name: "Chhavi"
120
+ });
121
+ ```
122
+
123
+ ### Stream Utilities
124
+
125
+ Provides helper functions for working with Node.js streams.
126
+
127
+ ```javascript
128
+ const { core } = require("nodecraft-toolkit");
129
+
130
+ async function streamOperations() {
131
+ const readStream = core.createReadStream("input.txt");
132
+ const writeStream = core.createWriteStream("output.txt");
133
+
134
+ await core.pipeStream(readStream, writeStream);
135
+ }
136
+
137
+ streamOperations();
138
+ ```
139
+
140
+ ## 2. HTTP Utilities
141
+
142
+ Provides helper functions for sending standardized HTTP responses.
143
+
144
+ ### Send JSON Response
145
+
146
+ ```javascript
147
+ const { http } = require("nodecraft-toolkit");
148
+
149
+ http.sendJSON(res, 200, {
150
+ message: "Success"
151
+ });
152
+ ```
153
+
154
+ ### Success Response
155
+
156
+ ```javascript
157
+ const response = http.successResponse(
158
+ "User fetched successfully",
159
+ { id: 1, name: "Chhavi" }
160
+ );
161
+
162
+ console.log(response);
163
+ ```
164
+
165
+ ### Error Response
166
+
167
+ ```javascript
168
+ const response = http.errorResponse(
169
+ "Something went wrong",
170
+ 500
171
+ );
172
+
173
+ console.log(response);
174
+ ```
175
+
176
+ ### Express Response Helpers
177
+
178
+ ```javascript
179
+ const { http } = require("nodecraft-toolkit");
180
+
181
+ app.get("/users", (req, res) => {
182
+ http.expressSuccess(res, "Users fetched successfully", []);
183
+ });
184
+ ```
185
+
186
+ ## 3. Express Middleware
187
+
188
+ Provides reusable middleware functions for Express applications.
189
+
190
+ ### Request Logger
191
+
192
+ Logs incoming HTTP requests.
193
+
194
+ ```javascript
195
+ const { express } = require("nodecraft-toolkit");
196
+
197
+ app.use(express.requestLogger);
198
+ ```
199
+
200
+ ### Async Handler
201
+
202
+ Wraps asynchronous route handlers and forwards errors to Express error middleware.
203
+
204
+ ```javascript
205
+ const { express } = require("nodecraft-toolkit");
206
+
207
+ app.get(
208
+ "/users",
209
+ express.asyncHandler(async (req, res) => {
210
+ const users = await getUsers();
211
+
212
+ res.json(users);
213
+ })
214
+ );
215
+ ```
216
+
217
+ ### Authentication Middleware
218
+
219
+ Checks whether a request contains a valid authentication token.
220
+
221
+ ```javascript
222
+ const { express } = require("nodecraft-toolkit");
223
+
224
+ app.use(express.authMiddleware((req) => {
225
+ return req.headers.authorization === "Bearer demo-token";
226
+ }));
227
+ ```
228
+
229
+ ### Not Found Middleware
230
+
231
+ Handles requests to routes that do not exist.
232
+
233
+ ```javascript
234
+ app.use(express.notFound);
235
+ ```
236
+
237
+ ### Error Handler
238
+
239
+ Handles errors forwarded through Express middleware.
240
+
241
+ ```javascript
242
+ app.use(express.errorHandler);
243
+ ```
244
+
245
+ **Important:** Register `notFound` and `errorHandler` after your application routes. The error handler should be the last middleware.
246
+
247
+ ## 4. Database Utilities
248
+
249
+ Provides reusable helpers for pagination, CRUD operations, and database error handling.
250
+
251
+ ### Pagination
252
+
253
+ Calculate pagination values from page number and page size.
254
+
255
+ ```javascript
256
+ const { database } = require("nodecraft-toolkit");
257
+
258
+ const pagination = database.getPagination(2, 10);
259
+
260
+ console.log(pagination);
261
+ ```
262
+
263
+ ### Pagination Metadata
264
+
265
+ Generate metadata for paginated results.
266
+
267
+ ```javascript
268
+ const meta = database.getPaginationMeta(100, 2, 10);
269
+
270
+ console.log(meta);
271
+ ```
272
+
273
+ ### CRUD Service
274
+
275
+ Create a reusable CRUD service using a database model.
276
+
277
+ ```javascript
278
+ const { database } = require("nodecraft-toolkit");
279
+
280
+ const userService = database.createCrudService(prisma.user);
281
+
282
+ async function operations() {
283
+ const users = await userService.findAll();
284
+
285
+ const user = await userService.findById(1);
286
+
287
+ const newUser = await userService.create({
288
+ name: "Chhavi",
289
+ email: "chhavi@example.com"
290
+ });
291
+
292
+ await userService.update(1, {
293
+ name: "Updated Name"
294
+ });
295
+
296
+ await userService.delete(1);
297
+ }
298
+ ```
299
+
300
+ This example assumes that Prisma Client has been initialized and a compatible `user` model exists in your Prisma schema.
301
+
302
+ ### Database Error Handling
303
+
304
+ Convert common database errors into readable application errors.
305
+
306
+ ```javascript
307
+ const { database } = require("nodecraft-toolkit");
308
+
309
+ try {
310
+ // Database operation
311
+ } catch (error) {
312
+ const handledError = database.handleDatabaseError(error);
313
+
314
+ console.log(handledError);
315
+ }
316
+ ```
317
+
318
+ ## 5. Validation Utilities
319
+
320
+ Provides helpers for validating input data and environment variables.
321
+
322
+ ### Input Validation
323
+
324
+ ```javascript
325
+ const { validation } = require("nodecraft-toolkit");
326
+
327
+ const result = validation.validateInput(
328
+ { name: "Chhavi", email: "chhavi@example.com" },
329
+ {
330
+ name: { required: true },
331
+ email: { required: true, type: "email" }
332
+ }
333
+ );
334
+
335
+ console.log(result);
336
+ ```
337
+
338
+ ### Environment Variable Validation
339
+
340
+ ```javascript
341
+ const { validation } = require("nodecraft-toolkit");
342
+
343
+ const env = validation.validateEnv(
344
+ ["PORT", "DATABASE_URL"]
345
+ );
346
+
347
+ console.log(env);
348
+ ```
349
+
350
+ ## Running Examples
351
+
352
+ The repository includes example applications demonstrating how to use the toolkit.
353
+
354
+ ### Basic Node.js Server
355
+
356
+ ```bash
357
+ node examples/basic-node-server.js
358
+ ```
359
+
360
+ ### Express Application
361
+
362
+ ```bash
363
+ node examples/express-app.js
364
+ ```
365
+
366
+ ### HTTP Demo
367
+
368
+ ```bash
369
+ node examples/http-demo.js
370
+ ```
371
+
372
+ ### Prisma Demo
373
+
374
+ ```bash
375
+ node examples/prisma-demo.js
376
+ ```
377
+
378
+ The Prisma demo requires a configured database connection and a generated Prisma Client.
379
+
380
+ ## Running Tests
381
+
382
+ Run the test suite using:
383
+
384
+ ```bash
385
+ npm test
386
+ ```
387
+
388
+ The project uses Node.js's built-in test runner.
389
+
390
+ Tests cover:
391
+
392
+ - Core utilities
393
+ - HTTP helpers
394
+ - Express middleware
395
+ - Express integration
396
+ - Database utilities
397
+ - Validation functions
398
+
399
+ ## Project Structure
400
+
401
+ ```text
402
+ nodecraft-toolkit/
403
+ │
404
+ ├── src/
405
+ │ ├── core/
406
+ │ │ ├── cli.js
407
+ │ │ ├── filesystem.js
408
+ │ │ ├── streams.js
409
+ │ │ └── events.js
410
+ │ │
411
+ │ ├── http/
412
+ │ │ └── response.js
413
+ │ │
414
+ │ ├── express/
415
+ │ │ ├── logger.js
416
+ │ │ ├── asyncHandler.js
417
+ │ │ ├── errorHandler.js
418
+ │ │ ├── notFound.js
419
+ │ │ └── authMiddleware.js
420
+ │ │
421
+ │ ├── database/
422
+ │ │ ├── pagination.js
423
+ │ │ ├── crudService.js
424
+ │ │ └── databaseError.js
425
+ │ │
426
+ │ ├── validation/
427
+ │ │ ├── validateInput.js
428
+ │ │ └── envValidator.js
429
+ │ │
430
+ │ └── index.js
431
+ │
432
+ ├── test/
433
+ │ ├── core/
434
+ │ ├── http/
435
+ │ ├── express/
436
+ │ ├── database/
437
+ │ └── validation/
438
+ │
439
+ ├── examples/
440
+ │ ├── basic-node-server.js
441
+ │ ├── express-app.js
442
+ │ ├── http-demo.js
443
+ │ └── prisma-demo.js
444
+ │
445
+ ├── index.js
446
+ ├── package.json
447
+ ├── package-lock.json
448
+ ├── README.md
449
+ ├── LICENSE
450
+ └── .gitignore
451
+ ```
452
+
453
+ ## Technologies Used
454
+
455
+ - Node.js
456
+ - JavaScript
457
+ - Express.js
458
+ - Prisma ORM (for the example integration)
459
+ - npm
460
+ - Node.js Built-in Test Runner
461
+
462
+ ## Package Information
463
+
464
+ - **Package Name:** nodecraft-toolkit
465
+ - **Current Published Version:** 1.0.0
466
+ - **Author:** Chhavi
467
+ - **License:** MIT
468
+ - **Node.js Requirement:** >=18
469
+
470
+ ## Links
471
+
472
+ - **npm Package:** https://www.npmjs.com/package/nodecraft-toolkit
473
+ - **GitHub Repository:** https://github.com/Chhavi-2407/nodecraft-toolkit
474
+
475
+ ## License
476
+
477
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
478
+
479
+ ---
480
+
481
+ Made with Node.js by **Chhavi**.
package/index.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require("./src");
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "nodecraft-toolkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "A reusable Node.js backend development toolkit",
5
+ "main": "index.js",
6
+ "type": "commonjs",
7
+ "files": [
8
+ "index.js",
9
+ "src/",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "scripts": {
14
+ "test": "node --test"
15
+ },
16
+ "keywords": [
17
+ "nodejs",
18
+ "express",
19
+ "backend",
20
+ "middleware",
21
+ "http",
22
+ "npm-package"
23
+ ],
24
+ "author": "Chhavi",
25
+ "license": "MIT",
26
+ "engines": {
27
+ "node": ">=18"
28
+ },
29
+ "peerDependencies": {
30
+ "express": "^4.18.0 || ^5.0.0"
31
+ },
32
+ "peerDependenciesMeta": {
33
+ "express": {
34
+ "optional": true
35
+ }
36
+ }
37
+ }
@@ -0,0 +1,57 @@
1
+
2
+ function parseArgs(args = process.argv.slice(2)) {
3
+ if (!Array.isArray(args)) {
4
+ throw new TypeError("Arguments must be an array");
5
+ }
6
+
7
+ const result = {
8
+ positional: [],
9
+ options: {}
10
+ };
11
+
12
+ for (let i = 0; i < args.length; i++) {
13
+ const arg = args[i];
14
+
15
+ if (typeof arg !== "string") {
16
+ throw new TypeError("Every argument must be a string");
17
+ }
18
+
19
+ if (arg.startsWith("--")) {
20
+ const option = arg.slice(2);
21
+
22
+ if (!option) {
23
+ throw new Error("Invalid empty option");
24
+ }
25
+
26
+ const equalIndex = option.indexOf("=");
27
+
28
+ if (equalIndex !== -1) {
29
+ const key = option.slice(0, equalIndex);
30
+ const value = option.slice(equalIndex + 1);
31
+
32
+ if (!key) {
33
+ throw new Error("Option name cannot be empty");
34
+ }
35
+
36
+ result.options[key] = value;
37
+ } else if (option.startsWith("no-")) {
38
+ result.options[option.slice(3)] = false;
39
+ } else if (
40
+ i + 1 < args.length &&
41
+ !args[i + 1].startsWith("--")
42
+ ) {
43
+ result.options[option] = args[++i];
44
+ } else {
45
+ result.options[option] = true;
46
+ }
47
+ } else {
48
+ result.positional.push(arg);
49
+ }
50
+ }
51
+
52
+ return result;
53
+ }
54
+
55
+ module.exports = {
56
+ parseArgs
57
+ };
@@ -0,0 +1,52 @@
1
+
2
+ const EventEmitter = require("node:events");
3
+
4
+ class EventManager extends EventEmitter {
5
+
6
+ subscribe(eventName, listener) {
7
+ if (typeof listener !== "function") {
8
+ throw new TypeError("Listener must be a function");
9
+ }
10
+
11
+ this.on(eventName, listener);
12
+
13
+ return () => this.off(eventName, listener);
14
+ }
15
+
16
+ subscribeOnce(eventName, listener) {
17
+ if (typeof listener !== "function") {
18
+ throw new TypeError("Listener must be a function");
19
+ }
20
+
21
+ this.once(eventName, listener);
22
+ }
23
+
24
+ publish(eventName, ...args) {
25
+ return this.emit(eventName, ...args);
26
+ }
27
+
28
+ unsubscribe(eventName, listener) {
29
+ this.off(eventName, listener);
30
+ }
31
+
32
+ getListeners(eventName) {
33
+ return this.listeners(eventName);
34
+ }
35
+
36
+ clear(eventName) {
37
+ if (eventName) {
38
+ this.removeAllListeners(eventName);
39
+ } else {
40
+ this.removeAllListeners();
41
+ }
42
+ }
43
+ }
44
+
45
+ function createEventManager() {
46
+ return new EventManager();
47
+ }
48
+
49
+ module.exports = {
50
+ EventManager,
51
+ createEventManager
52
+ };
@@ -0,0 +1,60 @@
1
+
2
+ const fs = require("node:fs/promises");
3
+ const path = require("node:path");
4
+
5
+ async function readFile(filePath) {
6
+ return await fs.readFile(filePath, "utf-8");
7
+ }
8
+
9
+ async function writeFile(filePath, content) {
10
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
11
+ await fs.writeFile(filePath, content, "utf-8");
12
+
13
+ return true;
14
+ }
15
+
16
+ async function appendFile(filePath, content) {
17
+ await fs.appendFile(filePath, content, "utf-8");
18
+
19
+ return true;
20
+ }
21
+
22
+ async function createDirectory(dirPath) {
23
+ await fs.mkdir(dirPath, { recursive: true });
24
+
25
+ return true;
26
+ }
27
+
28
+ async function fileExists(filePath) {
29
+ try {
30
+ await fs.access(filePath);
31
+ return true;
32
+ } catch (error) {
33
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") {
34
+ return false;
35
+ }
36
+
37
+ throw error;
38
+ }
39
+ }
40
+
41
+ async function getFileInfo(filePath) {
42
+ const stats = await fs.stat(filePath);
43
+
44
+ return {
45
+ size: stats.size,
46
+ isFile: stats.isFile(),
47
+ isDirectory: stats.isDirectory(),
48
+ createdAt: stats.birthtime,
49
+ modifiedAt: stats.mtime
50
+ };
51
+ }
52
+
53
+ module.exports = {
54
+ readFile,
55
+ writeFile,
56
+ appendFile,
57
+ createDirectory,
58
+ fileExists,
59
+ getFileInfo
60
+ };
@@ -0,0 +1,37 @@
1
+
2
+ const fs = require("node:fs");
3
+ const { pipeline } = require("node:stream/promises");
4
+
5
+ function createReadStream(filePath, options = {}) {
6
+ return fs.createReadStream(filePath, options);
7
+ }
8
+
9
+ function createWriteStream(filePath, options = {}) {
10
+ return fs.createWriteStream(filePath, options);
11
+ }
12
+
13
+ async function pipeStream(readable, writable) {
14
+ if (!readable || !writable) {
15
+ throw new TypeError("Readable and writable streams are required");
16
+ }
17
+
18
+ await pipeline(readable, writable);
19
+
20
+ return true;
21
+ }
22
+
23
+ async function copyFile(source, destination) {
24
+ const readable = createReadStream(source);
25
+ const writable = createWriteStream(destination);
26
+
27
+ await pipeline(readable, writable);
28
+
29
+ return true;
30
+ }
31
+
32
+ module.exports = {
33
+ createReadStream,
34
+ createWriteStream,
35
+ pipeStream,
36
+ copyFile
37
+ };
@@ -0,0 +1,91 @@
1
+
2
+ const { getPagination, getPaginationMeta } =
3
+ require("./pagination");
4
+
5
+ function createCrudService(model) {
6
+ const requiredMethods = [
7
+ "findMany",
8
+ "count",
9
+ "findUnique",
10
+ "create",
11
+ "update",
12
+ "delete"
13
+ ];
14
+
15
+ for (const method of requiredMethods) {
16
+ if (typeof model?.[method] !== "function") {
17
+ throw new TypeError(
18
+ `Database model must implement ${method}()`
19
+ );
20
+ }
21
+ }
22
+
23
+ async function getAll(query = {}, options = {}) {
24
+ const pagination = getPagination(query);
25
+
26
+ const where = options.where || {};
27
+ const orderBy = options.orderBy || {};
28
+
29
+ const [data, total] = await Promise.all([
30
+ model.findMany({
31
+ where,
32
+ orderBy,
33
+ skip: pagination.skip,
34
+ take: pagination.take
35
+ }),
36
+ model.count({ where })
37
+ ]);
38
+
39
+ return {
40
+ data,
41
+ pagination: getPaginationMeta(
42
+ total,
43
+ pagination.page,
44
+ pagination.limit
45
+ )
46
+ };
47
+ }
48
+
49
+ async function getById(id, options = {}) {
50
+ const data = await model.findUnique({
51
+ where: { [options.idField || "id"]: id }
52
+ });
53
+
54
+ if (!data) {
55
+ const error = new Error("Record not found");
56
+ error.statusCode = 404;
57
+ throw error;
58
+ }
59
+
60
+ return data;
61
+ }
62
+
63
+ async function create(data) {
64
+ return model.create({ data });
65
+ }
66
+
67
+ async function update(id, data, options = {}) {
68
+ return model.update({
69
+ where: { [options.idField || "id"]: id },
70
+ data
71
+ });
72
+ }
73
+
74
+ async function remove(id, options = {}) {
75
+ return model.delete({
76
+ where: { [options.idField || "id"]: id }
77
+ });
78
+ }
79
+
80
+ return {
81
+ getAll,
82
+ getById,
83
+ create,
84
+ update,
85
+ remove
86
+ };
87
+ }
88
+
89
+ module.exports = {
90
+ createCrudService
91
+ };
@@ -0,0 +1,26 @@
1
+
2
+ function handleDatabaseError(error) {
3
+ if (error.code === "P2002") {
4
+ const err = new Error("A record with this value already exists");
5
+ err.statusCode = 409;
6
+ return err;
7
+ }
8
+
9
+ if (error.code === "P2025") {
10
+ const err = new Error("Record not found");
11
+ err.statusCode = 404;
12
+ return err;
13
+ }
14
+
15
+ if (error.code === "P2003") {
16
+ const err = new Error("Related record does not exist");
17
+ err.statusCode = 400;
18
+ return err;
19
+ }
20
+
21
+ return error;
22
+ }
23
+
24
+ module.exports = {
25
+ handleDatabaseError
26
+ };
@@ -0,0 +1,40 @@
1
+
2
+ function getPagination(query = {}) {
3
+ const page = Number(query.page ?? 1);
4
+ const limit = Number(query.limit ?? 10);
5
+
6
+ if (!Number.isInteger(page) || page < 1) {
7
+ throw new Error("Page must be a positive integer");
8
+ }
9
+
10
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
11
+ throw new Error("Limit must be between 1 and 100");
12
+ }
13
+
14
+ const skip = (page - 1) * limit;
15
+
16
+ return {
17
+ page,
18
+ limit,
19
+ skip,
20
+ take: limit
21
+ };
22
+ }
23
+
24
+ function getPaginationMeta(total, page, limit) {
25
+ const totalPages = Math.ceil(total / limit);
26
+
27
+ return {
28
+ total,
29
+ page,
30
+ limit,
31
+ totalPages,
32
+ hasNextPage: page < totalPages,
33
+ hasPreviousPage: page > 1
34
+ };
35
+ }
36
+
37
+ module.exports = {
38
+ getPagination,
39
+ getPaginationMeta
40
+ };
@@ -0,0 +1,10 @@
1
+
2
+ function asyncHandler(fn) {
3
+ return function (req, res, next) {
4
+ Promise.resolve(fn(req, res, next)).catch(next);
5
+ };
6
+ }
7
+
8
+ module.exports = {
9
+ asyncHandler
10
+ };
@@ -0,0 +1,29 @@
1
+
2
+ function authMiddleware(authenticate) {
3
+ if (typeof authenticate !== "function") {
4
+ throw new TypeError("authenticate must be a function");
5
+ }
6
+
7
+ return async function (req, res, next) {
8
+ try {
9
+ const user = await authenticate(req);
10
+
11
+ if (!user) {
12
+ return res.status(401).json({
13
+ success: false,
14
+ error: "Unauthorized"
15
+ });
16
+ }
17
+
18
+ req.user = user;
19
+
20
+ next();
21
+ } catch (error) {
22
+ next(error);
23
+ }
24
+ };
25
+ }
26
+
27
+ module.exports = {
28
+ authMiddleware
29
+ };
@@ -0,0 +1,35 @@
1
+
2
+ function errorHandler(err, req, res, next) {
3
+ if (res.headersSent) {
4
+ return next(err);
5
+ }
6
+
7
+ const statusCode = err.statusCode || err.status || 500;
8
+
9
+ const safeStatusCode =
10
+ Number.isInteger(statusCode) &&
11
+ statusCode >= 400 &&
12
+ statusCode <= 599
13
+ ? statusCode
14
+ : 500;
15
+
16
+ const message =
17
+ safeStatusCode === 500
18
+ ? "Internal Server Error"
19
+ : err.message || "Something went wrong";
20
+
21
+ if (process.env.NODE_ENV !== "production") {
22
+ console.error(err);
23
+ }
24
+
25
+ return res.status(safeStatusCode).json({
26
+ success: false,
27
+ error: {
28
+ message
29
+ }
30
+ });
31
+ }
32
+
33
+ module.exports = {
34
+ errorHandler
35
+ };
@@ -0,0 +1,24 @@
1
+
2
+ function requestLogger(options = {}) {
3
+ const logger = options.logger || console.log;
4
+
5
+ return function (req, res, next) {
6
+ const startTime = Date.now();
7
+
8
+ res.on("finish", () => {
9
+ const duration = Date.now() - startTime;
10
+
11
+ const logMessage =
12
+ `${req.method} ${req.originalUrl || req.url} ` +
13
+ `${res.statusCode} ${duration}ms`;
14
+
15
+ logger(logMessage);
16
+ });
17
+
18
+ next();
19
+ };
20
+ }
21
+
22
+ module.exports = {
23
+ requestLogger
24
+ };
@@ -0,0 +1,14 @@
1
+
2
+ function notFound(req, res, next) {
3
+ const error = new Error(
4
+ `Route not found: ${req.method} ${req.originalUrl || req.url}`
5
+ );
6
+
7
+ error.statusCode = 404;
8
+
9
+ next(error);
10
+ }
11
+
12
+ module.exports = {
13
+ notFound
14
+ };
@@ -0,0 +1,65 @@
1
+
2
+ const STATUS_CODES = {
3
+ OK: 200,
4
+ CREATED: 201,
5
+ BAD_REQUEST: 400,
6
+ UNAUTHORIZED: 401,
7
+ FORBIDDEN: 403,
8
+ NOT_FOUND: 404,
9
+ CONFLICT: 409,
10
+ INTERNAL_SERVER_ERROR: 500
11
+ };
12
+
13
+ function sendJSON(res, statusCode, data, headers = {}) {
14
+ if (!res || typeof res.writeHead !== "function" ||
15
+ typeof res.end !== "function") {
16
+ throw new TypeError("Invalid HTTP response object");
17
+ }
18
+
19
+ const body = JSON.stringify(data);
20
+
21
+ res.writeHead(statusCode, {
22
+ "Content-Type": "application/json; charset=utf-8",
23
+ ...headers
24
+ });
25
+
26
+ res.end(body);
27
+ }
28
+
29
+ function successResponse(res, data, statusCode = STATUS_CODES.OK) {
30
+ return sendJSON(res, statusCode, {
31
+ success: true,
32
+ data
33
+ });
34
+ }
35
+
36
+ function errorResponse(res, message, statusCode = STATUS_CODES.INTERNAL_SERVER_ERROR) {
37
+ return sendJSON(res, statusCode, {
38
+ success: false,
39
+ error: message
40
+ });
41
+ }
42
+
43
+
44
+ function expressSuccess(res, data, statusCode = STATUS_CODES.OK) {
45
+ return res.status(statusCode).json({
46
+ success: true,
47
+ data
48
+ });
49
+ }
50
+
51
+ function expressError(res, message, statusCode = STATUS_CODES.INTERNAL_SERVER_ERROR) {
52
+ return res.status(statusCode).json({
53
+ success: false,
54
+ error: message
55
+ });
56
+ }
57
+
58
+ module.exports = {
59
+ STATUS_CODES,
60
+ sendJSON,
61
+ successResponse,
62
+ errorResponse,
63
+ expressSuccess,
64
+ expressError
65
+ };
package/src/index.js ADDED
@@ -0,0 +1,49 @@
1
+ const cli = require("./core/cli");
2
+ const filesystem = require("./core/filesystem");
3
+ const streams = require("./core/streams");
4
+ const events = require("./core/events");
5
+
6
+ const http = require("./http/response");
7
+
8
+ const logger = require("./express/logger");
9
+ const asyncHandler = require("./express/asyncHandler");
10
+ const errorHandler = require("./express/errorHandler");
11
+ const notFound = require("./express/notFound");
12
+ const authMiddleware = require("./express/authMiddleware");
13
+
14
+ const pagination = require("./database/pagination");
15
+ const crudService = require("./database/crudService");
16
+ const databaseError = require("./database/databaseError");
17
+
18
+ const inputValidation = require("./validation/validateInput");
19
+ const envValidation = require("./validation/envValidator");
20
+
21
+ module.exports = {
22
+ core: {
23
+ ...cli,
24
+ ...filesystem,
25
+ ...streams,
26
+ ...events
27
+ },
28
+
29
+ http,
30
+
31
+ express: {
32
+ ...logger,
33
+ ...asyncHandler,
34
+ ...errorHandler,
35
+ ...notFound,
36
+ ...authMiddleware
37
+ },
38
+
39
+ database: {
40
+ ...pagination,
41
+ ...crudService,
42
+ ...databaseError
43
+ },
44
+
45
+ validation: {
46
+ ...inputValidation,
47
+ ...envValidation
48
+ }
49
+ };
@@ -0,0 +1,24 @@
1
+ function validateEnv(requiredVariables = []) {
2
+ const missing = [];
3
+
4
+ for (const variable of requiredVariables) {
5
+ if (!process.env[variable]) {
6
+ missing.push(variable);
7
+ }
8
+ }
9
+
10
+ if (missing.length > 0) {
11
+ const error = new Error(
12
+ `Missing environment variables: ${missing.join(", ")}`
13
+ );
14
+
15
+ error.missingVariables = missing;
16
+ throw error;
17
+ }
18
+
19
+ return true;
20
+ }
21
+
22
+ module.exports = {
23
+ validateEnv
24
+ };
@@ -0,0 +1,63 @@
1
+ function validateInput(data, rules) {
2
+ const errors = [];
3
+
4
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
5
+ throw new TypeError("Data must be an object");
6
+ }
7
+
8
+ for (const [field, rule] of Object.entries(rules)) {
9
+ const value = data[field];
10
+
11
+ if (rule.required && (
12
+ value === undefined ||
13
+ value === null ||
14
+ value === ""
15
+ )) {
16
+ errors.push(`${field} is required`);
17
+ continue;
18
+ }
19
+
20
+ if (value === undefined || value === null) {
21
+ continue;
22
+ }
23
+
24
+ if (rule.type && typeof value !== rule.type) {
25
+ errors.push(`${field} must be a ${rule.type}`);
26
+ }
27
+
28
+ if (
29
+ rule.minLength &&
30
+ typeof value === "string" &&
31
+ value.length < rule.minLength
32
+ ) {
33
+ errors.push(
34
+ `${field} must be at least ${rule.minLength} characters`
35
+ );
36
+ }
37
+
38
+ if (
39
+ rule.min !== undefined &&
40
+ typeof value === "number" &&
41
+ value < rule.min
42
+ ) {
43
+ errors.push(`${field} must be at least ${rule.min}`);
44
+ }
45
+
46
+ if (
47
+ rule.max !== undefined &&
48
+ typeof value === "number" &&
49
+ value > rule.max
50
+ ) {
51
+ errors.push(`${field} must not exceed ${rule.max}`);
52
+ }
53
+ }
54
+
55
+ return {
56
+ valid: errors.length === 0,
57
+ errors
58
+ };
59
+ }
60
+
61
+ module.exports = {
62
+ validateInput
63
+ };