{"id":19425489,"url":"https://github.com/maxtermax/dispatch-model","last_synced_at":"2026-04-10T12:31:48.840Z","repository":{"id":57212928,"uuid":"84497932","full_name":"Maxtermax/dispatch-model","owner":"Maxtermax","description":"Simple express js response custom method for dispatch query to a web api, easy, clean, fast and beautiful code","archived":false,"fork":false,"pushed_at":"2018-10-06T19:58:01.000Z","size":231,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-02-18T08:39:32.434Z","etag":null,"topics":["dispatch","dispatch-model","expressjs","mongodb","nodejs","sailjs"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Maxtermax.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-03-09T23:21:33.000Z","updated_at":"2018-10-06T19:58:02.000Z","dependencies_parsed_at":"2022-08-24T21:01:28.441Z","dependency_job_id":null,"html_url":"https://github.com/Maxtermax/dispatch-model","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maxtermax%2Fdispatch-model","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maxtermax%2Fdispatch-model/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maxtermax%2Fdispatch-model/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Maxtermax%2Fdispatch-model/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Maxtermax","download_url":"https://codeload.github.com/Maxtermax/dispatch-model/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240605843,"owners_count":19827985,"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":["dispatch","dispatch-model","expressjs","mongodb","nodejs","sailjs"],"created_at":"2024-11-10T14:03:37.512Z","updated_at":"2026-04-10T12:31:48.609Z","avatar_url":"https://github.com/Maxtermax.png","language":"JavaScript","funding_links":["https://www.paypal.me/EPalaciosMena"],"categories":[],"sub_categories":[],"readme":"[![NPM](https://nodei.co/npm/dispatch-model.png?downloads=true\u0026downloadRank=true\u0026stars=true)](https://nodei.co/npm/dispatch-model/)\n\nDispatch Model\n===================\nIs a simple custom response express method develop by [me](https://github.com/maxtermax) , member of [HACKDO FOUNDATION.](http://hackdo.co/)\n\nTo dispatch query to a web api, easy, clean, fast and **beautiful code**, it works great with [waterline mongodb driver, localDisk ](https://github.com/vanetix/waterline) and [sailsjs](http://sailsjs.com/) but must be tested with mysql driver for nodejs:\n\n If you find this module helpful  please donate [here](https://www.paypal.me/EPalaciosMena)  with the mount of you want, it helps to maintain the project and enhands all.\n\n\nInstalation\n-------------\n\n    npm install dispatch-model --save\n\nor\n\n    git clone https://github.com/Maxtermax/dispatch-model.git\n\n\nSetup with sails js\n-------------\nFollow this steps:\n\n 1. Inside the directory responses add a new response file:\n```javascript\n //api/responses/dispatchModel.js\n module.exports = require('dispatch-model');\n```\n\n**note**:  `dispatchModel.js` is just a generic name you can call this response file whereaver you want.\n\n 2. Add a model with some schema for example:\n```javascript\n  //api/models/User.js\n  module.exports = {\n   attributes: {\n    firstName: 'string',\n    lastName: 'string'\n  }\n }\n```\n\nSetup with express js\n-------------\nFollow this steps:\n\n 1. In you express app configuration add\n\n```javascript\nconst dispatchModel = require('dispatch-model');\napp.use(\"*\",(req, res, next)=\u003e {\n  res.dispatchModel = dispatchModel;\n  next();\n});\n```\n\n Now let the magic begin inside some controller now can dispatch the User model like that:\n``` javascript\nmodule.exports = {\n  serve: function(req, res) {\n    let query = User.create({firstName: \"john\", lastName: \"doe\"});\n    res.dispatchModel(query);\n  }//end serve method\n}//end UserController\n```\n\n\n\nthe `dispatchModel` is now aviable for use, this take some arguments for dispatch some query, the first one is a **Promise**  that is usually a query from the database that return a result, with this code you would get:\n```javascript\n{\n  \"data\": {\n    \"firstName\": \"john\",\n    \"lastName\": \"doe\",\n    \"createdAt\": \"2017-03-10T02:51:15.184Z\",\n    \"updatedAt\": \"2017-03-10T02:51:15.184Z\",\n    \"id\": 34\n  },\n  \"status\": 200\n}\n```\n\n\n\n\n\n\nDispatch model, wrap an transform the data for you in this schema:\nfirt all response that get success in his query must return and json object with **data** as main attribute that represent the result of **query** in the database, and **status** that represent the status of response from the web API.\n\n\n\nResponse cases\n-------------\nDispatch model, **must** take as first argument some **Promise** that return some kind a information, and can also get a **second** argument which is is usable to transform the response.\n\nAs second argument **responseCases** can transform the data depend on manies escenarios like:\n\n - **[success](https://www.npmjs.com/package/dispatch-model#success)**\n   - **notFound**\n - **[errors](https://www.npmjs.com/package/dispatch-model#errors)**\n   - **notFound**\n   - **notAllow**\n   - **forbidden**\n   - **badRequest**\n   - **conflict**\n   - **serverError**\n\nExmaple:\n```javascript\nmodule.exports = {\n  // UserController.js\n  serve: function(req, res) {\n    let responseCases = {\n      success: {\n        omit: ['lastName'],\n        status: 201 //change status to created\n      }\n    }\n    let query = User.create({firstName: \"john\", lastName: \"doe\"});\n    res.dispatchModel(query, responseCases);\n  }//end serve method\n}//end UserController\n```\nIn case of **success** indicate that will return something like:\n\n```javascript\n{\n  \"data\": {\n    \"firstName\": \"john\",\n    \"createdAt\": \"2017-03-10T03:32:05.771Z\",\n    \"updatedAt\": \"2017-03-10T03:32:05.771Z\",\n    \"id\": 36\n  },\n  \"status\": 201\n}\n```\n\n\n\nThe **success** option can get few attibutes like:\n\nAttribute      | Required | Type\n--------       | -----    | ----\n**omit**           | false    | array\n**pick**           | false    | array\n**authentication** | false    | boolean\n**session**        | false    | json\n**status**         | false    | integer\n**map**            | false    | Function\n**beforeResponse** | false    | Function\n**afterResponse**  | false    | Function\n**view**           | false    | string\n\n## Success\n\n - **omit**: list of attributes that you wanna omit of the query response\n```javascript\n  showAll: function(req, res) {\n    let responseCases = {\n      success: {\n        omit: ['firstName']\n      }\n    }\n    let query = User.find({});\n    res.dispatchModel(query, responseCases);\n  },//end showAll\n```\nreturn :\n```javascript\n{\n  \"data\": [\n    {\n      \"lastName\": \"doe\",\n      \"createdAt\": \"2017-03-10T04:20:21.710Z\",\n      \"updatedAt\": \"2017-03-10T04:20:21.710Z\",\n      \"id\": 38\n    }\n  ],\n  \"status\": 200\n}\n```\n\n - **pick**: list of attributes that you wanna pick of the query response\n```javascript\nmodule.exports = {\n  serve: function(req, res) {\n    let responseCases = {\n      success: {\n       pick: ['firstName']\n     }\n   }\n\n   let query = User.find({});\n   res.dispatchModel(query, responseCases);\n  }//end serve\n}\n```\n return :\n```javascript\n{\n  \"data\": [\n    {\n    \"firstName\": \"john\"\n    }\n  ],\n  \"status\": 200\n}\n```\n\n - **authentication**:  boolean attributes that indicate that yout wanna save some\n - **session**: object that represent information that you wanna store in the session, for example:\n\n```javascript\nmodule.exports = {\n  createAndAuth: function(req, res) {\n    let responseCases = {\n      success: {\n        authentication: true,\n        session: {\n          firstName: true\n        }\n      }\n    }\n\n    let query = User.create({firstName: \"john\", lastName: \"doe\"});\n    res.dispatchModel(query, responseCases);\n  }//end createAndAuth\n}\n```\nthis code will create a user and save a session with the **firstName**  and now is avaible in **req.session.firstName**\n\n**Note:**  When wanna use **session** you must use **authentication**  set in **true**\n\n - **status**\n  Status is usable for indicate the status code of the response in the web api, this que use in all cases.\n```javascript\nmodule.exports = {\n  serve: function(req, res) {\n    let responseCases = {\n      success: {\n       status: 202 //change the default status code to 203 Accepted\n     }\n   }\n\n   let query = User.find({});\n   res.dispatchModel(query, responseCases);\n  }//end serve\n}\n```\nreturn:\n```javascript\n{\n  \"data\": [\n    {\n      \"firstName\": \"john\"\n    }\n  ],\n  \"status\": 202\n}\n```\n\n - **map**\nThis option can be used for map the response of the query to the database, example:\n\n```javascript\nmodule.exports = {\n  showAll: function(req, res) {\n    let responseCases = {\n      success: {\n        map: function(data, next) {\n          data.fullName = data.firstName+\" \"+data.lastName;\n          return data;\n        }\n      }\n    }\n    let query = User.find({});\n    res.dispatchModel(query, responseCases);\n  }//end showAll\n}\n```\nreturn:\n```javascript\n{\n  \"data\": [\n    {\n      \"firstName\": \"john\",\n      \"lastName\": \"doe\",\n      \"fullName\": \"john doe\"\n    }\n  ],\n  \"status\": 200\n}\n```\n\n - **beforeResponse**\nThis method can be used for do something before response, this is called when the query to the database is done, examples:\n\n```javascript\nmodule.exports = {\n  showAll: function(req, res) {\n    let responseCases = {\n      success: {\n        beforeResponse: function(partialData, next) {\n          let owner = partialData.data.id;\n          Pets.find({owner}).then(function(pet) {\n            //do some with you pet\n            next();\n          })\n          .catch((error)=\u003e{\n            if(error.message === \"customError\") return next(new Error(\"customError\"));\n            next(new Error(\"serverError\"));\n          })\n        }\n       },\n       errors: {\n        otherwise: {\n          customError: {\n            details: \"my custom error detail\",\n            status: 400\n          }\n        }\n      }\n    }\n    let query = User.find({});\n    res.dispatchModel(query, responseCases);\n  }//end showAll\n}\n```\n**Note:**  You **must**  call **next** method to continue the process otherwise it never response, in case that something go wrong you can throw and **error** that will be **catched** by the error cases, if you are using  **mongoose.js** you migth need to use [toObject](http://mongoosejs.com/docs/api.html#document_Document-toObject) or [toJSON](http://mongoosejs.com/docs/guide.html) in **beforeResponse** or **map**\n\n\nIn case of **success**  return:\n\n```javascript\n{\n  \"data\": [\n    {\n      \"firstName\": \"john\",\n      \"lastName\": \"doe\"\n    }\n  ],\n  \"status\": 200\n}\n```\n\n\nIn case of **customError**  return:\n\n```javascript\n{\n  \"data\": null,\n  \"details\": \"my custom error detail\",\n  \"status\":  400\n}\n```\n\nIn case of **serverError**  return:\n\n```javascript\n{\n  \"data\": null,\n  \"details\": \"Internal server error.\",\n  \"status\":  500\n}\n```\n\n - **afterResponse**\nThis method can be used for do something after response, this is called when the response is done, examples:\n\n```javascript\nmodule.exports = {\n  showAll: function(req, res) {\n    let responseCases = {\n      success: {\n        afterResponse: function(data) {\n          console.log(\"data response was: \", data);\n        }\n      }\n    }\n    let query = User.find({});\n    res.dispatchModel(query, responseCases);\n  }//end showAll\n}\n```\n\n - **view**\nAsuming that you has set some templete engine like [handlebar](http://handlebarsjs.com/) now you can response by **render** a view, example:\n\n```javascript\nmodule.exports = {\n  showAll: function(req, res) {\n    let responseCases = {\n      success: {\n       view: \"path/to/template\"\n     }\n   }\n   let query = User.find({});\n   res.dispatchModel(query, responseCases);\n  }//end showAll\n}\n```\n**Note:** the **view** option can be used in all cases, and must be equal to the path of you template, this change depend of the **template engine**\n\n## Errors\nThe **errors** option can get a few arguments like:\nAttribute      | Required | Type\n--------       | -----    | ----\n**notFound**        | false    | json\n**notAllow**        | false    | json\n**forbidden**       | false    | json\n**badRequest**       | false    | json\n**conflict**       | false    | json\n**serverError**       | false    | json\n**otherwise**      | false | json\n\n\n**Note:**   To trigger any of this **errors responses**, the **Promise** argument must **throw**  or **reject** an [error](https://nodejs.org/api/errors.html#errors_new_error_message) with a **message** called the same way that the error.\n\nThe **otherwise** is special and represent a generic error that **is not contemplated**  in the default errors responses list of  **dispatchModel** , this mean that you que used like a kind a **custom response error.**\n\nAll of them take as schema to response this:\n\nAttribute      | Required | Type\n--------       | -----    | ----\ndetails        | false    | string\nstatus         | false    | integer\n**generic attribute** | false | json\n\nAll the errors cases return the same schema, unless that you use a **generic attribute** to add something, example:\n\n```javascript\n  showAll: function(req, res) {\n    let responseCases = {\n      errors: {\n        notFound: {\n          details: \"my custom message for notFound\",\n          myGenerictData: \"Hola mundo\"\n        },\n        otherwise: {\n          myCustomError: {\n            details: \"my custom message\",\n            status: 304\n          }\n        }\n      }\n    }\n    let query = User.beHappy({});\n    res.dispatchModel(query, responseCases);\n  }//end showAll\n```\nIn case of  **notFound** return:\n\n```javascript\n{\n  \"data\": null\n  \"details\": \"my custom message for notFound\"\n  \"status\": 404,\n  \"myGenerictData\": \"Hola mundo\"\n}\n```\n**Note:**  the **notFound** can be use inside of **success** too.\n\nIn case of  **myCustomError** return:\n\n```javascript\n{\n  \"data\": null\n  \"details\": \"my custom message\"\n  \"status\":  304\n}\n```\n\n**Note:** in case that dispatchModel get a unexpected error, that was not set in any where, it will response with a **204** **No content**\n\n If you find this module helpful  please donate [here](https://www.paypal.me/EPalaciosMena)  with the mount of you want, it helps to maintain the project and enhands all.\n\nSo this is all for now, be in touch if you have some issue or want to contribute to this project.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxtermax%2Fdispatch-model","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaxtermax%2Fdispatch-model","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxtermax%2Fdispatch-model/lists"}