{"id":21623478,"url":"https://github.com/dylanfoster/parch","last_synced_at":"2025-07-29T06:32:44.991Z","repository":{"id":57143821,"uuid":"61052110","full_name":"dylanfoster/parch","owner":"dylanfoster","description":"Restify + Sequelize","archived":false,"fork":false,"pushed_at":"2018-08-30T02:56:13.000Z","size":1392,"stargazers_count":4,"open_issues_count":4,"forks_count":2,"subscribers_count":3,"default_branch":"develop","last_synced_at":"2025-07-26T10:41:39.349Z","etag":null,"topics":["api","framework","rest-api","restful","restify","router","sequelize"],"latest_commit_sha":null,"homepage":"http://parch-js.github.io","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dylanfoster.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-06-13T16:28:22.000Z","updated_at":"2021-11-14T15:42:27.000Z","dependencies_parsed_at":"2022-09-05T12:31:32.378Z","dependency_job_id":null,"html_url":"https://github.com/dylanfoster/parch","commit_stats":null,"previous_names":[],"tags_count":40,"template":false,"template_full_name":null,"purl":"pkg:github/dylanfoster/parch","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dylanfoster%2Fparch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dylanfoster%2Fparch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dylanfoster%2Fparch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dylanfoster%2Fparch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dylanfoster","download_url":"https://codeload.github.com/dylanfoster/parch/tar.gz/refs/heads/develop","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dylanfoster%2Fparch/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267639569,"owners_count":24119780,"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","status":"online","status_checked_at":"2025-07-29T02:00:12.549Z","response_time":2574,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["api","framework","rest-api","restful","restify","router","sequelize"],"created_at":"2024-11-25T00:13:06.277Z","updated_at":"2025-07-29T06:32:44.949Z","avatar_url":"https://github.com/dylanfoster.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# parch\n\n[![Build Status](https://travis-ci.org/dylanfoster/parch.svg?branch=master)](https://travis-ci.org/dylanfoster/parch)\n[![Coverage Status](https://coveralls.io/repos/github/dylanfoster/parch/badge.svg?branch=develop)](https://coveralls.io/github/dylanfoster/parch?branch=develop)\n[![bitHound Overall Score](https://www.bithound.io/github/dylanfoster/parch/badges/score.svg)](https://www.bithound.io/github/dylanfoster/parch)\n\n\u003e [Restify](http://restify.com/) + [Sequelize](http://docs.sequelizejs.com/en/latest/)\n\nParch combines restify and sequelize to bring you a powerful yet easy setup for\nyour API\n\n## Installation\n\nnpm\n\n```bash\nnpm install --save parch\n```\n\nyarn\n\n```bash\nyarn add --save parch\n```\n\n## Usage\n\n- [Application](#application)\n- [Router](#router)\n  - [#resource](#resource)\n  - [#route](#route)\n  - [#namespace](#namespace)\n- [Controller](#controller)\n  - [lifecycle hooks](#controller-lifecycle)\n  - [hooks](#controller-hooks) **deprecated**\n  - [nested controllers](#nested-controllers)\n- [Model](#model)\n- [Serializers](#serializers)\n- [Associations](#associations-wip)\n- [Authentication](#authentication-and-authorization)\n- [Application Initializers](#application-initializers)\n- [Logging](#logging)\n- [Error handling](#error-handling-and-responses)\n  - [Error Codes](#errors)\n  - [Responses](#responses)\n\n\n### Application\n\nFor a full list of available options [see below](#options)\n\n```javascript\nconst parch = require(\"parch\");\n\n// define your app\nconst app = new parch.Application({\n  authentication: {\n    secretKey: \"ssshhh\",\n    unauthenticated: [/\\/posts[\\s\\S]*/, \"/users/resetPassword\"]\n  },\n\n  controllers: {\n    dir: path.resolve(__dirname, \"controllers\")\n  },\n\n  database: {\n    connection: {\n      username: \"postgres\",\n      password: \"postgres\",\n      database: \"postgres\",\n      host:  \"localhost\",\n      dialect: \"postgres\",\n      logging: false\n    },\n\n    models: {\n      dir: path.resolve(__dirname, \"models\")\n    }\n  },\n\n  initializers: {\n    dir: path.resolve(__dirname, \"controllers\")\n  },\n\n  logging: {\n    dir: path.resolve(__dirname, 'logs'),\n    logger: Bunyan.createLogger(),\n    serializers: {\n      req(req) {\n        return {\n          url: req.url\n        }\n      },\n\n      res(res) {\n        return {\n          statusCode: res.statusCode\n        }\n      }\n    }\n  },\n\n  namespace: \"api\",\n\n  server: {\n    name: \"my-app\",\n    certificate: \"/path/to/my.crt\",\n    key: \"/path/to/my.key\",\n    log: Bunyan.createLogger(),\n    middlewares: [\n      restify.bodyParser(),\n      restify.queryParser(),\n      myCustomMiddleware()\n    ]\n  }\n});\n\n// wire up your routes\napp.map(function () {\n  this.resource(\"user\");\n  this.route(\"user/resetPassword\", {\n    using: \"users:resetPassword\", // controller:method\n    method: \"post\" // request method\n  });\n});\n\napp.start(3000).then(() =\u003e {\n  console.log(\"App listening.\")\n});\n```\n\nThe above will create the following route mapping\n\n```\nGET    /users               =\u003e UserController.index\nGET    /users/:userId       =\u003e UserController.show\nPOST   /users               =\u003e UserController.create\nPUT    /users/:userId       =\u003e UserController.update\nDELETE /users/:userId       =\u003e UserController.destroy\nPOST   /users/resetPassword =\u003e UserController.resetPassword\n```\n\n### Router\n\nThe router handles route management and normalization, creating CRUD endpoints\nfor resources and normalizing all paths.\n\n#### Resource\n\nUse `resource` to generate a set of CRUD endpoints.\n\n```javascript\napp.map(function () {\n  this.resource(\"user\");\n});\n\n/**\n * GET    /users               =\u003e UserController.index\n * GET    /users/:userId       =\u003e UserController.show\n * POST   /users               =\u003e UserController.create\n * PUT    /users/:userId       =\u003e UserController.update\n * DELETE /users/:userId       =\u003e UserController.destroy\n */\n```\n\n#### Route\n\nUse `route` to define a one off route.\n\n```javascript\napp.map(function () {\n  this.route(\"/foos/bar\", {\n    using: \"foo:getBar\",\n    method: \"get\"\n  });\n});\n\n/**\n * GET /foos/bar =\u003e FooController.getBar\n */\n```\n\n#### Namespace\n\nUse `namespace` to group a set of `routes` under a single base path. Namespace\ntakes an array of routes so follow the route api (with the addition of `path`)\n\n```javascript\napp.map(function () {\n  this.namespace(\"users/:userId\", [\n    { path: \"/account\", using: \"user:getAccount\", method: \"get\" },\n    { path: \"/image\", using: \"user:setImage\", method: \"post\" }\n  ]);\n});\n\n/**\n * GET /users/:userId/account =\u003e UserController.getAccount\n * POST /users/:userId/image  =\u003e UserController.setImage\n */\n```\n\n### Controller\n\n`lib/controllers/users.js`\n\n```javascript\nconst parch = require(\"parch\");\n\nclass UserController extends parch.Controller {\n  constructor(options) {\n    super(options);\n  }\n\n  index(req, res, next) {\n    this.store.findAll(req.query).then(records =\u003e {\n      /**\n       * {\n       *   users: [{\n       *   ...\n       *   }]\n       * }\n       */\n       res.send(this.STATUS_CODES.SUCCESS, records);\n    }).catch(next);\n  }\n\n  show(req, res, next) {\n    this.store.findOne(req.params.id).then(record =\u003e {\n      /**\n       * {\n       *   user: {\n       *   ...\n       *   }\n       * }\n       */\n       res.send(this.STATUS_CODES.SUCCESS, record);\n    }).catch(next);\n  }\n\n  create(req, res, next) {\n    this.store.createRecord(req.body.user).then(record =\u003e {\n      /**\n       * {\n       *   user: {\n       *   ...\n       *   }\n       * }\n       */\n       res.send(this.STATUS_CODES.CREATED, record);\n    }).catch(next);\n  }\n\n  update(req, res, next) {\n    this.store.updateRecord(req.params.id, req.body).then(updatedRecord =\u003e {\n      /**\n       * {\n       *   user: {\n       *   ...\n       *   }\n       * }\n       */\n       res.send(this.STATUS_CODES.SUCCESS, record);\n    }).catch(next);\n  }\n\n  destroy(req, res, next) {\n    this.store.destroyRecord(req.params.id).then(() =\u003e {\n      res.send(this.STATUS_CODES.NO_CONTENT);\n    }).catch(next);\n  }\n\n  resetPassword(req, res, next) {\n    this.store.findOne(req.params.id).then(record =\u003e {\n      record.password = req.body.password;\n      return record.save();\n    }).then(record =\u003e {\n      res.send(this.STATUS_CODES.SUCCESS);\n    }).catch(next);\n  }\n}\n```\n\n### Controller Hooks [Deprecated]\n\n**Controller hooks in this fashion are deprecated. Please use `beforeModel`, `model`, and `afterModel` structure instead. [see here for more](#controller-lifecycle)**\n\nController hooks allow for pre and post processing of requests. Both before and\nafter hooks are supported as well as any additional methods added when using\n`Controller#route` or `Controller#namespace`. When using the `after` hook, make\nsure to call next after sending your response.\n\n```javascript\nclass UserController extends parch.Controller {\n  constructor(options) {\n    super(options);\n\n    this.hooks = {\n      // The hook name must match the method\n      index: {\n        before(req, res, next) {\n          return checkPermissions().then(() =\u003e {\n            next();\n          }).catch(next);\n        },\n        after(req, res, next) {\n          req.log.child().info(\"post processing\");\n        }\n      }\n    };\n  }\n\n  index(req, res, next) {\n    res.send(200);\n    next();\n  }\n}\n```\n\n### Nested Controllers\n\nOrganizing your controllers into groups can make things more manageable. By storing\neach action in a separate class, you will have tighter control over your logic.\n\n```\n├── lib\n│   ├── controllers\n│   │   ├── post\n│   │   │   ├── create.js\n│   │   │   ├── destroy.js\n│   │   │   ├── index.js\n│   │   │   ├── show.js\n│   │   │   └── update.js\n│   │   └── users\n│   │       ├── create.js\n│   │       ├── destroy.js\n│   │       ├── index.js\n│   │       ├── show.js\n│   │       └── update.js\n```\n\n### Controller Lifecycle\n\nController lifecycle can be handled by three main hooks. Each of these hooks take\nthe same arguments `(req, res, next)`\n\n#### `beforeModel`\n\nThe `beforeModel` hook runs before the main model hook. In this method you have access to the request and response objects and it is assumed that the response\nlifecycle has not been completed.\n\n```javascript\nexport default class UserListController {\n  beforeModel(req, res, next) {\n    return utils.permissions(req)\n      .then(() =\u003e next())\n      .catch(next);\n  }\n}\n```\n\n#### `model`\n\nThe `model` hook is the main action of your controller class. This is where the\nresponse object is assumed to end. **Note: if you also define an `afterModel` hook\nyou _must_ call next in the model hook.\n\n```javascript\nexport default class UserListController {\n  model(req, res, next) {\n    this.store.findAll(\"user\").then(users =\u003e {\n      res.send(this.STATUS_CODES.SUCCESS, users);\n\n      next();\n    }).catch(next);\n  }\n}\n```\n\n#### `afterModel`\n\nThe `afterModel` is the last hook in the controller lifecycle. Here you can do\nthings like metrics or audit logs\n\n```javascript\nexport default class UserListController {\n  afterModel(req, res, next) {\n    req.log.debug(\"afterModel hook for user list\");\n  }\n}\n```\n\n### Model\n\nModels are defined following the [sequelize define](http://docs.sequelizejs.com/manual/tutorial/models-definition.html)\npattern. [Options](http://docs.sequelizejs.com/manual/tutorial/models-definition.html) for the model definition can be passed to the constructor's `super` call\n\n`lib/models/user.js`\n\n```javascript\nclass UserModel extends parch.Model {\n  constructor() {\n    super({\n      classMethods: {\n      },\n\n      getterMethods: {\n      },\n\n      hooks: {\n      },\n\n      instanceMethods: {\n      }\n    });\n  }\n\n  associate(User, models) {\n    User.hasMany(models.Posts);\n    User.hasMany(models.User, { as: \"Parent\" });\n  }\n\n  define(DataTypes) {\n    const user = {\n      email: {\n        type: DataTypes.STRING,\n        validate: { isEmail: true }\n      }\n    };\n\n    return user;\n  }\n}\n```\n\n### Serializers\n\nSerializers allow you to control how data is transformed and sent to the client.\nEach model you define can also define an accompanying serializer to transform its\ndata. If you do not define one yourself, Parch will use the [JSONSerializer](https://github.com/dylanfoster/json-serializer)\n\nJSONSerializer is the most basic of all the serializers, offering only a `normalizeResponse` method, which in turn just returns the instance or instance array.\nTo extend this behavior, the [RESTSerializer](https://github.com/dylanfoster/rest-serializer) will nest your record under a\nsingular or plural record key (e.g. `{ user: record  }` or `{ users: [records] }`), as well as automatically add each hasMany/belongsTo relationship as an array\nof ids, removing the need for you to transform these yourself. The [JSONAPISerializer](https://github.com/dylanfoster/json-api-serializer)(TBD) takes this even\nfurther, ensuring your data is transform following the JSONAPI spec\n\n`lib/serializers/user.js`\n\n```javascript\nimport { RestSerializer } from \"parch\";\n\nexport default UserSerializer extends RestSerializer {\n  keyForRecord(record, singular) {}\n\n  keyForRelationship(association) {}\n\n  normalizeArrayResponse(instances, fallbackName) {}\n\n  normalizeRelationships(instance) {}\n\n  normalizeSingularResponse(instance) {}\n}\n```\n\n## Authentication and Authorization\n\nAuthorization is handled using [jwt](https://jwt.io/), with more\noptions coming in the future. To disable auth for specific routes, use the\n`authentication.unauthenticated` array. Empty by default, you can give a string\nor regex expression to skip your unauthenticated routes\n\n```javascript\nconst parch = new parch.Application({\n  authentication: {\n    unauthenticated: [/\\/posts[\\s\\S]*/, \"/users/resetPassword\"]\n  }\n});\n```\n\nIn order to authenticate a user, create and sign a JWT token to send back to the\nclient. The authorization middleware will then look for this token in the\n`Authorization` header. [see jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken)\n\n```javascript\n// lib/controllers/user_controller.js\n\nconst jwt = require(\"jsonwebtoken\");\n\nconst config = require(\"../../config\");\n\nclass UserController extends parch.Controller {\n  constructor(settings) {\n    super(settings);\n  }\n\n  authenticate(req, res, next) {\n    this.model.findOne({ where: { email: req.body.email }}).then(user =\u003e {\n      if (user) {\n        const token = jwt.sign(user, config.secret);\n\n        res.send(200, { token });\n      } else {\n        throw new this.errors.UnauthorizedError(\"email or password is invalid\");\n      }\n    });\n  }\n}\n\nmodule.exports = UserController;\n\n...\n// lib/app.js\n\napp.map(function () {\n  this.route(\"/users/authenticate\", { using: \"user:authenticate\", method: \"post\" });\n});\n```\n\n```bash\ncurl http://my-server.com/protectedRoute -H 'Authorization: Bearer \u003ctoken\u003e'\n```\n\n## Application Initializers\n\nInitializers allow you to accomplish many things during application boot.\nRegistering mixins, add custom application logic, and adding services can all be\ndone in an initializer and attached to the application instance. Parch will run\nyour initializers in alphanumeric order. This means that if you need to run them\nin a specific order you should prefix them in a way that will accomplish that.\n\n\n`your-app/lib/initializers/my-awesome-initializer.js`\n\n```javascript\n\"use strict\";\n\nconst Worker = require(\"../worker\");\n\nmodule.exports = {\n  initialize(appInstance, registry) {\n    appInstance.foo = \"bar\";\n\n    app.worker = new Worker();\n  },\n\n  name: \"my-awesome-initializer\"\n};\n```\n\n## Logging\n\nLogging is handled automatically for you. All requests and responses will be logged\nusing a custom [Bunyan instance](https://github.com/dylanfoster/parch/blob/master/src/logger.js).\n\n## Error handling and responses\n\n### Errors\n\nError handling is done using [restify-errors](https://github.com/restify/errors).\nWhen using controller helpers (`findAll`, `findOne`, etc) errors are handled\nautomatically for you. Just catch your Promise with `next` and parch will handle\nthe rest.\n\n```javascript\nshow(req, res, next) {\n  this.findOne(req.params.id).then(user =\u003e {\n  }).catch(next);\n}\n\n/**\n * { code: \"NotFound\", message: \"User with id '1' does not exist\" }\n */\n```\n\nErrors handled by parch:\n\n - `findOne`:\n   - `NotFound`: The record does not exist\n - `createRecord`:\n   - `BadRequest`: Request body was missing or invalid\n   - `UnprocessableEntity`: Model validations failed\n - `updateRecord`:\n   - `BadRequest`: Request body was missing or invalid\n   - `UnprocessableEntity`: Model validations failed\n - `destroyRecord`:\n   - `NotFound`: The record does not exist\n\nNeed to handle your own errors? `controller.errors` contains all of [restify-errors](https://github.com/restify/errors)' errors\n\n### Responses\n\nParch also helps you standardize on your response statuses. Using [controller.STATUS_CODES](https://github.com/dylanfoster/parch/blob/develop/src/utils/status_codes.js)\nyou'll never have to worry about which status to send.\n\n```javascript\nshow(req, res, next) {\n  res.send(this.STATUS_CODES.SUCCESS) // 200\n}\n```\n\n## Options\n\n  - **authentication**\n    - `secretKey(String)`: A secret string used to sign JWT tokens\n    - `unauthenticated(Array)`: an array of strings or regex patterns to skip authentication.\n  - **controllers**\n    - `dir(String)`: The path to your controllers directory. **Default**: `__dirname/controllers`\n  - **database**\n    - `connection(Object)` [Sequelize connection options](http://docs.sequelizejs.com/en/latest/docs/getting-started/)\n    - `models`\n      - `dir(String)`: The path to your models directory. **Default**: `__dirname/models`\n  - **initializers**\n    - `dir(String)`: The path to your initializers directory. **Default**: `__dirname/initializers`\n  - **logging**\n    - `dir(String)`: Path where logs should be saved\n    - `logger(Object)` **optional**: An optional logger instance\n    - `serializers(Object)`:\n      - `req(Function)`: your request serializer. takes the request as its only argument\n      - `res(Function)`: your response serializer. takes the response as its only argument\n  - **namespace**: Set the base namespace for all routes and resources (e.g. `api`)\n  - **serializers**\n    - `dir(String)`: The path to your serializers directory. **Default*: `__dirname/serializers`\n  - **server** All options (*with the exception of `middlewares`*) are passed directly to [restify](http://restify.com/#creating-a-server)\n    - `log`: defaults to parch's [bunyan instance](https://github.com/dylanfoster/parch/blob/master/src/logger.js) but can be overridden\n    - `middlewares(Array)`: merged with parch's [default middlwares](https://github.com/dylanfoster/parch/blob/master/src/application.js#L24-L31)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdylanfoster%2Fparch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdylanfoster%2Fparch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdylanfoster%2Fparch/lists"}