From db6b6996637e6c540e45eb2539596944147d0c18 Mon Sep 17 00:00:00 2001 From: Ivan Li Date: Sun, 31 Jan 2021 19:42:17 +0800 Subject: [PATCH] feat(proejct): project curd. --- nest-cli.json | 6 +- package-lock.json | 433 +++++++++++++++++- package.json | 4 + src/app.module.ts | 2 + src/commons/commons.module.ts | 8 + src/commons/entities/app-base-entity.ts | 19 + .../Insufficient-balance.exception.ts | 6 + .../exceptions/application.exception.ts | 21 + .../exceptions/duplicate-entity.exception.ts | 35 ++ .../exceptions/lock-failed.exception.ts | 6 + .../value-out-of-range.exception.ts | 36 ++ .../exceptions/wrong-content.exception.ts | 7 + src/commons/filters/all.exception-filter.ts | 55 +++ src/commons/interfaces/available.interface.ts | 3 + .../interfaces/pagination.interface.ts | 6 + src/commons/services/base-db.service.ts | 179 ++++++++ src/commons/services/password-converter.ts | 15 + src/commons/services/typeorm-helper.ts | 304 ++++++++++++ src/main.ts | 2 + src/projects/dtos/create-project.input.ts | 28 ++ src/projects/dtos/update-project.input.ts | 5 + src/projects/project.entity.ts | 28 ++ src/projects/projects.module.ts | 11 + src/projects/projects.resolver.spec.ts | 18 + src/projects/projects.resolver.ts | 41 ++ src/projects/projects.service.spec.ts | 18 + src/projects/projects.service.ts | 35 ++ 27 files changed, 1326 insertions(+), 5 deletions(-) create mode 100644 src/commons/commons.module.ts create mode 100644 src/commons/entities/app-base-entity.ts create mode 100644 src/commons/exceptions/Insufficient-balance.exception.ts create mode 100644 src/commons/exceptions/application.exception.ts create mode 100644 src/commons/exceptions/duplicate-entity.exception.ts create mode 100644 src/commons/exceptions/lock-failed.exception.ts create mode 100644 src/commons/exceptions/value-out-of-range.exception.ts create mode 100644 src/commons/exceptions/wrong-content.exception.ts create mode 100644 src/commons/filters/all.exception-filter.ts create mode 100644 src/commons/interfaces/available.interface.ts create mode 100644 src/commons/interfaces/pagination.interface.ts create mode 100644 src/commons/services/base-db.service.ts create mode 100644 src/commons/services/password-converter.ts create mode 100644 src/commons/services/typeorm-helper.ts create mode 100644 src/projects/dtos/create-project.input.ts create mode 100644 src/projects/dtos/update-project.input.ts create mode 100644 src/projects/project.entity.ts create mode 100644 src/projects/projects.module.ts create mode 100644 src/projects/projects.resolver.spec.ts create mode 100644 src/projects/projects.resolver.ts create mode 100644 src/projects/projects.service.spec.ts create mode 100644 src/projects/projects.service.ts diff --git a/nest-cli.json b/nest-cli.json index 56167b3..2d39856 100644 --- a/nest-cli.json +++ b/nest-cli.json @@ -1,4 +1,8 @@ { "collection": "@nestjs/schematics", - "sourceRoot": "src" + "sourceRoot": "src", + "compilerOptions": { + "plugins": ["@nestjs/graphql"], + "introspectComments": true + } } diff --git a/package-lock.json b/package-lock.json index 5a95caf..45393ff 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2284,6 +2284,15 @@ } } }, + "@neuralegion/class-sanitizer": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@neuralegion/class-sanitizer/-/class-sanitizer-0.3.2.tgz", + "integrity": "sha512-JP+lwZHanVVxL3yc7HoEobzDIF96NaiEclUR7lzCR46I8yeRyr+VGwuezadA2NVEReQOERWftYUDXWVAbdn6Cg==", + "requires": { + "sanitizer": "^0.1.3", + "validator": "^11.1.0" + } + }, "@nodelib/fs.scandir": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.4.tgz", @@ -2840,6 +2849,11 @@ "resolved": "https://registry.npmjs.org/@types/ungap__global-this/-/ungap__global-this-0.3.1.tgz", "integrity": "sha512-+/DsiV4CxXl6ZWefwHZDXSe1Slitz21tom38qPCaG0DYCS1NnDPIQDTKcmQ/tvK/edJUKkmuIDBJbmKDiB0r/g==" }, + "@types/validator": { + "version": "13.1.3", + "resolved": "https://registry.npmjs.org/@types/validator/-/validator-13.1.3.tgz", + "integrity": "sha512-DaOWN1zf7j+8nHhqXhIgNmS+ltAC53NXqGxYuBhWqWgqolRhddKzfZU814lkHQSTG0IUfQxU7Cg0gb8fFWo2mA==" + }, "@types/webpack": { "version": "4.41.25", "resolved": "https://registry.npmjs.org/@types/webpack/-/webpack-4.41.25.tgz", @@ -3379,6 +3393,11 @@ "integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==", "dev": true }, + "abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, "accepts": { "version": "1.3.7", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", @@ -4160,6 +4179,49 @@ "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", "integrity": "sha1-HjRA6RXwsSA9I3SOeO3XubW0PlY=" }, + "aproba": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", + "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==" + }, + "are-we-there-yet": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz", + "integrity": "sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w==", + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + }, + "dependencies": { + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" + }, + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "requires": { + "safe-buffer": "~5.1.0" + } + } + } + }, "arg": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", @@ -4487,6 +4549,15 @@ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" }, + "bcrypt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.0.0.tgz", + "integrity": "sha512-jB0yCBl4W/kVHM2whjfyqnxTmOHkCX4kHEa5nYKSoGeYe8YrjTYTc87/6bwt1g8cmV0QrbhKriETg9jWtcREhg==", + "requires": { + "node-addon-api": "^3.0.0", + "node-pre-gyp": "0.15.0" + } + }, "bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", @@ -4832,6 +4903,11 @@ "integrity": "sha512-uc2Vix1frTfnuzxxu1Hp4ktSvM3QaI4oXl4ZUqL1wjTu/BGki9TrCWoqLTg/drR1KwAEarXuRFCG2Svr1GxPFw==", "dev": true }, + "class-transformer": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/class-transformer/-/class-transformer-0.3.2.tgz", + "integrity": "sha512-9QY6QXBH/+Gt1C3HBmJCrgY6+EFpIa6aLjfDnlXFx0zQl/HjrCE7qoaI0srNrxpMIfsobCpgUdDG5JYtJOpVsw==" + }, "class-utils": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", @@ -4855,6 +4931,23 @@ } } }, + "class-validator": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.13.1.tgz", + "integrity": "sha512-zWIeYFhUitvAHBwNhDdCRK09hWx+P0HUwFE8US8/CxFpMVzkUK8RJl7yOIE+BVu2lxyPNgeOaFv78tLE47jBIg==", + "requires": { + "@types/validator": "^13.1.3", + "libphonenumber-js": "^1.9.7", + "validator": "^13.5.2" + }, + "dependencies": { + "validator": { + "version": "13.5.2", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.5.2.tgz", + "integrity": "sha512-mD45p0rvHVBlY2Zuy3F3ESIe1h5X58GPfAtslBjY7EtTqGquZTj+VX/J4RnHWN8FKq0C9WRVt1oWAcytWRuYLQ==" + } + } + }, "clean-stack": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", @@ -5013,6 +5106,11 @@ "integrity": "sha512-67ueh2IRGst/51p0n6FvPrnRjAGHY5F8xdjkgrYE7DDzpJe6qA07RYQ9VcoUeo5ATOjSOiWpSL3SWBRRbempMw==", "optional": true }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=" + }, "collect-v8-coverage": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", @@ -5125,6 +5223,11 @@ "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.0.tgz", "integrity": "sha512-vlcSGgdYS26mPf7qNi+dCisbhiyDnrN1zaRbw3CSuc2wGOMEGGPsp46PdRG5gqXwgtJfjxDkxRNAgRPr1B77vQ==" }, + "console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=" + }, "consolidate": { "version": "0.16.0", "resolved": "https://registry.npmjs.org/consolidate/-/consolidate-0.16.0.tgz", @@ -5318,6 +5421,11 @@ "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", "dev": true }, + "deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==" + }, "deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", @@ -5393,6 +5501,11 @@ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" }, + "delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=" + }, "depd": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", @@ -5408,6 +5521,11 @@ "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" }, + "detect-libc": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz", + "integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=" + }, "detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -6459,6 +6577,54 @@ "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", "dev": true }, + "gauge": { + "version": "2.7.4", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", + "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, "generic-names": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/generic-names/-/generic-names-2.0.1.tgz", @@ -6821,6 +6987,11 @@ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==" }, + "has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=" + }, "has-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", @@ -7052,6 +7223,14 @@ "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==" }, + "ignore-walk": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-3.0.3.tgz", + "integrity": "sha512-m7o6xuOaT1aqheYHKf8W6J5pYH85ZI9w077erOzLje3JsB1gkafkAhHHY19dqjulgIZHFm32Cp5uNZgcQqdJKw==", + "requires": { + "minimatch": "^3.0.4" + } + }, "immutable": { "version": "3.7.6", "resolved": "https://registry.npmjs.org/immutable/-/immutable-3.7.6.tgz", @@ -7129,6 +7308,11 @@ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" }, + "ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" + }, "inquirer": { "version": "7.3.3", "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-7.3.3.tgz", @@ -8166,6 +8350,11 @@ "type-check": "~0.4.0" } }, + "libphonenumber-js": { + "version": "1.9.9", + "resolved": "https://registry.npmjs.org/libphonenumber-js/-/libphonenumber-js-1.9.9.tgz", + "integrity": "sha512-RhtAvacOkq4wc+RrswYE9MteJQy/1yd4lgLJTdL+HdYYRLZbERFv4ZRj/Nt+/gIB2xVSgW0MLNqb32hx042W+g==" + }, "lines-and-columns": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", @@ -8688,6 +8877,31 @@ "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", "dev": true }, + "needle": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/needle/-/needle-2.6.0.tgz", + "integrity": "sha512-KKYdza4heMsEfSWD7VPUIz3zX2XDwOyX2d+geb4vrERZMT5RMU6ujjaD+I5Yr54uZxQ2w6XRTAhHBbSCyovZBg==", + "requires": { + "debug": "^3.2.6", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + }, + "dependencies": { + "debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, "negotiator": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", @@ -8714,6 +8928,11 @@ "tslib": "^2.0.3" } }, + "node-addon-api": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.1.0.tgz", + "integrity": "sha512-flmrDNB06LIl5lywUz7YlNGZH/5p0M7W28k8hzd9Lshtdh1wshD2Y+U4h9LD6KObOy1f+fEVdgprPrEymjM5uw==" + }, "node-emoji": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.10.0.tgz", @@ -8754,12 +8973,102 @@ "which": "^2.0.2" } }, + "node-pre-gyp": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/node-pre-gyp/-/node-pre-gyp-0.15.0.tgz", + "integrity": "sha512-7QcZa8/fpaU/BKenjcaeFF9hLz2+7S9AqyXFhlH/rilsQ/hPZKK32RtR5EQHJElgu+q5RfbJ34KriI79UWaorA==", + "requires": { + "detect-libc": "^1.0.2", + "mkdirp": "^0.5.3", + "needle": "^2.5.0", + "nopt": "^4.0.1", + "npm-packlist": "^1.1.6", + "npmlog": "^4.0.2", + "rc": "^1.2.7", + "rimraf": "^2.6.1", + "semver": "^5.3.0", + "tar": "^4.4.2" + }, + "dependencies": { + "chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" + }, + "fs-minipass": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-1.2.7.tgz", + "integrity": "sha512-GWSSJGFy4e9GUeCcbIkED+bgAoFyj7XF1mV8rma3QW4NIqX9Kyx79N/PF61H5udOV3aY1IaMLs6pGbH71nlCTA==", + "requires": { + "minipass": "^2.6.0" + } + }, + "minipass": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-2.9.0.tgz", + "integrity": "sha512-wxfUjg9WebH+CUDX/CdbRlh5SmfZiy/hpkxaRI16Y9W56Pa75sWgd/rvFilSgrauD9NyFymP/+JFV3KwzIsJeg==", + "requires": { + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" + } + }, + "minizlib": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-1.3.3.tgz", + "integrity": "sha512-6ZYMOEnmVsdCeTJVE0W9ZD+pVnE8h9Hma/iOwwRDsdQoePpoX56/8B6z3P9VNwppJuBKNRuFDRNRqRWexT9G9Q==", + "requires": { + "minipass": "^2.9.0" + } + }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "requires": { + "glob": "^7.1.3" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "tar": { + "version": "4.4.13", + "resolved": "https://registry.npmjs.org/tar/-/tar-4.4.13.tgz", + "integrity": "sha512-w2VwSrBoHa5BsSyH+KxEqeQBAllHhccyMFVHtGtdMpF4W7IRWfZjFiQceJPChOeTsSDVUpER2T8FA93pr0L+QA==", + "requires": { + "chownr": "^1.1.1", + "fs-minipass": "^1.2.5", + "minipass": "^2.8.6", + "minizlib": "^1.2.1", + "mkdirp": "^0.5.0", + "safe-buffer": "^5.1.2", + "yallist": "^3.0.3" + } + }, + "yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==" + } + } + }, "node-releases": { "version": "1.1.70", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-1.1.70.tgz", "integrity": "sha512-Slf2s69+2/uAD79pVVQo8uSiC34+g8GWY8UH2Qtqv34ZfhYrxpYpfzs9Js9d6O0mbDmALuxaTlplnBTnSELcrw==", "dev": true }, + "nopt": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-4.0.3.tgz", + "integrity": "sha512-CvaGwVMztSMJLOeXPrez7fyfObdZqNUK1cPAEzLHrTybIua9pMdmmPR5YwtfNftIOMv3DPUhFaxsZMNTQO20Kg==", + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, "normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", @@ -8785,6 +9094,29 @@ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==" }, + "npm-bundled": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-1.1.1.tgz", + "integrity": "sha512-gqkfgGePhTpAEgUsGEgcq1rqPXA+tv/aVBlgEzfXwA1yiUJF7xtEt3CtVwOjNYQOVknDk0F20w58Fnm3EtG0fA==", + "requires": { + "npm-normalize-package-bin": "^1.0.1" + } + }, + "npm-normalize-package-bin": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-1.0.1.tgz", + "integrity": "sha512-EPfafl6JL5/rU+ot6P3gRSCpPDW5VmIzX959Ob1+ySFUuuYHWHekXpwdUZcKP5C+DS4GEtdJluwBjnsNDl+fSA==" + }, + "npm-packlist": { + "version": "1.4.8", + "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-1.4.8.tgz", + "integrity": "sha512-5+AZgwru5IevF5ZdnFglB5wNlHG1AOOuw28WhUq8/8emhBmLv6jX5by4WJCh7lW0uSYZYS6DXqIsyZVIXRZU9A==", + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1", + "npm-normalize-package-bin": "^1.0.1" + } + }, "npm-run-path": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", @@ -8794,11 +9126,27 @@ "path-key": "^3.0.0" } }, + "npmlog": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-4.1.2.tgz", + "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, "nullthrows": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/nullthrows/-/nullthrows-1.1.1.tgz", "integrity": "sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw==" }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=" + }, "nwsapi": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.0.tgz", @@ -8984,6 +9332,11 @@ "url-parse": "^1.4.3" } }, + "os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=" + }, "os-name": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/os-name/-/os-name-4.0.0.tgz", @@ -8997,8 +9350,16 @@ "os-tmpdir": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", - "dev": true + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" + }, + "osenv": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz", + "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==", + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } }, "p-each-series": { "version": "2.2.0", @@ -9593,6 +9954,24 @@ "unpipe": "1.0.0" } }, + "rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=" + } + } + }, "react-is": { "version": "17.0.1", "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.1.tgz", @@ -10198,6 +10577,11 @@ } } }, + "sanitizer": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/sanitizer/-/sanitizer-0.1.3.tgz", + "integrity": "sha1-1PCvdHXZp7ryqeWmEXGLqheKOeE=" + }, "sax": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", @@ -10362,8 +10746,7 @@ "signal-exit": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", - "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", - "dev": true + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==" }, "signedsource": { "version": "1.0.0", @@ -11851,6 +12234,11 @@ "spdx-expression-parse": "^3.0.0" } }, + "validator": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-11.1.0.tgz", + "integrity": "sha512-qiQ5ktdO7CD6C/5/mYV4jku/7qnqzjrxb3C/Q5wR3vGGinHTgJZN/TdFT3ZX4vXhX2R1PXx42fB1cn5W+uJ4lg==" + }, "vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -12044,6 +12432,43 @@ "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=" }, + "wide-align": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz", + "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==", + "requires": { + "string-width": "^1.0.2 || 2" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=" + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + } + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, "windows-release": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-4.0.0.tgz", diff --git a/package.json b/package.json index 2b3369f..64e4470 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,11 @@ "@nestjs/graphql": "^7.9.8", "@nestjs/platform-express": "^7.5.1", "@nestjs/typeorm": "^7.1.5", + "@neuralegion/class-sanitizer": "^0.3.2", "apollo-server-express": "^2.19.2", + "bcrypt": "^5.0.0", + "class-transformer": "^0.3.2", + "class-validator": "^0.13.1", "graphql": "^15.5.0", "graphql-tools": "^7.0.2", "js-yaml": "^4.0.0", diff --git a/src/app.module.ts b/src/app.module.ts index f83de78..b7362d9 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -5,6 +5,7 @@ import { TypeOrmModule } from '@nestjs/typeorm'; import { AppController } from './app.controller'; import { AppResolver } from './app.resolver'; import { AppService } from './app.service'; +import { ProjectsModule } from './projects/projects.module'; import configuration from './commons/config/configuration'; @Module({ @@ -35,6 +36,7 @@ import configuration from './commons/config/configuration'; }), inject: [ConfigService], }), + ProjectsModule, ], controllers: [AppController], providers: [AppService, AppResolver], diff --git a/src/commons/commons.module.ts b/src/commons/commons.module.ts new file mode 100644 index 0000000..12d0563 --- /dev/null +++ b/src/commons/commons.module.ts @@ -0,0 +1,8 @@ +import { Module } from '@nestjs/common'; +import { PasswordConverter } from './services/password-converter'; + +@Module({ + providers: [PasswordConverter], + exports: [PasswordConverter], +}) +export class CommonsModule {} diff --git a/src/commons/entities/app-base-entity.ts b/src/commons/entities/app-base-entity.ts new file mode 100644 index 0000000..1002875 --- /dev/null +++ b/src/commons/entities/app-base-entity.ts @@ -0,0 +1,19 @@ +import { Field, ID, ObjectType } from '@nestjs/graphql'; +import { + CreateDateColumn, + PrimaryGeneratedColumn, + UpdateDateColumn, +} from 'typeorm'; + +@ObjectType() +export class AppBaseEntity { + @Field(() => ID) + @PrimaryGeneratedColumn('uuid') + id: string; + + @CreateDateColumn() + createdAt: Date; + + @UpdateDateColumn({ select: false }) + updatedAt: Date; +} diff --git a/src/commons/exceptions/Insufficient-balance.exception.ts b/src/commons/exceptions/Insufficient-balance.exception.ts new file mode 100644 index 0000000..095ae11 --- /dev/null +++ b/src/commons/exceptions/Insufficient-balance.exception.ts @@ -0,0 +1,6 @@ +export class InsufficientBalanceException extends Error { + constructor(curr: number, amount: number) { + super(); + this.message = `余额不足。current balance:${curr},change amount:${amount}`; + } +} diff --git a/src/commons/exceptions/application.exception.ts b/src/commons/exceptions/application.exception.ts new file mode 100644 index 0000000..d7f425f --- /dev/null +++ b/src/commons/exceptions/application.exception.ts @@ -0,0 +1,21 @@ +export class ApplicationException extends Error { + code: number; + error: Error; + + constructor( + message: + | string + | { error?: Error; message?: string | object; code?: number }, + ) { + if (message instanceof Object) { + super(); + this.code = message.code; + this.error = message.error; + this.message = message.message as any; + } else if (typeof message === 'string') { + super((message as unknown) as any); + } else { + super((message as unknown) as any); + } + } +} diff --git a/src/commons/exceptions/duplicate-entity.exception.ts b/src/commons/exceptions/duplicate-entity.exception.ts new file mode 100644 index 0000000..b27ddb5 --- /dev/null +++ b/src/commons/exceptions/duplicate-entity.exception.ts @@ -0,0 +1,35 @@ +import { ValidationError } from '@nestjs/common'; +import { WrongContentException } from './wrong-content.exception'; + +export interface DuplicateFieldInfo { + property: string; + value: any; + name?: string; + message?: string; +} + +export class DuplicateEntityException extends WrongContentException { + errorObj: { [p: string]: any; message: ValidationError[] }; + constructor(exceptionInfo: DuplicateFieldInfo[]) { + super(DuplicateEntityException.getValidationError(exceptionInfo)); + } + + private static getValidationError( + exceptionInfo: DuplicateFieldInfo[], + ): ValidationError[] { + return exceptionInfo.map((item) => { + const property: string = item.property; + const value: any = item.value; + const message: string = item.message + ? item.message + : `${item.name || ''}已存在相同的值「${item.value}」`; + return { + property, + value, + constraints: { duplicate: message }, + target: undefined, + children: [], + } as ValidationError; + }); + } +} diff --git a/src/commons/exceptions/lock-failed.exception.ts b/src/commons/exceptions/lock-failed.exception.ts new file mode 100644 index 0000000..62637af --- /dev/null +++ b/src/commons/exceptions/lock-failed.exception.ts @@ -0,0 +1,6 @@ +export class LockFailedException extends Error { + constructor(lockId: any) { + super(); + this.message = `加锁失败。目标:${lockId}`; + } +} diff --git a/src/commons/exceptions/value-out-of-range.exception.ts b/src/commons/exceptions/value-out-of-range.exception.ts new file mode 100644 index 0000000..70aa213 --- /dev/null +++ b/src/commons/exceptions/value-out-of-range.exception.ts @@ -0,0 +1,36 @@ +import { ValidationError } from '@nestjs/common'; +import { WrongContentException } from './wrong-content.exception'; + +export interface ValueOutOfRangeInfo { + property: string; + value: any; + range: string; + name?: string; + message?: string; +} + +export class ValueOutOfRangeException extends WrongContentException { + errorObj: { [p: string]: any; message: ValidationError[] }; + constructor(exceptionInfo: ValueOutOfRangeInfo[]) { + super(ValueOutOfRangeException.getValidationError(exceptionInfo)); + } + + private static getValidationError( + exceptionInfo: ValueOutOfRangeInfo[], + ): ValidationError[] { + return exceptionInfo.map((item) => { + const property: string = item.property; + const value: any = item.value; + const message: string = item.message + ? item.message + : `${item.name || ''}的取值范围应是${item.range}`; + return { + property, + value, + constraints: { duplicate: message }, + target: undefined, + children: [], + } as ValidationError; + }); + } +} diff --git a/src/commons/exceptions/wrong-content.exception.ts b/src/commons/exceptions/wrong-content.exception.ts new file mode 100644 index 0000000..c8e17ac --- /dev/null +++ b/src/commons/exceptions/wrong-content.exception.ts @@ -0,0 +1,7 @@ +import { UnprocessableEntityException, ValidationError } from '@nestjs/common'; + +export class WrongContentException extends UnprocessableEntityException { + constructor(exceptionInfo: ValidationError[]) { + super(exceptionInfo); + } +} diff --git a/src/commons/filters/all.exception-filter.ts b/src/commons/filters/all.exception-filter.ts new file mode 100644 index 0000000..e5f202e --- /dev/null +++ b/src/commons/filters/all.exception-filter.ts @@ -0,0 +1,55 @@ +import { + ArgumentsHost, + Catch, + ExceptionFilter, + HttpException, + HttpStatus, +} from '@nestjs/common'; +import { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError'; + +@Catch() +export class AllExceptionsFilter implements ExceptionFilter { + catch(exception: any, host: ArgumentsHost) { + const ctx = host.switchToHttp(); + const response = ctx.getResponse(); + const request = ctx.getRequest(); + + const status = + exception instanceof HttpException + ? exception.getStatus() + : HttpStatus.INTERNAL_SERVER_ERROR; + + if (exception instanceof HttpException) { + const ex = exception.getResponse(); + if (ex instanceof Object) { + response.status(status).json({ + ...ex, + timestamp: Date.now(), + path: request.url, + }); + } else { + response.status(status).json({ + message: ex, + timestamp: Date.now(), + path: request.url, + }); + } + } else if (exception instanceof EntityNotFoundError) { + response.status(HttpStatus.NOT_FOUND).json({ + message: '资源未找到!', + timestamp: Date.now(), + path: request.url, + }); + } else { + console.error('服务器内部错误'); + console.error(exception); + response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ + code: status, + timestamp: new Date().toISOString(), + message: '服务器内部错误', + error: exception, + path: request.url, + }); + } + } +} diff --git a/src/commons/interfaces/available.interface.ts b/src/commons/interfaces/available.interface.ts new file mode 100644 index 0000000..da78ec6 --- /dev/null +++ b/src/commons/interfaces/available.interface.ts @@ -0,0 +1,3 @@ +export interface AvailableInterface { + isAvailable: boolean; +} diff --git a/src/commons/interfaces/pagination.interface.ts b/src/commons/interfaces/pagination.interface.ts new file mode 100644 index 0000000..5dbf897 --- /dev/null +++ b/src/commons/interfaces/pagination.interface.ts @@ -0,0 +1,6 @@ +export interface PaginationInterface { + pageSize?: number; + pageIndex?: number; + take?: number; + skip?: number; +} diff --git a/src/commons/services/base-db.service.ts b/src/commons/services/base-db.service.ts new file mode 100644 index 0000000..ab52e02 --- /dev/null +++ b/src/commons/services/base-db.service.ts @@ -0,0 +1,179 @@ +import { AppBaseEntity } from '../entities/app-base-entity'; +import { Brackets, Repository, SelectQueryBuilder } from 'typeorm'; +import { TypeormHelper } from './typeorm-helper'; +import { UnprocessableEntityException } from '@nestjs/common'; +import { + DuplicateEntityException, + DuplicateFieldInfo, +} from '../exceptions/duplicate-entity.exception'; + +export class BaseDbService extends TypeormHelper { + constructor(protected readonly repository: Repository) { + super(); + } + + readonly uniqueFields: Array> = []; + + async isDuplicateEntity>( + dto: Partial, + extendsFields: Array = [], + ): Promise { + const qb = this.repository.createQueryBuilder('entity'); + const compareFields = this.getCompareFields(dto, [ + ...this.uniqueFields, + ...extendsFields, + ]); + if (compareFields.length > 0) { + qb.andWhere( + new Brackets((bqb) => { + for (const key of compareFields) { + if (Array.isArray(key)) { + bqb.orWhere( + new Brackets((bbqb) => { + for (const k of key) { + bbqb.andWhere(`entity.${k} = :${k}`); + } + }), + ); + } else { + bqb.orWhere(`entity.${key} = :${key}`); + } + } + }), + ); + } else { + return false; + } + qb.setParameters(Object.assign({}, dto)); + const uniqueFields = Array.from(new Set(compareFields.flat())); + qb.addSelect(uniqueFields.map((f) => `entity.${f} AS entity_${f}`)); + return await this.checkDuplicateFields(qb, dto, uniqueFields); + } + + async isDuplicateEntityForUpdate( + id: string, + dto: Partial, + extendsFields: Array = [], + ): Promise { + const qb = this.repository.createQueryBuilder('entity'); + const compareFields = this.getCompareFields(dto, [ + ...this.uniqueFields, + ...extendsFields, + ]); + const flatCompareFields = compareFields.flat(); + if (compareFields.length > 0) { + qb.andWhere( + new Brackets((bqb) => { + for (const key of compareFields) { + if (Array.isArray(key)) { + if (key.length > 0) { + bqb.orWhere( + new Brackets((bbqb) => + key.forEach((k) => { + bbqb.andWhere(`entity.${k} = :${k}`); + }), + ), + ); + } + } else { + bqb.orWhere(`entity.${key} = :${key}`); + } + } + }), + ); + } else { + return false; + } + qb.andWhere(`entity.id <> :id`); + qb.setParameters(Object.assign({}, dto, { id })); + qb.addSelect(flatCompareFields.map((f) => `entity.${f} AS entity_${f}`)); + return await this.checkDuplicateFields(qb, dto, compareFields); + } + + async findOne(entity: Entity): Promise; + async findOne(id: string): Promise; + async findOne(idOrEntity: string | Entity): Promise { + if (idOrEntity instanceof Object) { + return idOrEntity; + } + return await this.repository.findOneOrFail({ + where: { id: idOrEntity }, + }); + } + + checkProperty( + obj: T, + field: keyof T, + whitelist: Array, + errMsg: string, + ) { + if (!whitelist.some((item) => obj[field] === item)) { + throw new UnprocessableEntityException(errMsg); + } + } + + async canYouRemoveWithIds(ids: string[]): Promise { + return; + } + + private getCompareFields( + dto: Partial, + fields: Array>, + ) { + if (!Array.isArray(fields)) { + return []; + } + const compareFields = []; + for (const field of fields as Array>) { + if (Array.isArray(field)) { + const tmpFields = []; + for (const f of field) { + if (dto[f] !== undefined) { + tmpFields.push(f); + } + } + compareFields.push(tmpFields); + } else if (dto[field] !== undefined) { + compareFields.push(field); + } + } + return compareFields; + } + + private async checkDuplicateFields( + qb: SelectQueryBuilder, + dto: Dto, + compareFields: Array, + ): Promise { + const existingEntity = await qb.getOne(); + if (!existingEntity) { + return false; + } + const duplicateEntityInfo: DuplicateFieldInfo[] = []; + for (const key of compareFields) { + if (existingEntity[key as string] === dto[key]) { + duplicateEntityInfo.push({ + property: key, + value: dto[key], + }); + } + } + throw new DuplicateEntityException(duplicateEntityInfo); + } + + protected async getTotalQueryBuilder( + qb: SelectQueryBuilder, + ): Promise> { + const totalQb = qb.clone(); + totalQb.offset(0).skip(0).take(undefined).limit(undefined); + return totalQb; + } + + getUpdateRows(returned: any): number { + return returned?.affected; + } + + isFindOne(queryArg): boolean { + return queryArg.id !== undefined; + } +} diff --git a/src/commons/services/password-converter.ts b/src/commons/services/password-converter.ts new file mode 100644 index 0000000..c92047d --- /dev/null +++ b/src/commons/services/password-converter.ts @@ -0,0 +1,15 @@ +import { Injectable } from '@nestjs/common'; +import { compare, genSalt, hash } from 'bcrypt'; + +@Injectable() +export class PasswordConverter { + async convertToStore(pwd: string | undefined): Promise { + if (pwd === undefined) { + return undefined; + } + return await hash(pwd, await genSalt()); + } + async compare(rawPwd: string, storePwd: string): Promise { + return await compare(rawPwd, storePwd); + } +} diff --git a/src/commons/services/typeorm-helper.ts b/src/commons/services/typeorm-helper.ts new file mode 100644 index 0000000..61a0d3b --- /dev/null +++ b/src/commons/services/typeorm-helper.ts @@ -0,0 +1,304 @@ +import { SelectQueryBuilder } from 'typeorm'; + +interface PaginationInterface { + pageSize?: number; + pageIndex?: number; + take?: number; + skip?: number; +} + +export class TypeormHelper { + static pagination(qb: SelectQueryBuilder, params: PaginationInterface) { + if (!params.take || isNaN(params.take)) { + if (!params.pageSize || isNaN(params.pageSize)) { + params.pageSize = 50; + } + params.take = params.pageSize; + } + if (!params.skip || isNaN(params.skip)) { + if (!params.pageIndex || isNaN(params.pageIndex)) { + params.pageIndex = 1; + } + params.skip = (params.pageIndex - 1) * params.pageSize; + } + if (params.skip) { + qb.skip(params.skip); + } + if (params.take) { + qb.take(params.take); + } + } + + static pagination4Raw( + qb: SelectQueryBuilder, + params: PaginationInterface, + ) { + if (!params.take || isNaN(params.take)) { + if (!params.pageSize || isNaN(params.pageSize)) { + params.pageSize = 15; + } + params.take = params.pageSize; + } + if (!params.skip || isNaN(params.skip)) { + if (!params.pageIndex || isNaN(params.pageIndex)) { + params.pageIndex = 1; + } + params.skip = (params.pageIndex - 1) * params.pageSize; + } + if (params.skip) { + qb.offset(params.skip); + } + if (params.take) { + qb.limit(params.take); + } + } + + static filterActive( + qb: SelectQueryBuilder, + alias: string, + params: { isActive?: boolean }, + ) { + if (params.isActive === true || params.isActive === false) { + qb.andWhere(`${alias}.isActive = :isActive`, params); + } + } + + static filterDeletion( + qb: SelectQueryBuilder, + alias: string, + params: { isDelete?: boolean; includeDeleted?: boolean }, + ) { + if (params.isDelete && params.includeDeleted) { + qb.andWhere(`${alias}.isDelete = true`); + } else if (params.isDelete === false || !params.includeDeleted) { + qb.andWhere(`${alias}.isDelete = false`); + } + } + + static rangeFilter( + qb: SelectQueryBuilder, + alias: string, + fieldName: string, + params, + ) { + const beginAt = params[`${fieldName}GT`]; + const endAt = params[`${fieldName}LT`]; + if (beginAt) { + qb.andWhere(`${alias}.${fieldName} >= :${`${fieldName}GT`}`, { + [`${fieldName}GT`]: beginAt, + }); + } + if (endAt) { + qb.andWhere(`${alias}.${fieldName} <= :${`${fieldName}LT`}`, { + [`${fieldName}LT`]: endAt, + }); + } + } + + static dateTimeRangeFilter2( + qb: SelectQueryBuilder, + alias: string, + fieldName: string, + beginAt: Date, + endAt: Date, + ) { + if (beginAt) { + qb.andWhere(`${alias}.${fieldName} >= :beginAt`, { beginAt }); + } + if (endAt) { + qb.andWhere(`${alias}.${fieldName} <= :endAt`, { endAt }); + qb.andWhere(`${alias}.${fieldName} >= :${fieldName}BeginAt`, { + [`${fieldName}BeginAt`]: beginAt, + }); + } + if (endAt) { + qb.andWhere(`${alias}.${fieldName} <= :${fieldName}EndAt`, { + [`${fieldName}EndAt`]: endAt, + }); + } + } + + static baseQuery( + qb: SelectQueryBuilder, + alias: string, + params: { + isDelete?: boolean; + includeDeleted?: boolean; + isActive?: boolean; + } & PaginationInterface, + ) { + this.filterByIds(qb, alias, params); + this.pagination(qb, params); + this.filterActive(qb, alias, params); + this.filterDeletion(qb, alias, params); + } + + static excludeDeletedRecords(qb: SelectQueryBuilder, alias: string) { + qb.andWhere(`${alias}.isDelete = FALSE`); + } + + static filterBoolean( + qb: SelectQueryBuilder, + alias: string, + params: any, + ) { + for (const key of Object.keys(params)) { + if (params[key] === true || params[key] === false) { + const sql = `${alias}.${key} = :${key}`; + qb.andWhere(sql, { [key]: params[key] }); + } + } + } + + static filterBooleanWhenExists( + qb: SelectQueryBuilder, + alias: string, + field: string, + params: { [field: string]: any }, + ) { + params[field] !== undefined && + params[field] !== null && + qb.andWhere(`${alias}.${field} = :${field}`, params); + } + + static filterEqual( + qb: SelectQueryBuilder, + alias: string, + field: string, + params: { [field: string]: any }, + ) { + params[field] !== undefined && + qb.andWhere(`${alias}.${field} = :${field}`, params); + } + + static sortResults( + qb: SelectQueryBuilder, + alias: string, + field: string, + params: { [field: string]: any }, + ) { + params[`${field}OrderBy`] !== undefined && + qb.addOrderBy(`${alias}.${field}`, params[`${field}OrderBy`]); + } + + static filterLike( + qb: SelectQueryBuilder, + alias: string, + field: string & (keyof Conditions | keyof T), + params: { [f: string]: any }, + ) { + params[field] && + qb.andWhere(`${alias}.${field} LIKE :like-$${field}`, { + [`like-${field}`]: `%${params[field]}%`, + }); + } + + static filterLike2( + qb: SelectQueryBuilder, + dbField: string, + pField: string, + params: { [field: string]: any }, + ) { + params[pField] && + qb.andWhere(`${dbField} LIKE :like-$${pField}`, { + [`like-${pField}`]: `%${params[pField]}%`, + }); + } + + static filterLike3( + qb: SelectQueryBuilder, + alias: string, + field: string, + params: { [field: string]: any }, + ) { + params[field] && + qb.andWhere(`${alias}.${field} LIKE :like-${field}`, { + [`like-${field}`]: `${params[field]}%`, + }); + } + + static filterNameOrRemark( + qb: SelectQueryBuilder, + alias: string, + params: { [field: string]: any }, + nameField = 'name', + remarkField = 'remark', + pField = 'name', + ) { + params[pField] && + qb.andWhere((qb1) => + qb1 + .orWhere(`${nameField} LIKE :${pField}`, { + [pField]: `%${params[pField]}%`, + }) + .orWhere(`${remarkField} LIKE :${pField}`, { + [pField]: `%${params[pField]}%`, + }) + .getQuery(), + ); + } + + static filterUserByIdOrName( + qb: SelectQueryBuilder, + alias: string, + entityName: string, + params: { [field: string]: any }, + ) { + TypeormHelper.filterEqual(qb, alias, `${entityName}Id`, params); + TypeormHelper.filterLike2( + qb, + `${entityName}.nick`, + `${entityName}Name`, + params, + ); + } + + static filterUserByIdOrName2( + qb: SelectQueryBuilder, + alias: string, + entityName: string, + field = 'name', + params: { [field: string]: any }, + ) { + TypeormHelper.filterEqual(qb, alias, `${entityName}Id`, params); + TypeormHelper.filterLike2( + qb, + `${entityName}.${field}`, + `${entityName}Name`, + params, + ); + } + + static filterByIds( + qb: SelectQueryBuilder, + alias: string, + params: { [field: string]: any }, + ) { + let ids = Array.isArray(params.ids) ? params.ids : [params.id]; + ids = ids.filter((id) => !!id); + if (ids.length > 0) { + qb.andWhereInIds(ids); + } + } + + static filterIn( + qb: SelectQueryBuilder, + alias: string, + dbField: string, + pField: string, + params: { [field: string]: any }, + ) { + if (!Array.isArray(params[pField])) { + return; + } + if (params[pField].length > 0) { + qb.andWhere(`${alias}.${dbField} IN (:...${pField})`, params); + } else { + qb.where('1 <> 1'); + } + } + + static getUserParentIds(user) { + return user.path.split('/').filter((v) => !!v); + } +} diff --git a/src/main.ts b/src/main.ts index 0bdd83f..2cb827e 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,3 +1,4 @@ +import { ValidationPipe } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; @@ -5,6 +6,7 @@ import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const configService = app.get(ConfigService); + app.useGlobalPipes(new ValidationPipe()); await app.listen(configService.get('http.port')); } bootstrap(); diff --git a/src/projects/dtos/create-project.input.ts b/src/projects/dtos/create-project.input.ts new file mode 100644 index 0000000..7988e10 --- /dev/null +++ b/src/projects/dtos/create-project.input.ts @@ -0,0 +1,28 @@ +import { InputType } from '@nestjs/graphql'; +import { IsString, IsUrl, MaxLength, MinLength } from 'class-validator'; + +@InputType({ isAbstract: true }) +export class CreateProjectInput { + @IsString() + @MaxLength(32) + @MinLength(2) + name: string; + + @IsString() + @MaxLength(32) + @MinLength(2) + comment: string; + + @IsUrl({ protocols: ['ssh'], require_protocol: false }) + @MaxLength(256) + sshUrl: string; + + @IsUrl() + @MaxLength(256) + webUrl?: string; + + @IsString() + @MaxLength(128) + @MinLength(1) + webHookSecret?: string; +} diff --git a/src/projects/dtos/update-project.input.ts b/src/projects/dtos/update-project.input.ts new file mode 100644 index 0000000..419d7c4 --- /dev/null +++ b/src/projects/dtos/update-project.input.ts @@ -0,0 +1,5 @@ +import { InputType } from '@nestjs/graphql'; +import { CreateProjectInput } from './create-project.input'; + +@InputType() +export class UpdateProjectInput extends CreateProjectInput {} diff --git a/src/projects/project.entity.ts b/src/projects/project.entity.ts new file mode 100644 index 0000000..07ec46d --- /dev/null +++ b/src/projects/project.entity.ts @@ -0,0 +1,28 @@ +import { ObjectType } from '@nestjs/graphql'; +import { AppBaseEntity } from 'src/commons/entities/app-base-entity'; +import { Entity, Column, DeleteDateColumn } from 'typeorm'; + +@ObjectType() +@Entity() +export class Project extends AppBaseEntity { + /** + * 唯一名称 + */ + @Column() + name: string; + + @Column() + comment: string; + + @Column() + sshUrl: string; + + @Column({ nullable: true }) + webUrl?: string; + + @Column({ nullable: true }) + webHookSecret?: string; + + @DeleteDateColumn() + deletedAt?: Date; +} diff --git a/src/projects/projects.module.ts b/src/projects/projects.module.ts new file mode 100644 index 0000000..daea7db --- /dev/null +++ b/src/projects/projects.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { ProjectsService } from './projects.service'; +import { ProjectsResolver } from './projects.resolver'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { Project } from './project.entity'; + +@Module({ + imports: [TypeOrmModule.forFeature([Project])], + providers: [ProjectsService, ProjectsResolver], +}) +export class ProjectsModule {} diff --git a/src/projects/projects.resolver.spec.ts b/src/projects/projects.resolver.spec.ts new file mode 100644 index 0000000..0a93e17 --- /dev/null +++ b/src/projects/projects.resolver.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { ProjectsResolver } from './projects.resolver'; + +describe('ProjectsResolver', () => { + let resolver: ProjectsResolver; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ProjectsResolver], + }).compile(); + + resolver = module.get(ProjectsResolver); + }); + + it('should be defined', () => { + expect(resolver).toBeDefined(); + }); +}); diff --git a/src/projects/projects.resolver.ts b/src/projects/projects.resolver.ts new file mode 100644 index 0000000..caf3ce0 --- /dev/null +++ b/src/projects/projects.resolver.ts @@ -0,0 +1,41 @@ +import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; +import { CreateProjectInput } from './dtos/create-project.input'; +import { UpdateProjectInput } from './dtos/update-project.input'; +import { Project } from './project.entity'; +import { ProjectsService } from './projects.service'; + +@Resolver(() => Project) +export class ProjectsResolver { + constructor(private readonly service: ProjectsService) {} + @Query(() => [Project]) + async findProjects() { + return await this.service.list(); + } + + @Query(() => Project) + async findProject(@Args('id', { type: () => String }) id: string) { + return await this.service.findOne(id); + } + + @Mutation(() => Project) + async createProject( + @Args('project', { type: () => CreateProjectInput }) + dto: UpdateProjectInput, + ) { + return await this.service.create(dto); + } + + @Mutation(() => Boolean) + async modifyProject( + @Args('id', { type: () => String }) id: string, + @Args('project', { type: () => UpdateProjectInput }) + dto: UpdateProjectInput, + ) { + return await this.service.update(id, dto); + } + + @Mutation(() => Number) + async deleteProject(@Args('id', { type: () => String }) id: string) { + return await this.service.remove(id); + } +} diff --git a/src/projects/projects.service.spec.ts b/src/projects/projects.service.spec.ts new file mode 100644 index 0000000..d3b3101 --- /dev/null +++ b/src/projects/projects.service.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { ProjectsService } from './projects.service'; + +describe('ProjectsService', () => { + let service: ProjectsService; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ProjectsService], + }).compile(); + + service = module.get(ProjectsService); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); +}); diff --git a/src/projects/projects.service.ts b/src/projects/projects.service.ts new file mode 100644 index 0000000..54ccded --- /dev/null +++ b/src/projects/projects.service.ts @@ -0,0 +1,35 @@ +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { BaseDbService } from 'src/commons/services/base-db.service'; +import { Repository } from 'typeorm'; +import { CreateProjectInput } from './dtos/create-project.input'; +import { Project } from './project.entity'; + +@Injectable() +export class ProjectsService extends BaseDbService { + readonly uniqueFields: Array = ['name']; + constructor( + @InjectRepository(Project) + readonly repository: Repository, + ) { + super(repository); + } + + async list() { + return this.repository.find(); + } + + async create(dto: CreateProjectInput) { + await this.isDuplicateEntity(dto); + return await this.repository.save(this.repository.create(dto)); + } + + async update(id: string, dto: CreateProjectInput) { + await this.isDuplicateEntityForUpdate(id, dto); + await this.repository.update({ id }, dto); + } + + async remove(id: string) { + return (await this.repository.softDelete({ id })).affected; + } +}