{"id":18829901,"url":"https://github.com/rxstack/sequelize-service","last_synced_at":"2026-05-08T04:49:32.625Z","repository":{"id":34079860,"uuid":"168143105","full_name":"rxstack/sequelize-service","owner":"rxstack","description":"SequelizeService for @rxstack/platform","archived":false,"fork":false,"pushed_at":"2023-03-04T03:29:58.000Z","size":674,"stargazers_count":1,"open_issues_count":6,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-01-31T09:45:47.483Z","etag":null,"topics":["mysql","nodejs","rxstack","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","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/rxstack.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-01-29T11:25:03.000Z","updated_at":"2022-02-04T15:20:26.000Z","dependencies_parsed_at":"2024-12-30T06:26:48.145Z","dependency_job_id":"e1011c79-b4b9-4d0b-a935-6976bd4a4fae","html_url":"https://github.com/rxstack/sequelize-service","commit_stats":{"total_commits":26,"total_committers":1,"mean_commits":26.0,"dds":0.0,"last_synced_commit":"3b495fb0a00f0207681d823e262a61cc10ad7c5d"},"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rxstack%2Fsequelize-service","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rxstack%2Fsequelize-service/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rxstack%2Fsequelize-service/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rxstack%2Fsequelize-service/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rxstack","download_url":"https://codeload.github.com/rxstack/sequelize-service/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239765547,"owners_count":19693156,"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":["mysql","nodejs","rxstack","typescript"],"created_at":"2024-11-08T01:46:57.909Z","updated_at":"2026-01-23T20:30:17.550Z","avatar_url":"https://github.com/rxstack.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# The RxStack Sequelize Service\n\n[![Build Status](https://travis-ci.org/rxstack/sequelize-service.svg?branch=master)](https://travis-ci.org/rxstack/sequelize-service)\n[![Maintainability](https://api.codeclimate.com/v1/badges/0605416059f00234dbc3/maintainability)](https://codeclimate.com/github/rxstack/sequelize-service/maintainability)\n[![Test Coverage](https://api.codeclimate.com/v1/badges/0605416059f00234dbc3/test_coverage)](https://codeclimate.com/github/rxstack/sequelize-service/test_coverage)\n\n\u003e Sequelize service that implements [@rxstack/platform adapter API and querying syntax](https://github.com/rxstack/rxstack/tree/master/packages/platform#services).\n\n## Table of content\n\n- [Installation](#installation)\n- [Setup](#setup)\n- [Module Options](#module-options)\n- [Service Options](#service-options)\n- [Usage](#usage)\n    - [Create interfaces](#usage-interfaces)\n    - [Create sequelize models](#usage-models)\n    - [How to use in controller](#usage-controller)\n    - [How to build queries with query-filter](#usage-query-filter)\n- [Commands](#commands)\n    - [Sync](#commands-sync)\n    - [Drop](#commands-drop)\n- [Validation Observer](#validation-observer)\n\n## Installation\n\n```\nnpm install @rxstack/sequelize-service --save\n\n// peer depencencies\nnpm install --no-save @rxstack/core@^0.7 @rxstack/platform@^0.7 @rxstack/exceptions@^0.6 @rxstack/query-filter@^0.6 @rxstack/security@^0.7 @rxstack/async-event-dispatcher@^0.6 @rxstack/service-registry@^0.6 winston@^3.3.3\n```\n\nand add one of the following:\n\n```bash\nnpm install --save pg pg-hstore\nnpm install --save mysql2 // For both mysql and mariadb dialects\nnpm install --save sqlite3\nnpm install --save tedious // MSSQL\n```\n\n[Read sequelize docs](http://docs.sequelizejs.com/)\n\n## \u003ca name=\"setup\"\u003e\u003c/a\u003e  Setup\n`SequelizeServiceModule` needs to be registered in the `application`. Let's create the application:\n\n\u003e In the example we are using `mysql`.\n\n```typescript\nimport {Application, ApplicationOptions} from '@rxstack/core';\nimport {SequelizeServiceModule} from '@rxstack/sequilize-service';\n\nexport const APP_OPTIONS: ApplicationOptions = {\n  imports: [\n    SequelizeServiceModule.configure({\n      connection: {\n        host: process.env.MYSQL_HOST,\n        database: process.env.MYSQL_DATABASE,\n        username: process.env.MYSQL_USER,\n        password: process.env.MYSQL_PASSWORD,\n        dialect: 'mysql',\n        define: {\n          timestamps: false\n        }\n      },\n      logger: {\n        enabled: true\n      }\n    })\n  ],\n  providers: [\n    // ...\n  ]\n};\n\nnew Application(APP_OPTIONS).start();\n```\n\n## \u003ca name=\"module-options\"\u003e\u003c/a\u003e Module Options\n\n- `connection`: [sequelize options](http://docs.sequelizejs.com/manual/installation/getting-started.html)\n- `logger.enabled`: enable query logging (defaults to false)\n- `logger.level`: logging level\n\n## \u003ca name=\"service-options\"\u003e\u003c/a\u003e Service Options\nIn addition to [service base options](https://github.com/rxstack/rxstack/tree/preparing-release/packages/platform#services-options)\nwe need to set the following options:\n\n- `model`: [sequelize model](http://docs.sequelizejs.com/manual/tutorial/models-definition.html)\n\n## \u003ca name=\"usage\"\u003e\u003c/a\u003e  Usage\n\n### \u003ca name=\"usage-interfaces\"\u003e\u003c/a\u003e Create interfaces\nFirst we need to create `model interface` and `InjectionToken`:\n\n```typescript\nimport {InjectionToken} from 'injection-js';\nimport {SequelizeService} from '@rxstack/sequelize-service';\n\nexport interface Product {\n  id: string;\n  name: string;\n}\n\nexport const PRODUCT_SERVICE = new InjectionToken\u003cSequelizeService\u003cProduct\u003e\u003e('PRODUCT_SERVICE');\n```\n\n### \u003ca name=\"usage-models\"\u003e\u003c/a\u003e Create sequelize models\n\n\n```typescript\nimport {DataTypes, Sequelize} from 'sequelize';\nimport {ModelStatic} from '@rxstack/sequelize-service';\n\nexport const defineProduct = (connection: Sequelize): ModelStatic =\u003e  {\n  return \u003cModelStatic\u003econnection.define('product', {\n    _id: {\n      type: DataTypes.INTEGER,\n      primaryKey: true,\n      autoIncrement: true\n    },\n    name: {\n      type: DataTypes.STRING, allowNull: false, unique: true,\n      validate: {\n        notEmpty: true\n      }\n    }\n  });\n};\n```\n\ndefine all models in a singe function (useful to set associations) :\n\n```typescript\nimport {DataTypes, Sequelize} from 'sequelize';\nimport {ModelStatic} from '@rxstack/sequelize-service';\nimport {defineProduct} from './product.schema';\n\nexport const defineModels = (connection: Sequelize): {[key: string]: ModelStatic} =\u003e  {\n\n  const product = defineProduct(connection);\n  // define other models here\n  // ...\n  // define associations here\n\n  return {\n    product\n    // ...\n  };\n};\n```\n\nthen register the service and models in the application provides:\n\n```typescript\nimport {InjectionToken} from 'injection-js';\nimport {ApplicationOptions} from '@rxstack/core';\nimport {SequelizeService} from '@rxstack/sequelize-service';\nimport {SEQUELIZE_CONNECTION_TOKEN} from '@rxstack/sequelize-service'\nimport {ModelStatic} from '@rxstack/sequelize-service';\nimport {Sequelize} from 'sequelize';\n\nexport const SEQUELIZE_MODELS = new InjectionToken\u003c{[key: string]: ModelStatic}\u003e('SEQUELIZE_MODELS'); \n\nexport const APP_OPTIONS: ApplicationOptions = {\n  // ...\n  providers: [\n    {\n      provide: SEQUELIZE_MODELS,\n      useFactory: (conn: Sequelize) =\u003e defineModels(conn),\n      deps: [SEQUELIZE_CONNECTION_TOKEN],\n    },\n    {\n      provide: PRODUCT_SERVICE,\n      useFactory: (conn: Sequelize, models: {[key: string]: ModelStatic}) =\u003e {\n        return new SequelizeService\u003cProduct\u003e({\n          idField: '_id', defaultLimit: 25, model: models['product']\n        });\n      },\n      deps: [SEQUELIZE_CONNECTION_TOKEN, SEQUELIZE_MODELS],\n    },\n  ]\n};\n```\n\n### \u003ca name=\"usage-controller\"\u003e\u003c/a\u003e How to use in controller\n\n```typescript\nimport {Injectable} from 'injection-js';\nimport {Http, Request, Response, WebSocket, InjectorAwareInterface} from '@rxstack/core';\n\n@Injectable()\nexport class ProductController implements InjectorAwareInterface {\n\n  @Http('POST', '/product', 'app_product_create')\n  @WebSocket('app_product_create')\n  async createAction(request: Request): Promise\u003cResponse\u003e {\n    // getting connection\n    const conn = this.injector.get(SEQUELIZE_CONNECTION_TOKEN);\n    const service = this.injector.get(PRODUCT_SERVICE);\n    \n    // standard use\n    await service.insertOne(request.body);\n    \n    // with transaction and sequelize model options\n    await conn.transaction(async (t: any) =\u003e {\n      await service.insertOne(request.body, {transaction: t});\n      await anotherService.insertOne(request.body, {transaction: t});\n    });\n  }\n}\n```\n\n### \u003ca name=\"usage-query-filter\"\u003e\u003c/a\u003e How to build queries with query-filter\n\nIf you use [@rxstack/query-filter](https://github.com/rxstack/rxstack/tree/master/packages/query-filter) \nto build db queries then you need to replace default operators with sequelize specific ones:\n\n```typescript\nimport {QueryFilterSchema} from '@rxstack/query-filter';\nimport {Op} from 'sequelize';\n\nexport const myQueryFilterSchema: QueryFilterSchema = {\n  'properties': {\n    'product_name': {\n      'property_path': 'name',\n      'operators': ['$ne', '$eq'],\n      'replace_operators': [['$eq', Op.eq], ['$ne', Op.ne]],\n      'sort': true\n    }\n  },\n  'allowOrOperator': true,\n  'replaceOrOperatorWith': Op.or,\n  'defaultLimit': 10\n};\n```\n\n## \u003ca name=\"commands\"\u003e\u003c/a\u003e  Commands\nHelpful commands managing your sequelize database\n\n### \u003ca name=\"commands-sync\"\u003e\u003c/a\u003e Sync\nSync all defined models to the DB. [More info](http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html#instance-method-sync)\n\n```bash\nnpm run cli sequelize:sync\n```\n\nwith \"force\" option, defaults to false\n\n```bash\nnpm run cli sequelize:sync -- -f\n```\n\n### \u003ca name=\"commands-drop\"\u003e\u003c/a\u003e Drop\nDrop all tables. [More info](http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html#instance-method-drop)\n\n```bash\nnpm run cli sequelize:drop\n```\n\n## \u003ca name=\"validation-observer\"\u003e\u003c/a\u003e  Validation Observer\n`ValidationObserver` converts sequelize errors to `BadRequestException`.\n\nIn order to return proper validation errors and status code `400 ` we catch the exception and throw `BadRequestException`.\nThe error messages can be accessed `exception.data['errors']` and implement [`ValidationError[]`](https://github.com/rxstack/rxstack/blob/master/packages/platform/src/interfaces.ts).\n\n## License\n\nLicensed under the [MIT license](LICENSE).\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frxstack%2Fsequelize-service","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frxstack%2Fsequelize-service","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frxstack%2Fsequelize-service/lists"}