{"id":28002923,"url":"https://github.com/slaega/db-validation","last_synced_at":"2025-05-09T01:44:47.790Z","repository":{"id":288095508,"uuid":"966816953","full_name":"slaega/db-validation","owner":"slaega","description":"validation library for Prisma‑backed services. It lets you declare common database checks—like “exists” or “unique”—via a fluent builder, and integrates them into your service or controller via decorators.","archived":false,"fork":false,"pushed_at":"2025-05-05T16:58:58.000Z","size":588,"stargazers_count":1,"open_issues_count":5,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-09T01:44:43.746Z","etag":null,"topics":["clean-code","nestjs","nestjs-backend","prisma","validation-rules","validation-service"],"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/slaega.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,"zenodo":null}},"created_at":"2025-04-15T13:53:31.000Z","updated_at":"2025-04-17T11:44:25.000Z","dependencies_parsed_at":null,"dependency_job_id":"81ed7b4e-47db-405c-9235-3dc875f8d53a","html_url":"https://github.com/slaega/db-validation","commit_stats":null,"previous_names":["slaega/db-validation"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slaega%2Fdb-validation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slaega%2Fdb-validation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slaega%2Fdb-validation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slaega%2Fdb-validation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/slaega","download_url":"https://codeload.github.com/slaega/db-validation/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253176444,"owners_count":21866142,"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":["clean-code","nestjs","nestjs-backend","prisma","validation-rules","validation-service"],"created_at":"2025-05-09T01:44:47.052Z","updated_at":"2025-05-09T01:44:47.788Z","avatar_url":"https://github.com/slaega.png","language":"TypeScript","readme":"# @slaega/db-validation\n\n**@slaega/db-validation** is a NestJS‑compatible validation library for Prisma‑backed services. It lets you declare common database checks—like “exists” or “unique”—via a fluent builder, and integrates them into your service or controller via decorators.\n\n---\n\n## 🚀 Features\n\n- **Existence check**: Verify that a record exists before proceeding.  \n- **Uniqueness check**: Ensure a field is unique (optionally excluding the current record).  \n- **Custom rules**: Extend with your own validation logic.  \n- **Decorator integration**: Hook validations into your service methods with a single decorator.\n\n---\n\n## 📦 Installation\n\n```bash\nyarn add @slaega/db-validation\n# or\nnpm install @slaega/db-validation\n```\n\nSince this package declares NestJS and Prisma as **peerDependencies**, make sure your app has them installed too:\n\n```bash\nyarn add @nestjs/common @nestjs/core @prisma/client reflect-metadata\n```\n\n---\n\n## ⚙️ Usage\n\n### 1. Define validation rules\n\nCreate a class that returns a `DbValidationBuilder` instance for each method you want to guard:\n\n```ts\nimport { DbValidationBuilder } from '@slaega/db-validation';\n\nexport class PostValidationRules {\n  create(userId: number, data: { title: string }) {\n    return DbValidationBuilder.new()\n      .exists('User', { id: userId }, 'User not found')\n      .unique('Post', { title: data.title }, undefined, 'Post title already in use');\n  }\n\n  update(userId: number, postId: number, data: { title: string }) {\n    return DbValidationBuilder.new()\n      .exists('Post', { id: postId, authorId: userId }, 'Post not found')\n      .unique('Post', { title: data.title }, { id: postId }, 'Title conflict');\n  }\n\n  findOne(userId: number, postId: number) {\n    return DbValidationBuilder.new()\n      .exists('Post', { id: postId, authorId: userId }, 'Post not found');\n  }\n}\n```\n\n### 2. Apply via decorator # UseDbValidationSimple\n\nUse the built‑in decorator to run your rules automatically before the decorated method:\n\n```ts\nimport { Injectable } from '@nestjs/common';\nimport { UseDbValidationSimple } from '@slaega/db-validation';\nimport { PostRepository } from './post.repository';\nimport { PostValidationRules } from './post.validation-rules';\n\n@Injectable()\nexport class PostService {\n  constructor(\n    private readonly repo: PostRepository,\n    public readonly dbValidatorService: DbValidationService, // this name must match the decorator\n  ) {}\n\n  @UseDbValidationSimple(PostValidationRules, 'create')\n  async createPost(userId: number, input: { title: string }) {\n    return this.repo.create({ ...input, authorId: userId });\n  }\n\n  @UseDbValidationSimple(PostValidationRules, 'update')\n  async updatePost(userId: number, postId: number, input: { title: string }) {\n    return this.repo.update(postId, input);\n  }\n}\n```\n\n### 2. Apply via decorator # UseDbValidation\n\nUse the built‑in decorator to run your rules automatically before the decorated method:\n\n```ts\nimport { Injectable } from '@nestjs/common';\nimport { UseDbValidation } from '@slaega/db-validation';\nimport { PostRepository } from './post.repository';\nimport { PostValidationRules } from './post.validation-rules';\n\n@Injectable()\nexport class PostService {\n  constructor(\n    private readonly repo: PostRepository,\n    public readonly dbValidatorService: DbValidationService, // this name must match the decorator\n  ) {}\n\n  @UseDbValidation(PostValidationRules, 'create', (self) =\u003e self.dbValidatorService)\n  async createPost(userId: number, input: { title: string }) {\n    return this.repo.create({ ...input, authorId: userId });\n  }\n\n  @UseDbValidation(PostValidationRules, 'update', (self) =\u003e self.dbValidatorService)\n  async updatePost(userId: number, postId: number, input: { title: string }) {\n    return this.repo.update(postId, input);\n  }\n}\n```\n\n\u003e 💡 The property name `dbValidatorService` must match the default expected by the decorator (`UseDbValidationSimple`). If you'd prefer a custom name, use `UseDbValidationFrom()` instead and provide the key.\n\n---\n\n### 3. Without decorators (manual usage)\n\nIf you don’t want to use decorators, you can call the validator directly:\n\n```ts\nconst builder = new PostValidationRules().create(userId, input);\nawait dbValidatorService.validate(builder);\n```\n\n---\n\n## 🧩 Decorators API\n\n### `@UseDbValidation`\nLow-level decorator. Lets you control how the validator service is retrieved from `this`.\n\n```ts\n@UseDbValidation(RulesClass, 'methodName', (self) =\u003e self.myCustomValidator)\n```\n\n### `@UseDbValidationFrom`\nMid-level decorator. Lets you specify the property name of the validator service on the class (defaults to `validationService`).\n\n```ts\n@UseDbValidationFrom(RulesClass, 'methodName', 'dbValidatorService')\n```\n\n### `@UseDbValidationSimple`\nHigh-level, opinionated decorator. Looks for a property named `dbValidatorService` in your class.\n\n```ts\n@UseDbValidationSimple(RulesClass, 'methodName')\n```\n\n---\n\n## 🛠 API\n\n#### `DbValidationBuilder`\n\n| Method                                            | Description                                                                                              |\n|---------------------------------------------------|----------------------------------------------------------------------------------------------------------|\n| `.exists(modelName, where, errorMessage?)`        | Throws `NotFoundException` if no record matches `where`.                                                 |\n| `.unique(modelName, where, exclude?, errorMessage?)` | Throws `ConflictException` if a record matching `where` exists and doesn’t match `exclude`.            |\n| `.dependent(modelName, where, dependentField, expectedValue, errorMessage?)` | Throws `BadRequestException` if record’s `dependentField` ≠ `expectedValue`. |\n| `.equals(value, expected, errorMessage?)`         | Throws `BadRequestException` if `value !== expected`.                                                    |\n| `.inList(value, list, errorMessage?)`             | Throws `BadRequestException` if `value` not in `list`.                                                    |\n| `.notInList(value, list, errorMessage?)`          | Throws `BadRequestException` if `value` is in `list`.                                                    |\n| `.custom(validateFn, errorType?, errorMessage?)`  | Runs arbitrary async `validateFn`; throws exception based on `errorType` (`not_found`, `conflict`, or `bad_request`). |\n\n---\n\n## 🔄 Regenerating Mappings\n\nWhenever you update your Prisma schema, regenerate the client and then re-run the CLI to rebuild your TypeScript mapping:\n\n```bash\n# Direct commands:\nnpx prisma generate \u0026\u0026 npx db-validation\n\n# Or via package.json scripts:\n# package.json\n\"scripts\": {\n  \"prisma:generate\": \"prisma generate\",\n  \"generate:types\": \"npm run prisma:generate \u0026\u0026 npm run generate\",\n  \"generate\": \"db-validation\"\n}\n\n# Then:\nnpm run generate:types\n# or\nyarn generate:types\n```\n\nThis will produce a `dist/types.ts` file containing:\n\n```ts\nimport { Prisma } from '@prisma/client';\n\nexport type ModelWhereMapping = {\n  User: Prisma.UserWhereInput;\n  Post: Prisma.PostWhereInput;\n  // …and so on for each model\n};\n```\n\n---\n\n## 🧪 Testing locally\n\nTo develop and test your package in isolation:\n\n1. **Clone \u0026 install**  \n   ```bash\n   git clone https://github.com/slaega/db-validation.git\n   cd db-validation\n   yarn install\n   ```\n\n2. **Build**  \n   ```bash\n   yarn build\n   ```\n\n3. **Link into a consuming project**  \n   ```bash\n   yarn link\n   cd ../your-app\n   yarn link @slaega/db-validation\n   yarn install\n   ```\n\n4. **Run tests**  \n   ```bash\n   yarn test\n   yarn test:watch\n   ```\n\n---\n\n## 🤝 Contributing\n\n1. Fork the repo  \n2. Create a feature branch (`git checkout -b feature/my-change`)  \n3. Commit your changes (`git commit -m 'Add feature'`)  \n4. Push to your branch (`git push origin feature/my-change`)  \n5. Open a Pull Request\n\n---\n\n## 📄 License\n\nThis project is **MTI** [LICENSE](LICENSE) for details.\n\n---\n\n\u003e Maintained by **Slaega**. Feel free to open issues on GitHub!\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fslaega%2Fdb-validation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fslaega%2Fdb-validation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fslaega%2Fdb-validation/lists"}