├── .babelrc ├── .eslintrc ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── apidoc.json ├── article.md ├── config ├── development.js ├── errorCode.js ├── index.js └── product.js ├── nodemon.json ├── package.json ├── pm2.json ├── server.js ├── src ├── bin │ └── app.js ├── lib │ ├── dbConnection.js │ ├── log.js │ └── resFormat.js └── routes │ ├── index.js │ └── user │ ├── index.js │ ├── user.controller.js │ ├── user.lib.js │ └── user.model.js └── test ├── routes └── user │ ├── user.controller.test.js │ ├── user.lib.test.js │ ├── user.model.test.js │ └── user.test.js └── test.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["latest"] 3 | } -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "env": { 4 | "browser": true, 5 | "es6": true, 6 | "node": true 7 | }, 8 | "globals": { 9 | "_": true, 10 | "moment": true, 11 | "process": true, 12 | "describe": true, 13 | "before": true, 14 | "after": true, 15 | "it": true 16 | }, 17 | "plugins": [ 18 | "babel" 19 | ], 20 | "rules": { 21 | /* 22 | ** STRICT MODE 23 | ** These rules relate to using strict mode. 24 | */ 25 | "strict": 0, // `[2, "function"]` is default, optionally set `[2, "never"]` 26 | 27 | /* 28 | ** VARIABLES 29 | ** These rules have to do with variable declarations. 30 | */ 31 | "init-declarations": 0, // `[2, "always"]` is default 32 | "no-catch-shadow": 0, // `2` is default 33 | "no-delete-var": 1, // `2` is default 34 | "no-label-var": 2, 35 | "no-shadow-restricted-names": 2, 36 | "no-shadow": [2, {"builtinGlobals": false, "hoist": "all"}], // `[2, {"builtinGlobals": false, "hoist": "functions"}]` is default 37 | "no-undef-init": 1, // `2` is default 38 | "no-undef": 2, 39 | "no-undefined": 2, 40 | "no-unused-vars": [2, {"vars": "all", "args": "all"}], // `[2, {"vars": "all", "args": "after-used"}]` is default, optionally set `[2, {"vars": "all", "args": "after-used", "varsIgnorePattern": "", "argsIgnorePattern": ""}]` 41 | "no-use-before-define": 1, 42 | 43 | /* 44 | ** POSSIBLE ERRORS 45 | ** The following rules point out areas where you might 46 | ** have made mistakes. 47 | */ 48 | "comma-dangle": [1, "always-multiline"], 49 | "no-cond-assign": [2, "except-parens"], 50 | "no-console": [1, { "allow": ["error", "info"] }], // `2` is default. Set to `0` when developing with node 51 | "no-constant-condition": 2, 52 | "no-control-regex": 2, 53 | "no-debugger": 2, 54 | "no-dupe-args": 2, 55 | "no-dupe-keys": 2, 56 | "no-duplicate-case": 2, 57 | "no-empty-character-class": 2, 58 | "no-empty": 2, 59 | "no-ex-assign": 2, 60 | "no-extra-boolean-cast": 2, 61 | "no-extra-parens": [1, "all"], // `[2, "all"]` is default 62 | "no-extra-semi": 1, // `2` is default 63 | "no-func-assign": 2, 64 | "no-inner-declarations": [2, "both"], // `[2, "functions"]` is default 65 | "no-invalid-regexp": 2, 66 | "no-irregular-whitespace": 2, 67 | "no-negated-in-lhs": 2, 68 | "no-obj-calls": 2, 69 | "no-regex-spaces": 2, 70 | "no-sparse-arrays": 2, 71 | "no-unreachable": 2, 72 | "use-isnan": 2, 73 | "valid-jsdoc": 0, // `2` is default 74 | "valid-typeof": 2, 75 | "no-unexpected-multiline": 2, 76 | 77 | /* 78 | ** BEST PRACTICES 79 | ** These are rules designed to prevent you from making mistakes. 80 | ** They either prescribe a better way of doing something or help 81 | ** you avoid footguns. 82 | */ 83 | "accessor-pairs": [2, {"getWithoutSet": false, "setWithoutGet": true}], 84 | "block-scoped-var": 2, 85 | "complexity": [1, 20], // `[2, 2]` is recommended 86 | "consistent-return": 0, 87 | "curly": [2, "all"], 88 | "default-case": 2, 89 | "dot-notation": [2, {"allowKeywords": true, "allowPattern": ""}], 90 | "dot-location": [2, "property"], // `[2, "object"]` is recommended 91 | "eqeqeq": 2, // `2` is recommended, optionally set `[2, "smart"]` or `[2, "allow-null"]` 92 | "guard-for-in": 2, 93 | "no-alert": 1, // `2` is recommended 94 | "no-caller": 2, 95 | "no-div-regex": 2, 96 | "no-else-return": 2, 97 | "no-eq-null": 2, 98 | "no-eval": 2, 99 | "no-extend-native": 2, // `2` is recommended, optionally set `[2, {"exceptions": ["Object"]}]` 100 | "no-extra-bind": 2, 101 | "no-fallthrough": 1, // `2` is recommended 102 | "no-floating-decimal": 1, // `2` is recommended 103 | "no-implicit-coercion": [1, {"boolean": false, "number": true, "string": false}], // `[2, {"boolean": true, "number": true, "string": true}],` is recommended 104 | "no-implied-eval": 2, 105 | "no-invalid-this": 0, // `2` is recommended 106 | "no-iterator": 2, 107 | "no-labels": 2, 108 | "no-lone-blocks": 2, 109 | "no-loop-func": 2, 110 | "no-multi-spaces": [2, {"exceptions": {"VariableDeclarator": true, "ImportDeclaration": true, "AssignmentExpression": true, "ObjectExpression": true}}], // `2` is recommended 111 | "no-multi-str": 2, 112 | "no-native-reassign": 2, // `2` is recommended, optionally set `[2, {"exceptions": ["Object"]}]` 113 | "no-new-func": 2, 114 | "no-new-wrappers": 2, 115 | "no-new": 2, 116 | "no-octal-escape": 2, 117 | "no-octal": 2, 118 | "no-param-reassign": 1, // `2` is recommended and actually defaults to `[2, {"props": false}]` 119 | "no-proto": 2, 120 | "no-redeclare": [2, {"builtinGlobals": true}], // `2` is recommended and actually defaults to `[2, {"builtinGlobals": false}]` 121 | "no-return-assign": [2, "except-parens"], 122 | "no-script-url": 2, 123 | "no-self-compare": 2, 124 | "no-sequences": 2, 125 | "no-throw-literal": 2, 126 | "no-unused-expressions": 2, // `2` is recommended and actually defaults to `[2, {"allowShortCircuit": false, "allowTernary": false}]` 127 | "no-useless-call": 1, // `2` is recommended 128 | "no-useless-concat": 2, 129 | "no-void": 2, 130 | "no-warning-comments": [1, {"terms": ["todo", "fixme"], "location": "start"}], // `[0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }]` is recommended 131 | "no-with": 2, 132 | "radix": 1, // `2` is recommended 133 | "vars-on-top": 1, // `2` is recommended 134 | "wrap-iife": [2, "inside"], // `[2, "outside"]` is recommended 135 | "yoda": [1, "never"], // `[2, "never"]` is recommended, optionally set `[2, "never", {"exceptRange": true, "onlyEquality": false}] 136 | 137 | /* 138 | ** STYLISTIC ISSUES 139 | ** These rules are purely matters of style and are 140 | ** quite subjective. 141 | */ 142 | "array-bracket-spacing": [1, "never"], // optionally set `[2, "never", {"singleValue": true, "objectsInArrays": true, "arraysInArrays": true}]` 143 | "block-spacing": [1, "always"], 144 | "brace-style": [1, "1tbs", {"allowSingleLine": false}], 145 | "camelcase": 0, 146 | "comma-spacing": [1, {"before": false, "after": true}], 147 | "comma-style": [1, "last"], // optionally set `[2, "first", {"exceptions": {"ArrayExpression": true, "ObjectExpression": true}}]` 148 | "computed-property-spacing": [1, "never"], 149 | "consistent-this": [1, "self"], 150 | "eol-last": 0, 151 | "func-names": 0, 152 | "func-style": 0, // optionally set `[2, "expression"]` 153 | "id-length": 0, // optionally set `[2, {"min": 3, "max": 10, "properties": "never", "exceptions": ["x"]}]` 154 | "id-match": 0, // optionally set `[2, "^[a-z]+([A-Z][a-z]+)*$", {"properties": false}]` 155 | "indent": [1, 2, {"SwitchCase": 1, "VariableDeclarator": 2}], // optionally set `[2, 2, {"SwitchCase": 1, "VariableDeclarator": {"var": 2, "let": 2, "const": 3}}]` 156 | "jsx-quotes": [1, "prefer-double"], 157 | "key-spacing": [1, {"beforeColon": false, "afterColon": true, "mode": "minimum"}], // optionally set `[2, {"beforeColon": false, "afterColon": true, "mode": "strict", "align": "colon"}]` 158 | "lines-around-comment": 0, // optionally set `[2, {"beforeBlockComment": true, "beforeLineComment": true, "allowBlockStart": true}]` 159 | "linebreak-style": 0, // optionally set `[1, "unix"]` 160 | "max-nested-callbacks": [1, 3], 161 | "new-cap": [1, {"newIsCap": true, "capIsNew": true}], // optionally set `[2, {"capIsNewExceptions": ["Person"]}]` 162 | "new-parens": 1, 163 | "newline-after-var": 0, 164 | "no-array-constructor": 1, 165 | "no-continue": 1, 166 | "no-inline-comments": 0, 167 | "no-lonely-if": 1, 168 | "no-mixed-spaces-and-tabs": 1, // optionally set `[2, "smart-tabs"]` 169 | "no-multiple-empty-lines": [1, {"max": 1}], 170 | "no-nested-ternary": 1, 171 | "no-new-object": 1, 172 | "no-restricted-syntax": 0, // optionally set `[2, "FunctionExpression", "WithStatement"]` 173 | "no-spaced-func": 1, 174 | "no-ternary": 0, 175 | "no-trailing-spaces": [1, {"skipBlankLines": false}], 176 | "no-underscore-dangle": 0, 177 | "no-unneeded-ternary": [1, {"defaultAssignment": true}], 178 | "object-curly-spacing": [2, "always"], // optionally set `[2, "always", {"objectsInObjects": false, "arraysInObjects": false}]` 179 | "one-var": [1, {"uninitialized": "always", "initialized": "never"}], // optionally set `[2, {"var": "always", "let": "never", "const": "never"}]` 180 | "operator-assignment": 0, // optionally set `[2, "always"]` 181 | "operator-linebreak": [1, "after"], // optionally set `[2, "before", {"overrides": {"?": "after"}}]` 182 | "padded-blocks": [1, "never"], 183 | "quote-props": [1, "as-needed", {"keywords": false, "unnecessary": false, "numbers": true}], 184 | "quotes": [1, "single", "avoid-escape"], 185 | "require-jsdoc": 0, 186 | "semi-spacing": [1, {"before": false, "after": true}], 187 | "semi": [2, "never"], 188 | "sort-vars": 0, // optaionlly set `[2, {"ignoreCase": true}]` 189 | "keyword-spacing": 2, 190 | "space-before-blocks": [1, "always"], // optionally set `[2, {"functions": "never", "keywords": "always"}]` 191 | "space-before-function-paren": [1, "never"], // optionally set `[2, {"anonymous": "always", "named": "never"}]` 192 | "space-in-parens": [1, "never"], // optionally set `[2, "always", {"exceptions": ["empty"]}]` 193 | "space-infix-ops": [1, {"int32Hint": false}], 194 | "space-unary-ops": [1, {"words": true, "nonwords": false}], 195 | "spaced-comment": [1, "always", {"exceptions": ["/"]}], // optionally set `[2, "always", {"exceptions": ["-", "+"], "markers": ["/"]}]` 196 | "wrap-regex": 1, 197 | 198 | /* 199 | ** ECMASCRIPT 6 200 | ** These rules are only relevant to ES6 environments. 201 | */ 202 | "arrow-parens": 0, 203 | "babel/arrow-parens": 2, 204 | "arrow-spacing": [2, {"before": true, "after": true}], 205 | "constructor-super": 2, 206 | "generator-star-spacing": [0, {"before": false, "after": true}], 207 | "babel/generator-star-spacing": [2, {"before": false, "after": true}], 208 | "no-class-assign": 2, 209 | "no-const-assign": 2, 210 | "no-dupe-class-members": 0, // `2` is default, only use on ES6+ environments 211 | "no-this-before-super": 2, 212 | "no-var": 0, // `2` is default, only use on ES6+ environments - when using this set `"blockBindings": true` in `ecmaFeatures` object 213 | "object-shorthand": 0, // `[2, "always"]` is default 214 | "prefer-arrow-callback": 0, // `2` is default, only use on ES6+ environments 215 | "prefer-const": 1, // `2` is default 216 | "prefer-spread": 0, // `2` is default, only use on ES6+ environments 217 | "prefer-reflect": 0, // `2` is default, only use on ES6+ environments, optionally set `[2, {exceptions: ["apply", "call"]}]` 218 | "prefer-template": 0, // `2` is default, only use on ES6+ environments 219 | "require-yield": 2, 220 | 221 | /* 222 | ** NODE.JS AND COMMONJS 223 | ** These rules are specific to JavaScript running on Node.js or 224 | ** using CommonJS in the browser. 225 | */ 226 | "callback-return": 0, // `2` is default, optionally set `[2, ["callback", "cb", "next"]]` 227 | "global-require": 0, // `2` is default 228 | "handle-callback-err": 0, // `2` is default, optionally set `[2, "^(err|error)$"]` 229 | "no-mixed-requires": 0, // [2, false] is default 230 | "no-new-require": 0, // `2` is default 231 | "no-path-concat": 0, // `2` is default 232 | "no-process-exit": 0, // `2` is default 233 | "no-restricted-modules": 0, // no default, optionally set `[2, "fs", "os"]` 234 | "no-sync": 0, // `2` is default 235 | 236 | /* 237 | ** LEGACY 238 | ** The following rules are included for compatibility with JSHint and 239 | ** JSLint. While the names of the rules may not match up with the 240 | ** JSHint/JSLint counterpart, the functionality is the same. 241 | */ 242 | "max-depth": 0, // `[2, 4]` is default 243 | "max-len": 0, // `[2, 80, 4]` is default, optionally set `[2, 80, 4, {"ignoreComments": true, "ignoreUrls": true}]` 244 | "max-params": 0, // no default, optionally set `[2, 3]` 245 | "max-statements": 0, // no default, optionally set `[2, 2]` 246 | "no-bitwise": 1, // `2` is default 247 | "no-plusplus": 0 // `2` is default 248 | } 249 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | /**/*.swp 3 | npm-debug.log 4 | .vscode 5 | coverage 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | online: 2 | git fetch && git reset --hard && git checkout origin/master && npm install --production && pm2 startOrRestart pm2.json 3 | development: 4 | git fetch && git reset --hard && git checkout origin/master && npm install --development && pm2 startOrRestart pm2.json 5 | test: 6 | npm test -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 描述 2 | ----- 3 | 项目主要目的是在用户登录,注册场景下介绍如何使用sinon来实施 4 | 5 | 6 | ### 项目环境说明 7 | Node.js 5.8.0 8 | 9 | 更多依赖信息查看项目的package.json文件 10 | 11 | 12 | ----- 13 | 14 | ### 组件 15 | 语法检查: eslint 16 | 17 | 文档:apidoc 18 | 19 | 日志:log4js, 日志会统一打到/var/log目录下 20 | 21 | 调试:nodemon 22 | 23 | Http框架:koa 24 | 25 | javascript版本:es6 26 | 27 | 测试框架:mocha 28 | 29 | 测试组件:sinon 30 | 31 | 测试断言: assert 32 | 33 | database: mysql 34 | 35 | 36 | ---- 37 | 38 | ### 如果启动 39 | 开发调试:npm start 40 | 41 | 测试:npm test 42 | 43 | 生产部署:make online 44 | 45 | 测试部署:make test 46 | 47 | ---- 48 | -------------------------------------------------------------------------------- /apidoc.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mocha-sinon", 3 | "version": "1.0.0", 4 | "description": "sinon的使用demo项目", 5 | "title": "mocha-sinon", 6 | "url" : "" 7 | } -------------------------------------------------------------------------------- /article.md: -------------------------------------------------------------------------------- 1 | Sinon 入门,看这篇文章就够了 2 | ---- 3 | 4 | # 为什么需要Sinon 5 | 当我们在开发前端项目的时候, 很多时候需要根据后端返回的数据来渲染页面, 我们通常使用AJAX发送请求给服务端。当我们开发后端逻辑的时候有时候需要连接数据库,根据从数据库中得到的数据来执行后续的逻辑代码, 或者其他的依赖, 甚至会更加复杂棘手。这些开发都存在一个共同的局限性, 就是会去依赖别的服务, 需要别的系统的支持。 例如, 如果我们使用Ajax请求网络, 您需要有一个服务器来响应对应的请求。对于数据库, 您需要有一个为测试设置的测试数据库。 6 | 7 | 所有这些都意味着编写和运行测试更加困难, 因为您需要做额外的工作来准备和设置一个测试成功的环境。 8 | 值得庆幸的是, 我们可以用sinon.js避免所有麻烦。我们可以利用它的特性将上面的例子简化为几行代码。 9 | 10 | 然而, 第一次接触`spies`, `stub`, `mock`可能棘手。它可能很难选择什么时候用什么功能。它们也有一些问题,所以你需要知道你应该用什么功能解决什么样的问题。 11 | 在这篇文章中将向你展示`spies`, `stub`, `mock`何时以及如何使用它们,并给你一套最佳实践,帮助您避免常见的陷阱. 12 | 13 | # 什么是Sinon 14 | `Sinon`具有独立的spies, stub, mock功能,`Sinon`并不是独立的测试框架,它只是在测试中提供了上述的三种功能, 例如我们常用的测试框架`Mocha`,`Sinon`并不能完全替代`Mocha`的功能。 15 | 16 | `Sinon`通过所谓的测试替代(`test-double`)轻松消除测试的复杂度, 17 | 测试替代,顾名思义,测试中用到的是真实代码逻辑的替代品。回过头来看Ajax示例,我们不需要设置服务器,而是用Ajax的替代代码,我们把Ajax的逻辑替换成不需要通过请求服务器就返回预先设置好的数据,这听起来有不可思议,但是基本概念很简单。因为JavaScript是动态的,所以我们可以在调用某个方法的时候使用任何函数来替换它。在`Sinon`中们可以用一个测试逻辑取代任何JavaScript函数,然后让测试复杂的事情变的简单化。 18 | 19 | ## spies的概念 20 | 顾名思义,`spies`我们干脆就把它称作间谍函数好了,间谍函数是`Sinon`最简单的部分,其它的功能都是建立在`spies`之上的,`spies`的主要用途是收集有关函数调用的信息。您还可以使用它们来帮助验证事物,例如是否调用了函数等。就像电影《窃听风云》中一样,监听房间内都有那些人进出,做了什么事,而且这个监听过程是不会房间内的人感知的。同样`spies`的实现监听的基础上是不会影响函数本身的正常调用(被监听的函数的上下文关系不会被影响)。当然我们实现是需要在`房间里偷偷的安装窃听器`的, 那么`spies`的窃听器是如何实现的呢?后文我们有介绍 21 | 22 | ## stub的概念 23 | 他们拥有`spies`的所有功能,不是监视某个函数的调用情况,而是完全取代了这个函数。换句话说,当使用`spies`时,原始函数仍然运行,但是当使用`stub`时,函数将不具有原始的功能,而是替换后的函数。 24 | 25 | ## mock的概念 26 | `mock`与`stub`的功能一样都是用来替换指定的函数,如果你想替换掉一个对象中的多个方法,这时`mock`就可以发挥作用了,但是如果仅仅是替换对象中的一个函数,那么`stub`更加简单易用,当我们使用`mock`的时候应该十分小心,因为大量的替换原有代码逻辑,会导致test变的`脆弱`, 27 | 28 | ----- 29 | 30 | # Sinon的使用场景 31 | ## spies 32 | 正如名字所暗示的,`spies`被用来获取关于函数调用的信息。例如,一个`spies`可以告诉我们调用一个函数的次数、每次调用的参数、返回的值、抛出的错误等。因此,当测试的目的是验证发生的事情时,间谍是一个很好的选择。结合`Sinon`的说法,我们可以通过一个简单的`spies`检查不同的结果。 33 | 34 | 间谍最常见的场景包括: 35 | 36 | - 检查函数被调用了多少次 37 | ``` 38 | it('should call save once', function() { 39 | var save = sinon.spy(Database, 'save'); 40 | 41 | setupNewUser({ name: 'test' }, function() { }); 42 | 43 | save.restore(); 44 | sinon.assert.calledOnce(save); 45 | }); 46 | ``` 47 | - 检查传递给函数的参数 48 | ``` 49 | it('should pass object with correct values to save', function() { 50 | var save = sinon.spy(Database, 'save'); 51 | var info = { name: 'test' }; 52 | var expectedUser = { 53 | name: info.name, 54 | nameLowercase: info.name.toLowerCase() 55 | }; 56 | 57 | setupNewUser(info, function() { }); 58 | 59 | save.restore(); 60 | sinon.assert.calledWith(save, expectedUser); 61 | }); 62 | ``` 63 | ## stub 64 | 存根就像间谍,除了它们替换目标功能。它们还可以包含自定义行为,例如返回值,或抛出异常。他们甚至可以自动调用作为参数提供的任何回调函数。 65 | 66 | 存根有几个常用的用途: 67 | 68 | - 您可以使用它们来代替有问题的代码段 69 | - 您可以使用它们来触发不会触发的代码路径,例如错误处理 70 | - 您可以使用它们来帮助测试异步代码更容易 71 | - 存根可用于替代有问题的代码,即使写入测试困难的代码。这通常是外部网络连接,数据库或其他非JavaScript引起的。这些问题是它们经常需要手动设置。例如,在运行测试之前,我们需要填写一个带有测试数据的数据库,这使得运行和写入更复杂。 72 | ``` 73 | it('should pass object with correct values to save', function() { 74 | var save = sinon.stub(Database, 'save'); 75 | var info = { name: 'test' }; 76 | var expectedUser = { 77 | name: info.name, 78 | nameLowercase: info.name.toLowerCase() 79 | }; 80 | 81 | setupNewUser(info, function() { }); 82 | 83 | save.restore(); 84 | sinon.assert.calledWith(save, expectedUser); 85 | }); 86 | 87 | ``` 88 | 通过用stub替换与数据库相关的功能,我们不再需要实际的数据库进行测试。 几乎任何情况下,类似的方法都可以用于其他难以测试的代码。 89 | 90 | 存根也可用于触发不同的代码路径。 如果我们测试的代码调用另一个函数,我们有时需要测试它在异常条件下的行为, 我们可以使用存根从代码中触发错误: 91 | ``` 92 | it('should pass the error into the callback if save fails', function() { 93 | var expectedError = new Error('oops'); 94 | var save = sinon.stub(Database, 'save'); 95 | save.throws(expectedError); 96 | var callback = sinon.spy(); 97 | 98 | setupNewUser({ name: 'foo' }, callback); 99 | 100 | save.restore(); 101 | sinon.assert.calledWith(callback, expectedError); 102 | }); 103 | ``` 104 | ## mock 105 | 主要用于当你存根的时候想验证多个具体的行为时 106 | 107 | 例如,以下是我们如何使用`mock`验证更具体的数据库保存方案: 108 | ``` 109 | it('should pass object with correct values to save only once', function() { 110 | var info = { name: 'test' }; 111 | var expectedUser = { 112 | name: info.name, 113 | nameLowercase: info.name.toLowerCase() 114 | }; 115 | var database = sinon.mock(Database); 116 | database.expects('save').once().withArgs(expectedUser); 117 | 118 | setupNewUser(info, function() { }); 119 | 120 | database.verify(); 121 | database.restore(); 122 | }); 123 | ``` 124 | # Sinon的实现原理 125 | ## spies 126 | ``` 127 | const sinon = { 128 | spyObjs: {}, 129 | spy: function(obj, method) { 130 | const self = this; 131 | this.spyObjs['spy#:' + (Object.keys(self.spyObjs).length + 1)] = {} 132 | this.proxy(obj, method); 133 | }, proxy: function(obj, method) { 134 | const descriptor = Object.getOwnPropertyDescriptor(obj, method); 135 | const delegateFlag = 'spy#:' + Object.keys(sinon.spyObjs).length; 136 | this.spyObjs[delegateFlag] = { 137 | delegateValue: descriptor.value, 138 | delegateObject: obj 139 | } 140 | Object.defineProperty(obj, method, Object.getOwnPropertyDescriptor(this, 'invoke')) 141 | }, invoke: function(name) { 142 | console.log('参数%s, 被调用了', name) 143 | const delegateFlag = 'spy#:' + Object.keys(sinon.spyObjs).length; 144 | sinon.spyObjs[delegateFlag].delegateValue.apply(sinon.spyObjs[delegateFlag].delegateObject) 145 | } 146 | } 147 | 148 | var testFlag = { 149 | sayHello: function(name) { 150 | console.log('Hello:%s', name) 151 | }, whoAmI: function() { 152 | this.sayHello('bugall') 153 | console.log('Who am i') 154 | } 155 | } 156 | sinon.spy(testFlag, 'whoAmI'); 157 | 158 | testFlag.whoAmI('bugall') 159 | ``` 160 | ## stub 161 | ## mock 162 | 163 | 164 | ##  165 | -------------------------------------------------------------------------------- /config/development.js: -------------------------------------------------------------------------------- 1 | const dbConfig = { 2 | "mysql": { 3 | "host" : "localhost", 4 | "port" : 3306, 5 | "user" : "root", 6 | "password" : "nijiaoa", 7 | "database" : "test", 8 | "connectionLimit" : 100 9 | } 10 | } 11 | 12 | const server = { 13 | port: 3000 14 | } 15 | 16 | const logConfig = { 17 | path: '/var/log', 18 | type: 'console' 19 | } 20 | 21 | export default { dbConfig, server, logConfig} 22 | -------------------------------------------------------------------------------- /config/errorCode.js: -------------------------------------------------------------------------------- 1 | export default { 2 | FORMAT_ERROR: { 3 | msg: '输入数据格式错误', 4 | code: 2001 5 | }, WRONG_PASSWORD: { 6 | msg: '用户密码错误', 7 | code: 3001 8 | }, USER_NOT_EXSIT: { 9 | msg: '用户名不存在', 10 | code: 3010 11 | }, USERNAME_HAS_USED: { 12 | msg: '用户名已被使用', 13 | code: 3020 14 | } 15 | } -------------------------------------------------------------------------------- /config/index.js: -------------------------------------------------------------------------------- 1 | import development from './development' 2 | import product from './product' 3 | 4 | let config = null 5 | 6 | if (process.env.NODE_ENV === 'development') { 7 | config = development 8 | } else if (process.env.NODE_ENV === 'product') { 9 | config = product 10 | } 11 | 12 | export default config -------------------------------------------------------------------------------- /config/product.js: -------------------------------------------------------------------------------- 1 | const dbConfig = { 2 | "mysql": { 3 | "host" : "localhost", 4 | "port" : 3306, 5 | "user" : "root", 6 | "password" : "nijiaoa", 7 | "database" : "test", 8 | "connectionLimit" : 100 9 | } 10 | } 11 | 12 | const server = { 13 | port: 3000 14 | } 15 | 16 | const logConfig = { 17 | path: '/var/log', 18 | type: 'file' 19 | } 20 | 21 | export default { dbConfig, server, logConfig} 22 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": [ 3 | "./src" 4 | ], 5 | "ext": "js jsx html json", 6 | "exec":"npm run eslint && node server.js", 7 | "env": { 8 | "DEBUG":"app:*" 9 | } 10 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-backend-scaffolding", 3 | "version": "2.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "./node_modules/mocha/bin/_mocha", 8 | "eslint": "./node_modules/.bin/eslint src", 9 | "start": "npm run server", 10 | "server": "./node_modules/.bin/babel-node ./server.js", 11 | "doc": "./node_modules/.bin/apidoc -i doc -o doc_content", 12 | "cron": "nodemon server/cron", 13 | "cover": "node_modules/.bin/babel-node node_modules/.bin/babel-istanbul cover node_modules/.bin/_mocha" 14 | }, 15 | "repository": { 16 | "type": "git", 17 | "url": "git+https://github.com/bugall/mocha-sinon-chai.git" 18 | }, 19 | "author": "", 20 | "license": "ISC", 21 | "bugs": { 22 | "url": "https://github.com/bugall/mocha-sinon-chai/issues" 23 | }, 24 | "homepage": "https://github.com/bugall/mocha-sinon-chai#readme", 25 | "dependencies": { 26 | "babel-core": "^6.25.0", 27 | "babel-polyfill": "^6.23.0", 28 | "babel-preset-latest": "^6.24.1", 29 | "bluebird": "^3.5.0", 30 | "koa": "2.0.0", 31 | "koa-bodyparser": "3.1.0", 32 | "koa-qs": "^2.0.0", 33 | "koa-router": "^7.2.1", 34 | "mysql": "^2.13.0" 35 | }, 36 | "devDependencies": { 37 | "apidoc": "^0.17.6", 38 | "babel-cli": "^6.26.0", 39 | "babel-eslint": "^7.2.3", 40 | "babel-istanbul": "^0.12.2", 41 | "babel-preset-es2015": "^6.24.1", 42 | "chai": "^4.0.2", 43 | "eslint": "^4.2.0", 44 | "eslint-plugin-babel": "^4.1.1", 45 | "istanbul": "^0.4.5", 46 | "log4js": "^2.0.0", 47 | "mocha": "^3.5.0", 48 | "nodemon": "^1.11.0", 49 | "sinon": "^2.3.6" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /pm2.json: -------------------------------------------------------------------------------- 1 | { 2 | "apps": [{ 3 | "name": "mocha-sinon", 4 | "script": "app.js", 5 | "cwd": "/var/www/mocha-sinon", 6 | "exec_mode": "cluster", 7 | "instances": 2, 8 | "max_memory_restart": "1G", 9 | "autorestart": true, 10 | "args": [], 11 | "env": { 12 | "NODE_ENV": "production" 13 | }, 14 | "env_test": { 15 | "NODE_ENV": "development", 16 | "DEBUG": "app:*", 17 | "DEBUG_FD": "1" 18 | } 19 | }] 20 | } -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | process.env.NODE_ENV = process.env.NODE_ENV || 'development' 3 | const serverConfig = require('./config').default.server 4 | const http = require('http') 5 | const app = require('./src/bin/app') 6 | const server = http.createServer(app.callback()) 7 | server.listen(serverConfig.port) 8 | server.on('listening', () => { 9 | console.log(`🌐 listening on port 💻 ${serverConfig.port} in ${process.env.NODE_ENV} mode`) 10 | }) 11 | module.exports = app 12 | -------------------------------------------------------------------------------- /src/bin/app.js: -------------------------------------------------------------------------------- 1 | import bodyParser from 'koa-bodyparser' 2 | import Koa from 'koa' 3 | import promise from 'bluebird' 4 | import qs from 'koa-qs' 5 | import ResFormat from '../lib/resFormat' 6 | const resFormat = new ResFormat() 7 | 8 | global.Promise = promise 9 | 10 | const app = new Koa() 11 | import routes from '../routes' 12 | app.use((ctx, next) => { 13 | return next().then(() => { 14 | }).catch((err) => { 15 | ctx.status = 500 16 | ctx.body = '服务器繁忙' 17 | resFormat.proces(ctx, err.message) 18 | }) 19 | }) 20 | 21 | qs(app) 22 | app.use(bodyParser()) 23 | app.use(routes.routes(), routes.allowedMethods()) 24 | module.exports = app 25 | -------------------------------------------------------------------------------- /src/lib/dbConnection.js: -------------------------------------------------------------------------------- 1 | import mysql from 'mysql' 2 | import config from '../../config/index' 3 | import Promise from 'bluebird' 4 | import Log from './log' 5 | const dbConfig = config.dbConfig 6 | 7 | const pool = mysql.createPool({ 8 | connectionLimit: dbConfig.mysql.connectionLimit, 9 | host: dbConfig.mysql.host, 10 | user: dbConfig.mysql.user, 11 | password: dbConfig.mysql.password, 12 | port: dbConfig.mysql.port, 13 | database: dbConfig.mysql.database, 14 | }) 15 | const log = new Log() 16 | 17 | const getConnection = () => { 18 | return new Promise((resolve, reject) => { 19 | pool.getConnection((err, connection) => { 20 | if (err) { 21 | reject(err) 22 | } else { 23 | log.info('log=lib;model=dbConnection;method=getConnection;msg=get connection') 24 | resolve(connection) 25 | } 26 | }) 27 | }) 28 | } 29 | 30 | const exec = async function(queryContent, params) { 31 | const conn = await getConnection() 32 | // eslint-disable-next-line 33 | return new Promise((resolve, reject) => { 34 | conn.query(queryContent, params, (err, results) => { 35 | if (err) { 36 | conn.release() 37 | reject(err) 38 | } else { 39 | resolve(results) 40 | log.info(`log=lib;model=dbConnection;method=query;info=${queryContent}${params}`) 41 | } 42 | }) 43 | }) 44 | } 45 | 46 | export { exec } 47 | -------------------------------------------------------------------------------- /src/lib/log.js: -------------------------------------------------------------------------------- 1 | import log4js from 'log4js' 2 | import config from '../../config' 3 | const logConfig = config.logConfig 4 | 5 | log4js.configure({ 6 | appenders: { 7 | debug: { 8 | type: logConfig.type, 9 | filename: '/var/log/debug.log', 10 | category: 'debug', 11 | }, info: { 12 | type: logConfig.type, 13 | filename: '/var/log/info.log', 14 | category: 'info', 15 | }, warn: { 16 | type: logConfig.type, 17 | filename: '/var/log/warn.log', 18 | category: 'warn', 19 | }, error: { 20 | type: logConfig.type, 21 | filename: '/var/log/error.log', 22 | category: 'error', 23 | }, fatal: { 24 | type: logConfig.type, 25 | filename: '/var/log/fatal.log', 26 | category: 'fatal', 27 | }, 28 | }, categories: { 29 | default: { 30 | appenders: ['debug'], 31 | level: 'debug', 32 | }, debug: { 33 | appenders: ['debug'], 34 | level: 'debug', 35 | }, info: { 36 | appenders: ['info'], 37 | level: 'info', 38 | }, warn: { 39 | appenders: ['warn'], 40 | level: 'warn', 41 | }, error: { 42 | appenders: ['error'], 43 | level: 'error', 44 | }, fatal: { 45 | appenders: ['fatal'], 46 | level: 'fatal', 47 | }, 48 | }, 49 | }) 50 | export default class { 51 | constructor() { 52 | } 53 | async debug(msg) { 54 | log4js.getLogger('debug').debug(msg) 55 | } 56 | async info(msg) { 57 | log4js.getLogger('info').info(msg) 58 | } 59 | async warn(msg) { 60 | log4js.getLogger('warn').warn(msg) 61 | } 62 | async error(msg) { 63 | log4js.getLogger('error').error(msg) 64 | } 65 | async tatal(msg) { 66 | log4js.getLogger('fatal').fatal(msg) 67 | } 68 | } -------------------------------------------------------------------------------- /src/lib/resFormat.js: -------------------------------------------------------------------------------- 1 | import errorCode from '../../config/errorCode' 2 | import Log from './log' 3 | 4 | export default class ResFormat extends Log { 5 | constructor() { 6 | super() 7 | } 8 | async proces(ctx, type) { 9 | const query = JSON.stringify(ctx.query) 10 | const body = JSON.stringify(ctx.request.body) 11 | const params = JSON.stringify(ctx.params) 12 | 13 | ctx.status = 200 14 | ctx.body = errorCode[type] || ctx.body 15 | this.error(`log=server;type=${type};${ctx.path};${ctx.method};${query};${body};${params}`) 16 | } 17 | } -------------------------------------------------------------------------------- /src/routes/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | import Router from 'koa-router' 4 | import user from './user' 5 | const router = new Router() 6 | 7 | router.use('/user', user.routes(), user.allowedMethods()) 8 | 9 | export default router 10 | -------------------------------------------------------------------------------- /src/routes/user/index.js: -------------------------------------------------------------------------------- 1 | import Router from 'koa-router' 2 | import UserController from './user.controller' 3 | const userController = new UserController() 4 | const router = new Router() 5 | 6 | /** 7 | * @description 获取用户信息 8 | * @param {Number} id 用户的id 9 | * @return {Json} data 用户的信息 10 | */ 11 | router.get('/:id', userController.getUserById) 12 | 13 | /** 14 | * @description 注册一个用户 15 | * @param {String} username 账号名(不超过20个字符) 16 | * @param {String} password 密码(不超过32个字符) 17 | * @return {Json} userId 用户的id 18 | */ 19 | router.post('/', userController.createUser) 20 | 21 | /** 22 | * @description 检测用户的账号密码是否正确 23 | * @param {String} username 账号名(不超过20个字符) 24 | * @param {String} password 密码(不超过32个字符) 25 | * @return {Boolean} success false | true 是否存在 26 | */ 27 | router.post('/login', userController.checkUserPassword) 28 | export default router 29 | 30 | -------------------------------------------------------------------------------- /src/routes/user/user.controller.js: -------------------------------------------------------------------------------- 1 | import User from './user.model' 2 | import userLib from './user.lib.js' 3 | import _ from 'lodash' 4 | 5 | export default class UserController { 6 | constructor() {} 7 | async getUserById(ctx) { 8 | const userId = ctx.params.id 9 | if (isNaN(userId)) { 10 | throw new Error('FORMAT_ERROR') 11 | } 12 | const data = await User.getUserById(userId) 13 | ctx.body = { 14 | code: 200, 15 | data: data, 16 | } 17 | } 18 | 19 | async createUser(ctx) { 20 | const { username, password } = ctx.request.body 21 | if (username.length > 100 || password.length > 32) { 22 | throw new Error('FORMAT_ERROR') 23 | } 24 | // 判断用户名是否已经被使用 25 | // 为了演示,这里就简单处理,常规业务这里有四种种实现方式 26 | // 1. 插入前查询是否存在, 并发无法保证数据一致性 27 | // 2. 使用事务,使用一致性读这个级别,但是这个会降低表的读性能,以为这个级读是排他锁 28 | // 3. 表上的用户名字段设置为唯一索引,但是这个会造成插入的性能,像阿里云的rds已经不支持这个功能 29 | // 4. 使用消息队列 30 | const userInfo = await User.getUserInfoByUsername(username) 31 | if (!_.isEmpty(userInfo)) { 32 | throw new Error('USERNAME_HAS_USED') 33 | } 34 | const newUserInfo = await User.createUser(username, userLib.passwordEncrypt(password)) 35 | ctx.body = { 36 | code: 200, 37 | data: { userId: newUserInfo.insertId }, 38 | } 39 | } 40 | 41 | async checkUserPassword(ctx) { 42 | const { username, password } = ctx.request.body 43 | if (username.length > 100 || password.length > 32) { 44 | throw new Error('FORMAT_ERROR') 45 | } 46 | const usersInfo = await User.getUserInfoByUsername(username) 47 | 48 | if (_.isEmpty(usersInfo)) { 49 | throw new Error('USER_NOT_EXSIT') 50 | } 51 | if (usersInfo[0].password !== userLib.passwordEncrypt(password)) { 52 | throw new Error('WRONG_PASSWORD') 53 | } 54 | 55 | ctx.body = { 56 | code: 200, 57 | data: 'success', 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /src/routes/user/user.lib.js: -------------------------------------------------------------------------------- 1 | import crypto from 'crypto' 2 | 3 | export default class { 4 | constructor() {} 5 | static passwordEncrypt(password) { 6 | const hash = crypto.createHash('md5') 7 | return hash.update(password).digest('hex') 8 | } 9 | } -------------------------------------------------------------------------------- /src/routes/user/user.model.js: -------------------------------------------------------------------------------- 1 | import { exec } from '../../lib/dbConnection' 2 | 3 | export default class { 4 | constructor() { } 5 | static async getUserById(id) { 6 | return await exec('SELECT * FROM user WHERE id =?', [id]) 7 | } 8 | static async createUser(username, password) { 9 | return await exec('INSERT INTO user (name, password) VALUES(?, ?)', [username, password]) 10 | } 11 | static async getUserInfoByUsername(username) { 12 | return await exec('SELECT password FROM user WHERE name = ? limit 1', [username]) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /test/routes/user/user.controller.test.js: -------------------------------------------------------------------------------- 1 | import { assert } from 'chai' 2 | import sinon from 'sinon' 3 | import userModel from '../../../src/routes/user/user.model' 4 | import userLib from '../../../src/routes/user/user.lib' 5 | 6 | let getUserStub = null 7 | let createUserStub = null 8 | let getUserByUsernameStub = null 9 | 10 | before((done) => { 11 | // Stub getUserById 12 | getUserStub = sinon.stub(userModel, 'getUserById') 13 | getUserStub.withArgs(1).returns({ 14 | name: 'bugall', 15 | password: 'bugall-password', 16 | }) 17 | getUserStub.withArgs('string').returns({}) 18 | 19 | // Stub createUser 20 | createUserStub = sinon.stub(userModel, 'createUser') 21 | createUserStub.withArgs('bugall-two', userLib.passwordEncrypt('bugall-two-password')).returns({ "insertId": 1 }) 22 | createUserStub.withArgs('bugall', userLib.passwordEncrypt('password-password')).returns({}) 23 | 24 | // Stub getUserInfoByUsername 25 | getUserByUsernameStub = sinon.stub(userModel, 'getUserInfoByUsername') 26 | getUserByUsernameStub.withArgs('bugall').returns([{ id: 1, name: 'bugall', password: 'bugall-password' }]) 27 | getUserByUsernameStub.withArgs('bugall-two').returns([]) 28 | done() 29 | }) 30 | 31 | describe('Get user by id', () => { 32 | const obj = { 33 | say: function(name) { 34 | console.log(name) 35 | } 36 | } 37 | obj.say('hello') 38 | const UserController = require('../../../src/routes/user/user.controller').default 39 | const userController = new UserController() 40 | 41 | it('Shoud not success when id not a numeic type', async () => { 42 | const ctx = { params: { id: 'string' }, body: {} } 43 | let errorMsg = null 44 | try { 45 | await userController.getUserById(ctx) 46 | } catch (e) { 47 | errorMsg = e.message 48 | } 49 | assert.equal(errorMsg, 'FORMAT_ERROR') 50 | }) 51 | it('Shoud success when id is a numeic type', async () => { 52 | const ctx = { params: { id: 1 }, body: {} } 53 | await userController.getUserById(ctx) 54 | assert.equal(ctx.body.code, 200) 55 | }) 56 | }) 57 | 58 | describe('Create user', () => { 59 | const UserController = require('../../../src/routes/user/user.controller').default 60 | const userController = new UserController() 61 | 62 | it('Shoud success when username not exist', async () => { 63 | const ctx = { request: { body: { username: 'bugall-two', password: 'bugall-two-password' } } } 64 | await userController.createUser(ctx) 65 | assert.equal(ctx.body.code, 200) 66 | }) 67 | it('Shoud not success when username has exist', async () => { 68 | const ctx = { request: { body: { username: 'bugall', password: 'bugall-password' } } } 69 | let errorMsg = null 70 | try { 71 | await userController.createUser(ctx) 72 | } catch (e) { 73 | errorMsg = e.message 74 | } 75 | assert.equal(errorMsg, 'USERNAME_HAS_USED') 76 | }) 77 | }) 78 | 79 | after((done) => { 80 | createUserStub.restore() 81 | getUserStub.restore() 82 | getUserByUsernameStub.restore() 83 | done() 84 | }) 85 | -------------------------------------------------------------------------------- /test/routes/user/user.lib.test.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bugall/node-backend-scaffolding/d7377b179afdd526f9f93491f98e0c723209e500/test/routes/user/user.lib.test.js -------------------------------------------------------------------------------- /test/routes/user/user.model.test.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bugall/node-backend-scaffolding/d7377b179afdd526f9f93491f98e0c723209e500/test/routes/user/user.model.test.js -------------------------------------------------------------------------------- /test/routes/user/user.test.js: -------------------------------------------------------------------------------- 1 | describe('User Lib', () => { 2 | require('./user.controller.test') 3 | }) 4 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | process.env.NODE_ENV = process.env.NODE_ENV || 'development' 3 | 4 | before(function(done) { 5 | done() 6 | }) 7 | 8 | describe('Routes Test', function() { 9 | require('./routes/user/user.test') 10 | }) 11 | 12 | after(function(done) { 13 | done() 14 | }) 15 | --------------------------------------------------------------------------------