{"id":20538310,"url":"https://github.com/basemkhirat/express-mvc","last_synced_at":"2025-04-14T07:50:50.501Z","repository":{"id":41828333,"uuid":"108473234","full_name":"basemkhirat/express-mvc","owner":"basemkhirat","description":"A light-weight mvc pattern for express framework with minimum dependencies","archived":false,"fork":false,"pushed_at":"2022-12-22T09:22:52.000Z","size":242,"stargazers_count":52,"open_issues_count":11,"forks_count":13,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-03-27T21:23:32.075Z","etag":null,"topics":["expressjs","i18n","mean","mean-stack","mongodb","mongoose","mvc","nodejs","passportjs","sailsjs"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/basemkhirat.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-10-26T22:41:45.000Z","updated_at":"2024-12-26T21:42:49.000Z","dependencies_parsed_at":"2023-01-30T06:46:03.739Z","dependency_job_id":null,"html_url":"https://github.com/basemkhirat/express-mvc","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/basemkhirat%2Fexpress-mvc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/basemkhirat%2Fexpress-mvc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/basemkhirat%2Fexpress-mvc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/basemkhirat%2Fexpress-mvc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/basemkhirat","download_url":"https://codeload.github.com/basemkhirat/express-mvc/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248844048,"owners_count":21170486,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["expressjs","i18n","mean","mean-stack","mongodb","mongoose","mvc","nodejs","passportjs","sailsjs"],"created_at":"2024-11-16T00:46:15.656Z","updated_at":"2025-04-14T07:50:50.466Z","avatar_url":"https://github.com/basemkhirat.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Attention\n\nNow, we don't give support for this package as we worked on the core since Jan 2019 to introduce dotapp nodejs framework.\n\nSee: [DotApp Framework](https://github.com/basemkhirat/dotapp-framework)\n\nIf you are a maintainer, contact us and you are welcome to have access.\n\n# express-mvc\nA light-weight mvc pattern for express framework with minimum dependencies\n\n\n## Installation\n\n```bash\nnpm install express-mvc-generate -g\n```\n\nExpress MVC generator command will be installed globally so from anywhere you can call it to generate the project skeleton.\n\n```bash\nexpress-mvc-generate my-project\ncd my-project\nnpm install\nnpm start\n```\nServer will be created at port 3000 by default. you can change the port later from app configurations.\n\nBrowse `http://localhost:3000` and have fun.\n\n\n## The config directory\n\nAll application configuration files are stored here grouped by its functionalites:\n\n`app.js` setting the enviromment, port and main app configurations.\n\n`db.js` setting monogdb connection parameters.\n\n`body.js` setting the body parser module configurations.\n\n`i18n.js` setting the current app locale and other localization configurations.\t\n \n`jwt.js` setting the secret hash and expiration date used by bycrpt package.\n\n`session.js` setting all session configurations such as the name and secret hash.\n\n`csrf.js` setting the Cross-Site Request Forgery protection.\n\n`cors.js` setting the Cross-Origin Resource Sharing protection.\n\n\nIn production environment. we always need a different configuration parameters that what the `config/env` directory do.\n\nThe application gets the enviroment stored in `app.js` file and load the evironment file. So if we are working in `production` environment, the application will automatically load the configuration file `config/env/production.js` and uses its defined items to override items stored outside.\n\n```javascript\n# production.js\n\nmodule.exports = {\n\tdb: {\n\t\turl: 'mongodb://localhost/production_db_name',\n\t}\n}\n```\n\nWe can access configuration using the `_config()` function. so if we want to get the environment key we call `_config('app.env')`.\n\n## Public directory\n\nHere we can put our static files such as image, css, js, uploads and other client side files to be served.\n\n## Application directory\n\nContains the MVC folder structure:\n\n`controllers` are modules. each of them exports an object of methods that accept request and response.\n\n```javascript\n# HomeController.js\n\nmodule.exports = {\n\n    /**\n     * Show homepage\n     * @param req\n     * @param res\n     */\n    index: function (req, res) {\n        return res.render(\"hello world !\");\n    },\n}\n```\n\n`routes` define app routes definitions.\n\nThere are two files. one for web routes (browser routes) and the other for api routes. you can define routes easily.\n\n```javascript\n# web.js\n\nvar router = require(\"express\").Router();\n\nrouter.get(\"/\", HomeController.index);\n\nmodule.exports = router;\n```\n\n`Note` api routes defined in `api.js` are prefixed by default with the value of configuation `_config(\"app.api_prefix\")`;\n\n`models` define the mongoose collection models that interact directly with database.\n\n```javascript\n# User.js\n\nvar mongoose = require(\"mongoose\");\n\nvar schema = mongoose.Schema({\n        username: {\n            type: String,\n            unique: true\n        }     \n});\n\nmodule.exports = mongoose.model(\"user\", schema, \"user\");\n```\n\nYou should read [mongoose docs](http://mongoosejs.com/docs/guide.html) before writing your models\n\n`views` define app templates files.\n\nThe default engine is `ejs`. You can change views settings from `app.js`\n\n```javascript\n# hello.ejs\n\n\u003ch1\u003e\n    Hello world \u003c%= _lang(\"name\") %\u003e!\n\u003c/h1\u003e\n\n```\n\n`middlewares` are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.\n\n```javascript\n# SessionAuth.js\n\nmodule.exports = function (req, res, next) {\n\n    if (req.isAuthenticated()) return next();\n\n    return res.forbidden();\n};\n\nYou can call middlwares within routes file using:\n\nrouter.get(\"/profile\", SessionAuth, HomeController.profile);\n\n```\n\n\n`services` are libraries of functions that you can use from anywhere in your app. For example, you might have an EmailService which tidily wraps up one or more helper functions so you can use them in more than one place within your application. Services are the best and simplest way to build reusable code.\n\n\n```javascript\n# EmailService.js\n\nmodule.exports = {\n\n    /**\n     * Send emails\n     * @param req\n     * @param res\n     */\n    send: function (req, res) {\n        // Sending ...\n    },\n}\n```\n\nFrom anywhere in your project you can call it `EmailService.send()`\n\n`lang` stores the translation keys grouped by each locale.\n\n```javascript\n# en.json\n\n{\n\t\"name\": \"express\"\n}\n```\n\nYou can get the localized value using the helper function `_lang('name')`\n\n\n`responses`: are custom responses attached to the `res` object to send a given responses. you can write your own custom response.\n\n\n```javascript\n# invalid.js\n\nmodule.exports = function (data) {\n\t\n\tvar req = this.req; \n\tvar res = this.res;\n\t\n\t// data processing......\n\t\n\treturn res.send(data);    \n});\n```\n\nFrom controller or middlewares you can call it using `res.invalid()`\n\n\n\n## Global helper functions\n\n\n`_config(key)` gets the configuration value by key.\n\n```javascript\n_config(\"app.env\");\t\t\n// return 'development'\n\n_config(\"db\"); \t\n// return { url: 'mongodb://localhost/db_name', options: { useMongoClient: true } }\n\n```\n\n`_lang(key)` gets the localized value by key.\n\n```javascript\n_lang(\"name\");\t\t\n// return 'express'\n```\n\n\n`_url(path)` gets the application base url.\n\n```javascript\n_url();\t\t\n// return 'http://localhost:3000'\n\n_url(\"api/token\");\t\t\n// return 'http://localhost:3000/api/token'\n\n_url(\"css/style.css\");\t\t\n// return 'http://localhost:3000/css/style.css'\n\n```\n\n\n## Authentication\n\nThis application comes with two type of authentication methods:\n\n`session` for working with server side rendering applications which authentication meta data is stored as session files on server and cookies in browser and browser sends this cookie with any request.\n\nYou can set the session using `login` function\n\n```javascript\nreq.login({id: \"59f4856fd3b99e1d311ef94a\", name: 'john'}, function (error) {\n    if (error) return next(error);\n    return res.redirect(\"/profile\");\n});\n```\nAlso you can use the builtin SesionAuth middleware to protect your routes.\n\n```javascript\nrouter.get(\"/profile\", SessionAuth, HomeController.profile);\n```\n\nTo logout please use the `logout` function\n\n```javascript\nreq.logout();\n```\n\n---\n`jwt` authentication suitable for building APIs.\n\nIn this type we only generate a json web token for the user payload object\nusing the `sign` function\n\n```javascript\njwt.sign(\n    user.toJSON(),\n    _config(\"jwt.secret\"),\n    {expiresIn: _config(\"jwt.expires\")}\n);\n\n// return '.eyJ1cGRhdGVkQXQiOiIyMDE3LTEwLTMwVDE3OjQxOjQzLjExOFoiLCJjcmVhdGVkQXQiOiIyMDE3LTEwLTMwVDE3OjQxOjQzLjExOFoiLCJlbWFpbCI6ImF0ZWZAZ21haWwuY29tIiwicGFzc3dvcmQiOiIkMmEkMTAkUlJZb3Z5YlFZSGx0NFRZOWNXSzhZLjd0QlozN1ZNU0p1SXZkYmNZSGVoVFRwcjlOczFEMUMiLCJmaXJzdF9uYW1lIjoic2RmIiwiX2lkIjoiNTlmNzY0NTdjNzU2MmM1ODkxYjkzNmYxIiwidXBkYXRlZF9hdCI6IjIwMTctMTAtMzBUMTc6NDE6NDMuMTE4WiIsImNyZWF0ZWRfYXQiOiIyMDE3LTEwLTMwVDE3OjQxOjQzLjExOFoiLCJsYW5nIjoiZW4iLCJzY29yZSI6MCwiaWF0IjoxNTA5Mzg1MzAzLCJleHAiOjE2MDkzODUzMDJ9.JCYlwK66EbHXsGeZw12MXC5RhUbiJIG_G3xV-2Qyvws'\n```\n\nThis token will be sent to the client (browser or mobile) and the client will store and send it every request using the query string parameter `?token=thehashhere`\n\nYou can use the built-in TokenAuth middleware to protect your routes\n\n```javascript\nrouter.get(\"/user\", TokenAuth, UserController.find);\n```\n\n---\nYou can check if user is logged in using:\n\n```javascript\nreq.isAuthenticated();\t\t// return true or false\n```\n\nYou can get the current user\n\n```javascript\nreq.user;\t\t// return a json of user object\n```\n\n## Redirection\n\nThe response method `res.back()` is added with express to redirect to the previous page.\n\n## Author\n[Basem Khirat](http://basemkhirat.com) - [basemkhirat@gmail.com](mailto:basemkhirat@gmail.com) - [@basemkhirat](https://twitter.com/basemkhirat)  \n\n\n## Bugs, Suggestions and Contributions\n\nThanks to [everyone](https://github.com/basemkhirat/express-mvc/graphs/contributors)\nwho has contributed to this project!\n\nPlease use [Github](https://github.com/basemkhirat/express-mvc) for reporting bugs, \nand making comments or suggestions.\n\n## License\n\nMIT\n\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbasemkhirat%2Fexpress-mvc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbasemkhirat%2Fexpress-mvc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbasemkhirat%2Fexpress-mvc/lists"}