nodecraft-toolkit 0.0.0-stage → 1.0.0

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,245 @@
1
- # Temporary Holding Version
2
1
 
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.
2
+ # NodeCraft Toolkit
3
+
4
+ A reusable Node.js backend development toolkit containing utilities for core Node.js modules, HTTP responses, Express middleware, database operations, and input validation.
5
+
6
+ ## Features
7
+
8
+ - **Core Utilities:** CLI argument parsing, filesystem operations, streams, and event management.
9
+ - **HTTP Utilities:** Standardized JSON success and error responses.
10
+ - **Express Middleware:** Request logger, async handler, authentication middleware, 404 handler, and error handler.
11
+ - **Database Utilities:** Pagination, reusable CRUD service, and Prisma error handling.
12
+ - **Validation:** Input validation and environment variable validation.
13
+
14
+ ## Requirements
15
+
16
+ - Node.js 18 or above
17
+ - Express 4 or 5 (optional, required only for Express utilities)
18
+ - Prisma Client (optional, required only when using Prisma integration)
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install nodecraft-toolkit
24
+ ```
25
+
26
+ For Express projects:
27
+
28
+ ```bash
29
+ npm install express
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ Import the toolkit:
35
+
36
+ ```js
37
+ const toolkit = require("nodecraft-toolkit");
38
+ ```
39
+
40
+ ### 1. Core Utilities
41
+
42
+ #### CLI Argument Parser
43
+
44
+ ```js
45
+ const { parseArgs } = toolkit.core;
46
+
47
+ const result = parseArgs(["server", "--port", "5000"]);
48
+
49
+ console.log(result);
50
+ ```
51
+
52
+ #### Filesystem
53
+
54
+ ```js
55
+ const { writeFile, readFile } = toolkit.core;
56
+
57
+ async function main() {
58
+ await writeFile("demo.txt", "Hello NodeCraft!");
59
+ const content = await readFile("demo.txt");
60
+
61
+ console.log(content);
62
+ }
63
+
64
+ main();
65
+ ```
66
+
67
+ #### Event Manager
68
+
69
+ ```js
70
+ const { createEventManager } = toolkit.core;
71
+
72
+ const events = createEventManager();
73
+
74
+ events.subscribe("userCreated", (user) => {
75
+ console.log("New user:", user);
76
+ });
77
+
78
+ events.publish("userCreated", { id: 1, name: "Chhavi" });
79
+ ```
80
+
81
+ #### Streams
82
+
83
+ ```js
84
+ const { copyFile } = toolkit.core;
85
+
86
+ copyFile("source.txt", "destination.txt")
87
+ .then(() => console.log("File copied"))
88
+ .catch(console.error);
89
+ ```
90
+
91
+ ### 2. HTTP Utilities
92
+
93
+ ```js
94
+ const { http } = toolkit;
95
+
96
+ const server = require("node:http").createServer((req, res) => {
97
+ http.successResponse(res, {
98
+ message: "Welcome to NodeCraft"
99
+ });
100
+ });
101
+
102
+ server.listen(3000);
103
+ ```
104
+
105
+ Available functions:
106
+
107
+ - `sendJSON()`
108
+ - `successResponse()`
109
+ - `errorResponse()`
110
+ - `expressSuccess()`
111
+ - `expressError()`
112
+
113
+ ### 3. Express Middleware
114
+
115
+ ```js
116
+ const express = require("express");
117
+ const toolkit = require("nodecraft-toolkit");
118
+
119
+ const app = express();
120
+
121
+ app.use(express.json());
122
+ app.use(toolkit.express.requestLogger());
123
+
124
+ app.get("/", (req, res) => {
125
+ res.json({ message: "Welcome" });
126
+ });
127
+
128
+ app.use(toolkit.express.notFound);
129
+ app.use(toolkit.express.errorHandler);
130
+
131
+ app.listen(3000);
132
+ ```
133
+
134
+ Available middleware:
135
+
136
+ - `requestLogger()`
137
+ - `asyncHandler()`
138
+ - `authMiddleware()`
139
+ - `notFound`
140
+ - `errorHandler`
141
+
142
+ ### 4. Database Utilities
143
+
144
+ #### Pagination
145
+
146
+ ```js
147
+ const { database } = toolkit;
148
+
149
+ const pagination = database.getPagination({
150
+ page: 2,
151
+ limit: 10
152
+ });
153
+
154
+ console.log(pagination);
155
+ ```
156
+
157
+ #### CRUD Service with Prisma
158
+
159
+ ```js
160
+ const { PrismaClient } = require("@prisma/client");
161
+ const { database } = require("nodecraft-toolkit");
162
+
163
+ const prisma = new PrismaClient();
164
+
165
+ const userService = database.createCrudService(prisma.user);
166
+
167
+ async function main() {
168
+ const users = await userService.getAll({
169
+ page: 1,
170
+ limit: 10
171
+ });
172
+
173
+ console.log(users);
174
+ }
175
+
176
+ main().finally(() => prisma.$disconnect());
177
+ ```
178
+
179
+ The CRUD service expects a Prisma-style model delegate.
180
+
181
+ ### 5. Validation
182
+
183
+ #### Input Validation
184
+
185
+ ```js
186
+ const { validation } = toolkit;
187
+
188
+ const result = validation.validateInput(
189
+ { name: "Chhavi", age: 20 },
190
+ {
191
+ name: {
192
+ required: true,
193
+ type: "string",
194
+ minLength: 3
195
+ },
196
+ age: {
197
+ required: true,
198
+ type: "number",
199
+ min: 18
200
+ }
201
+ }
202
+ );
203
+
204
+ console.log(result);
205
+ ```
206
+
207
+ #### Environment Validation
208
+
209
+ ```js
210
+ const { validation } = toolkit;
211
+
212
+ validation.validateEnv(["PORT", "DATABASE_URL"]);
213
+ ```
214
+
215
+ ## Running Tests
216
+
217
+ Clone the repository and install its development dependencies:
218
+
219
+ ```bash
220
+ npm install
221
+ npm test
222
+ ```
223
+
224
+ The project uses Node.js built-in test runner.
225
+
226
+ ## Project Structure
227
+
228
+ ```text
229
+ nodecraft-toolkit/
230
+ ├── src/
231
+ │ ├── core/
232
+ │ ├── http/
233
+ │ ├── express/
234
+ │ ├── database/
235
+ │ └── validation/
236
+ ├── test/
237
+ ├── examples/
238
+ ├── index.js
239
+ ├── package.json
240
+ └── README.md
241
+ ```
242
+
243
+ ## License
244
+
245
+ MIT
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"
3
+ "version": "1.0.0",
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
+ }
6
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
+ };