├── .gitignore
├── .snyk
├── LICENSE
├── README.md
├── __tests__
├── api
│ └── rest
│ │ └── users.router.spec.ts
└── common
│ └── response.common.spec.ts
├── environments
└── development.env
├── jest.config.js
├── nginx.conf
├── package-lock.json
├── package.json
├── pm2-server.json
├── reflect-metadata
├── src
├── api
│ ├── index.ts
│ └── rest
│ │ ├── handlers
│ │ ├── index.ts
│ │ ├── orders.handler.ts
│ │ └── users.handler.ts
│ │ ├── index.ts
│ │ ├── middleware
│ │ ├── auth.middleware.ts
│ │ └── index.ts
│ │ └── routes
│ │ ├── orders.routes.ts
│ │ └── users.routes.ts
├── common
│ ├── decarators.ts.practice
│ ├── enums
│ │ ├── event-dispatcher-names.enum.ts
│ │ ├── index.ts
│ │ └── router-methods.enum.ts
│ ├── index.ts
│ ├── response.common.ts
│ └── utilities.common.ts
├── config
│ ├── index.ts
│ └── response.ts
├── core
│ ├── custom-router.ts
│ ├── index.ts
│ └── jwt.provider.ts
├── loaders
│ ├── dependencyInjector.ts
│ ├── express.loader.ts
│ ├── index.ts
│ ├── loggers.loader.ts
│ └── mongoose.loader.ts
├── models
│ ├── index.ts
│ ├── orders.model.ts
│ └── users.model.ts
├── server.ts
├── services
│ ├── index.ts
│ ├── orders.service.ts
│ └── users.service.ts
├── subscribers
│ ├── orders-event.subscriber.ts
│ └── users.events-subscriber.ts
└── types
│ ├── IRouterParams.ts
│ ├── IUser.ts
│ └── index.ts
├── tsconfig.json
└── webpack.config.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | ### Node template
3 | # Logs
4 | logs
5 | *.log
6 | npm-debug.log*
7 | yarn-debug.log*
8 | yarn-error.log*
9 | lerna-debug.log*
10 |
11 | # Diagnostic reports (https://nodejs.org/api/report.html)
12 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
13 |
14 | # Runtime data
15 | pids
16 | *.pid
17 | *.seed
18 | *.pid.lock
19 |
20 | # Directory for instrumented libs generated by jscoverage/JSCover
21 | lib-cov
22 |
23 | # Coverage directory used by tools like istanbul
24 | coverage
25 | *.lcov
26 |
27 | # nyc test coverage
28 | .nyc_output
29 |
30 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
31 | .grunt
32 |
33 | # Bower dependency directory (https://bower.io/)
34 | bower_components
35 |
36 | # node-waf configuration
37 | .lock-wscript
38 |
39 | # Compiled binary addons (https://nodejs.org/api/addons.html)
40 | build/Release
41 |
42 | # Dependency directories
43 | node_modules/
44 | jspm_packages/
45 |
46 | # TypeScript v1 declaration files
47 | typings/
48 |
49 | # TypeScript cache
50 | *.tsbuildinfo
51 |
52 | # Optional npm cache directory
53 | .npm
54 |
55 | # Optional eslint cache
56 | .eslintcache
57 |
58 | # Microbundle cache
59 | .rpt2_cache/
60 | .rts2_cache_cjs/
61 | .rts2_cache_es/
62 | .rts2_cache_umd/
63 |
64 | # Optional REPL history
65 | .node_repl_history
66 |
67 | # Output of 'npm pack'
68 | *.tgz
69 |
70 | # Yarn Integrity file
71 | .yarn-integrity
72 |
73 | # dotenv environment variables file
74 | .env
75 | .env.test
76 |
77 | # parcel-bundler cache (https://parceljs.org/)
78 | .cache
79 |
80 | # Next.js build output
81 | .next
82 |
83 | # Nuxt.js build / generate output
84 | .nuxt
85 | dist
86 |
87 | # Gatsby files
88 | .cache/
89 | # Comment in the public line in if your project uses Gatsby and *not* Next.js
90 | # https://nextjs.org/blog/next-9-1#public-directory-support
91 | # public
92 |
93 | # vuepress build output
94 | .vuepress/dist
95 |
96 | # Serverless directories
97 | .serverless/
98 |
99 | # FuseBox cache
100 | .fusebox/
101 |
102 | # DynamoDB Local files
103 | .dynamodb/
104 |
105 | # TernJS port file
106 | .tern-port
107 |
108 | .idea/
109 | git4idea/
110 | !/src/common/decarators.ts.practice
111 |
--------------------------------------------------------------------------------
/.snyk:
--------------------------------------------------------------------------------
1 | # Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities.
2 | version: v1.13.5
3 | ignore: {}
4 | patch: {}
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Node JS Starter kit in SOLID Architecture.
2 |
3 | # Introduction
4 |
5 | This is the starter kit project for node js with `typescript`
6 | programming. This project is with `express js` and `mongoose` frameworks to
7 | build a Rest APIs. This project structure also support with multiple API
8 | protocalls also we build the project with unit testing for end points and
9 | logic codes by `supertest` and `jest`.
10 |
11 | This project also example for best practice node js application
12 |
13 | ## Project structure explanations:
14 |
15 | 1. api - Write api codes like rest, graphql, socket
16 | 2. common - Write common functions to be usable for all the modules
17 | 3. config - Write App config code
18 | 4. code - Write Application core level code like engine of your
19 | your project, service providers
20 | 5. models - Wirte database collection models
21 | 6. loaders - Write your application modueles and load dependcy of app
22 | 7. services - Write application logics
23 | 8. subscribers - Write Event subscriber code
24 | 9. types - Write application types like interfaces, absracts
25 | 10. __test__ - Write jest unit testing code.
26 |
27 | # Core Concepts of this application.
28 |
29 | Node Js is run time environment for javascript which built on
30 | V8 Javascript engine. Its Single thread non blocking IO programming
31 | environment and its intepreted language. Which uses the javascript to
32 | run a servers. javascript is dynamic programming language. There is no
33 | type defention and less OOPS features for its programming. So Choosing
34 | Typescript for developing node js application which will increase the
35 | productivity and easy to write reusable code.
36 |
37 | This application is mainly design for develop a secured, low latency
38 | swagger friendly (not yet implemented for swagger) and strong implementation.
39 |
40 | We everyone know javascript is a single thread application. So Writing
41 | perfomable app is very difficult compare than the other multi thread
42 | programming. However its offer a non blocking IO So we can able to
43 | delivering resources to endpoints is make fast as possible as per writing
44 | javascript asynchronus coding styles and event emiters. So Here we are using
45 | async and Event dispatchers.
46 |
47 | Case Study:
48 | We are writing api for user registration. In this endpoint logic
49 | we are writting the code for user registration if the user data
50 | valid the we will send confimation email and return responses.
51 | Here we can write send the email confirmation in event emmiter when
52 | the user data valid then write the api to return response and emit the
53 | user data to send the email confirmation in background.
54 |
55 | > We can write the async packages to handle the complex asynchronus calls parallely and series
56 |
57 | To reduce the latency of an endpoints response we are not added the
58 | common middleware like body parser. which added in particularly api calls
59 | only. So other API calls can make faster.
60 |
61 | Write Test driven development Its an common approach from most of the
62 | developers. Writing an unit testing for project it will make you more confident
63 | to deployment and do not allow your code run in production if it not tested.
64 | Here we are using jest and supertest for endpoints. Use seperate db for unit
65 | testing environment.
66 |
67 | We are added the pm2 server cofiguration here to run this application in
68 | cluster mode to speed up the api calls. We are setting the environmetn varibales
69 | for only in development and testing not added for production. Which added in pm2 server
70 | So it give an extra layer security for an app. include the pm2-server
71 | file in your cloud instance itself. here we added for example.
72 |
73 | Use HTTPS/SSL for security, We added helmet and cors setup for improving the
74 | security purpose. Adding the secure level module in the middleware only never
75 | going to be make your application more secure its about how you are writing also
76 | to be consider. use csurf for prevent the CSRF attack.
77 |
78 | Case Study:
79 | I have seen one web application there they written one api call for the
80 | loginned User details by passing id in http query. Even that id is in number format
81 | as 1001 when we changed the 1001 to 1002 it gave the details of another uses
82 | details. They can get the another user deta. Its became a CSRF loophole. They can get
83 | the data by any otherways like JWT token or Auth token. So Writing the code is need
84 | to be secured manner. Poor way of coding become a loophole.
85 |
86 | Don't make user ids in readable formats. its will helpful to enumrate the other user. Study more
87 | about security improvement in [OWSAP](https://www.owasp.org/index.php/Web_Application_Security_Testing_Cheat_Sheet.)
88 |
89 | Use Rate Limitter for avoid DDoS , brute force attack and dictionary attack on form datas like signin, OTP cracking.
90 | We are already using the Helmet it will prevent some browser level attack.
91 |
92 | To imporve the low latency of IO calls we are using the Event emitters, async calls for
93 | parallel and series asynchronus process.
94 |
95 |
96 |
97 | This project is refered from the following blog and some documents.
98 | [Reference](https://dev.to/santypk4/bulletproof-node-js-project-architecture-4epf)
99 |
100 | > Note : This project still in construction mode
101 |
102 |
103 |
--------------------------------------------------------------------------------
/__tests__/api/rest/users.router.spec.ts:
--------------------------------------------------------------------------------
1 | import * as request from "supertest";
2 | import express from "express";
3 |
4 | import config from '../../../src/config';
5 | import loaders from "../../../src/loaders";
6 |
7 |
8 | describe('Get users API', () => {
9 |
10 | let loadedModules: any;
11 | beforeAll(async ()=>{
12 | const app = express();
13 | loadedModules = await loaders({ expressApp: app});
14 | });
15 |
16 | it('Should response code 200', async () => {
17 |
18 | const response = await request.agent(loadedModules.app)
19 | .get(config.api.prefix + '/users');
20 | expect(response.status).toBe(200);
21 |
22 | });
23 |
24 | });
25 |
--------------------------------------------------------------------------------
/__tests__/common/response.common.spec.ts:
--------------------------------------------------------------------------------
1 | import {formatErrorMessage, formatSuccessMessage} from "../../src/common";
2 |
3 | describe('Rest API Success Response output', () => {
4 |
5 | it('should create a success response', async () => {
6 |
7 | const input = formatSuccessMessage({
8 | msg: 'Success',
9 | data: {},
10 | sessionToken: 'xyz',
11 | sessionValidity: 1
12 | });
13 |
14 | const output = {
15 | status: {
16 | code: 200,
17 | message: 'Success',
18 | },
19 | data: {},
20 | session: {
21 | token: 'xyz',
22 | validity: 1,
23 | message: 'Session is valid'
24 | }
25 | };
26 |
27 | expect(input).toStrictEqual(output)
28 | });
29 |
30 | it('should create a success response with status code 202', async () => {
31 |
32 | const input = formatSuccessMessage({
33 | msg: 'Success',
34 | data: {},
35 | sessionToken: 'xyz',
36 | sessionValidity: 1,
37 | statusCode: 202
38 | });
39 |
40 | expect(input.status.code).toBe(202)
41 | });
42 |
43 | });
44 |
45 | describe('Rest API Failure Response output', () => {
46 |
47 | it('should create a failure response', async () => {
48 |
49 | const input = formatErrorMessage({
50 | msg: 'Session is invalid',
51 | });
52 |
53 | const output = {
54 | status: {
55 | code: 400,
56 | message: 'Session is invalid',
57 | },
58 | data: {},
59 | session: {
60 | token: null,
61 | validity: 0,
62 | message: null
63 | }
64 | };
65 |
66 | expect(input).toStrictEqual(output)
67 |
68 | });
69 |
70 | it('should create a failure response with status code 403', async () => {
71 |
72 | const input = formatErrorMessage({
73 | msg: 'Session is invalid',
74 | code: 403
75 | });
76 |
77 | expect(input.status.code).toBe(403)
78 |
79 | });
80 |
81 | });
82 |
--------------------------------------------------------------------------------
/environments/development.env:
--------------------------------------------------------------------------------
1 | # JSON web token (JWT) secret: this keeps our app's user authentication secure
2 | # This secret should be a random 20-ish character string
3 | JWT_SECRET ='JtSctSudESrN'
4 |
5 | # Mongo DB
6 | # Local development
7 | MONGODB_URI='mongodb://127.0.0.1:27017/all'
8 |
9 | DB_USER='allDev'
10 | DB_PASSWORD='allDev@api'
11 |
12 | # Port
13 | PORT=4000
14 |
15 | # Debug
16 | LOG_LEVEL='debug'
17 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | // For a detailed explanation regarding each configuration property, visit:
2 | // https://jestjs.io/docs/en/configuration.html
3 |
4 | module.exports = {
5 | // All imported modules in your tests should be mocked automatically
6 | // automock: false,
7 |
8 | // Stop running tests after the first failure
9 | // bail: false,
10 |
11 | // Respect "browser" field in package.json when resolving modules
12 | // browser: false,
13 |
14 | // The directory where Jest should store its cached dependency information
15 | // cacheDirectory: "/var/folders/bw/vvybgj3d3kgb98nzjxfmpv5c0000gn/T/jest_dx",
16 |
17 | // Automatically clear mock calls and instances between every test
18 | // clearMocks: false,
19 |
20 | // Indicates whether the coverage information should be collected while executing the test
21 | // collectCoverage: false,
22 |
23 | // An array of glob patterns indicating a set of files for which coverage information should be collected
24 | // collectCoverageFrom: null,
25 |
26 | // The directory where Jest should output its coverage files
27 | // coverageDirectory: null,
28 |
29 | // An array of regexp pattern strings used to skip coverage collection
30 | coveragePathIgnorePatterns: [
31 | "/node_modules/"
32 | ],
33 |
34 | // A list of reporter names that Jest uses when writing coverage reports
35 | // coverageReporters: [
36 | // "json",
37 | // "text",
38 | // "lcov",
39 | // "clover"
40 | // ],
41 |
42 | // An object that configures minimum threshold enforcement for coverage results
43 | // coverageThreshold: null,
44 |
45 | // Make calling deprecated APIs throw helpful error messages
46 | // errorOnDeprecated: false,
47 |
48 | // Force coverage collection from ignored files usin a array of glob patterns
49 | // forceCoverageMatch: [],
50 |
51 | // A path to a module which exports an async function that is triggered once before all test suites
52 | // globalSetup: null,
53 |
54 | // A path to a module which exports an async function that is triggered once after all test suites
55 | // globalTeardown: null,
56 |
57 | // A set of global variables that need to be available in all test environments
58 | "globals": {
59 | "ts-jest": {
60 | "tsConfigFile": "tsconfig.json"
61 | }
62 | },
63 |
64 | // An array of directory names to be searched recursively up from the requiring module's location
65 | // moduleDirectories: [
66 | // "node_modules"
67 | // ],
68 |
69 | // An array of file extensions your modules use
70 | moduleFileExtensions: [
71 | 'js',
72 | 'ts',
73 | 'json'
74 | ],
75 |
76 | // A map from regular expressions to module names that allow to stub out resources with a single module
77 | // moduleNameMapper: {},
78 |
79 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
80 | // modulePathIgnorePatterns: [],
81 |
82 | // Activates notifications for test results
83 | // notify: false,
84 |
85 | // An enum that specifies notification mode. Requires { notify: true }
86 | // notifyMode: "always",
87 |
88 | // A preset that is used as a base for Jest's configuration
89 | preset: 'ts-jest',
90 |
91 | // Run tests from one or more projects
92 | // projects: null,
93 |
94 | // Use this configuration option to add custom reporters to Jest
95 | // reporters: undefined,
96 |
97 | // Automatically reset mock state between every test
98 | // resetMocks: false,
99 |
100 | // Reset the module registry before running each individual test
101 | // resetModules: false,
102 |
103 | // A path to a custom resolver
104 | // resolver: null,
105 |
106 | // Automatically restore mock state between every test
107 | // restoreMocks: false,
108 |
109 | // The root directory that Jest should scan for tests and modules within
110 | // rootDir: null,
111 |
112 | // A list of paths to directories that Jest should use to search for files in
113 | // roots: [
114 | // ""
115 | // ],
116 |
117 | // Allows you to use a custom runner instead of Jest's default test runner
118 | // runner: "jest-runner",
119 |
120 | // The paths to modules that run some code to configure or set up the testing environment before each test
121 | // setupFiles: [],
122 |
123 | // The path to a module that runs some code to configure or set up the testing framework before each test
124 | // setupTestFrameworkScriptFile: './tests/setup.js',
125 |
126 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing
127 | // snapshotSerializers: [],
128 |
129 | // The test environment that will be used for testing
130 | testEnvironment: 'node',
131 |
132 | // Options that will be passed to the testEnvironment
133 | // testEnvironmentOptions: {},
134 |
135 | // Adds a location field to test results
136 | // testLocationInResults: false,
137 |
138 | // The glob patterns Jest uses to detect test files
139 | testMatch: [
140 | // '**/?(*.)+(spec|test).js?(x)',
141 | '**/?(*.)+(spec|test).ts?(x)',
142 | ],
143 |
144 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
145 | // testPathIgnorePatterns: [
146 | // "/node_modules/"
147 | // ],
148 |
149 | // The regexp pattern Jest uses to detect test files
150 | // testRegex: "",
151 |
152 | // This option allows the use of a custom results processor
153 | // testResultsProcessor: null,
154 |
155 | // This option allows use of a custom test runner
156 | // testRunner: "jasmine2",
157 |
158 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
159 | // testURL: "http://localhost",
160 |
161 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
162 | // timers: "real",
163 |
164 | // A map from regular expressions to paths to transformers
165 | transform: {
166 | '^.+\\.ts?$': 'ts-jest',
167 | },
168 |
169 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
170 | // transformIgnorePatterns: [
171 | // "/node_modules/"
172 | // ],
173 |
174 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
175 | // unmockedModulePathPatterns: undefined,
176 |
177 | // Indicates whether each individual test should be reported during the run
178 | verbose: true,
179 |
180 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
181 | // watchPathIgnorePatterns: [],
182 |
183 | // Whether to use watchman for file crawling
184 | // watchman: true,
185 | };
186 |
--------------------------------------------------------------------------------
/nginx.conf:
--------------------------------------------------------------------------------
1 | ##
2 | # You should look at the following URL's in order to grasp a solid understanding
3 | # of Nginx configuration files in order to fully unleash the power of Nginx.
4 | # http://wiki.nginx.org/Pitfalls
5 | # http://wiki.nginx.org/QuickStart
6 | # http://wiki.nginx.org/Configuration
7 | #
8 | # Generally, you will want to move this file somewhere, and start with a clean
9 | # file but keep this around for reference. Or just disable in sites-enabled.
10 | #
11 | # Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
12 | ##
13 |
14 | # Default server configuration
15 | #
16 | server {
17 |
18 | listen 80 default_server;
19 | listen [::]:80 default_server;
20 |
21 | # SSL configuration
22 | #
23 | listen 443 ssl default_server;
24 | listen [::]:443 ssl default_server;
25 |
26 | ssl_certificate /etc/ssl/certs/localhost.crt;
27 | ssl_certificate_key /etc/ssl/private/localhost.key;
28 |
29 | ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
30 | #
31 | # Note: You should disable gzip for SSL traffic.
32 | # See: https://bugs.debian.org/773332
33 | #
34 | # Read up on ssl_ciphers to ensure a secure configuration.
35 | # See: https://bugs.debian.org/765782
36 | #
37 | # Self signed certs generated by the ssl-cert package
38 | # Don't use them in a production server!
39 | #
40 | # include snippets/snakeoil.conf;
41 |
42 | root /var/www/html;
43 |
44 | # Add index.php to the list if you are using PHP
45 | index index.html index.htm index.nginx-debian.html;
46 |
47 | server_name _;
48 |
49 | # location / {
50 | # First attempt to serve request as file, then
51 | # as directory, then fall back to displaying a 404.
52 | # try_files $uri $uri/ /index.html =404;
53 | # }
54 |
55 | # location /api/ {
56 | # proxy_pass http://dev.coreservices.prorank.ai/coreservices.dev/api/v1.0/;
57 | # }
58 |
59 |
60 | location / {
61 | proxy_http_version 1.1;
62 | proxy_set_header Connection 'upgrade';
63 | proxy_set_header X-Real-IP $remote_addr;
64 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
65 | proxy_set_header X-NginX-Proxy true;
66 | proxy_set_header X-Forwarded-Proto https;
67 | proxy_pass http://nodes;
68 | proxy_ssl_session_reuse off;
69 | proxy_set_header Host $http_host;
70 | proxy_cache_bypass $http_upgrade;
71 | proxy_redirect off;
72 | }
73 |
74 |
75 | location /socket.io {
76 | include proxy_params;
77 | proxy_http_version 1.1;
78 | proxy_buffering off;
79 | proxy_set_header Upgrade $http_upgrade;
80 | proxy_set_header Connection "Upgrade";
81 | proxy_pass http://nodes/socket.io;
82 | }
83 |
84 |
85 |
86 | # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
87 | #
88 | #location ~ \.php$ {
89 | # include snippets/fastcgi-php.conf;
90 | #
91 | # # With php7.0-cgi alone:
92 | # fastcgi_pass 127.0.0.1:9000;
93 | # # With php7.0-fpm:
94 | # fastcgi_pass unix:/run/php/php7.0-fpm.sock;
95 | #}
96 |
97 | # deny access to .htaccess files, if Apache's document root
98 | # concurs with nginx's one
99 | #
100 | #location ~ /\.ht {
101 | # deny all;
102 | #}
103 | }
104 |
105 | upstream nodes {
106 | # enable sticky session based on IP
107 | ip_hash;
108 |
109 | server localhost:3000;
110 | server localhost:3001;
111 | server localhost:3002;
112 | server localhost:3003;
113 | }
114 |
115 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "nodejs-starter-kit",
3 | "version": "1.0.0",
4 | "description": "My node js starter kit project",
5 | "private": true,
6 | "scripts": {
7 | "start": "NODE_ENV=development ts-node ./src/server.ts",
8 | "build": "webpack && cp -r environments dist",
9 | "dev": "NODE_ENV=development npm run build && node ./dist/main.js",
10 | "prod": "webpack && pm2 start pm2-server.json",
11 | "test": "NODE_ENV=development jest --testTimeout=10000 ",
12 | "test:coverage": "jest --coverage",
13 | "snyk:test": "snyk test"
14 | },
15 | "author": "Team Shadow Hijackers",
16 | "license": "ISC",
17 | "dependencies": {
18 | "@types/bcrypt": "^3.0.0",
19 | "@types/connect-mongodb-session": "0.0.2",
20 | "@types/cookie-parser": "^1.4.2",
21 | "@types/express-session": "^1.17.0",
22 | "@types/jsonwebtoken": "^8.3.9",
23 | "app-root-path": "^3.0.0",
24 | "async": "^3.2.0",
25 | "bcrypt": "^5.0.0",
26 | "body-parser": "^1.19.0",
27 | "connect-mongodb-session": "^2.3.1",
28 | "cookie-parser": "^1.4.5",
29 | "dotenv": "^8.2.0",
30 | "dotenv-webpack": "^1.7.0",
31 | "event-dispatch": "^0.4.1",
32 | "express": "^4.17.1",
33 | "express-session": "^1.17.1",
34 | "helmet": "^3.21.3",
35 | "jsonwebtoken": "^8.5.1",
36 | "lodash": "^4.17.15",
37 | "mongoose": "^5.8.11",
38 | "morgan": "^1.9.1",
39 | "nodemon": "^2.0.2",
40 | "reflect-metadata": "^0.1.13",
41 | "request": "^2.79.0",
42 | "socket.io": "^2.3.0",
43 | "ts-jest": "^25.2.1",
44 | "ts-node": "^8.6.2",
45 | "typedi": "^0.8.0",
46 | "winston": "^3.2.1"
47 | },
48 | "devDependencies": {
49 | "@types/app-root-path": "^1.2.4",
50 | "@types/async": "^3.0.8",
51 | "@types/express": "^4.17.2",
52 | "@types/helmet": "0.0.45",
53 | "@types/jest": "^25.1.4",
54 | "@types/mongoose": "^5.7.0",
55 | "@types/morgan": "^1.7.37",
56 | "@types/node": "^13.7.0",
57 | "@types/socket.io": "^2.1.4",
58 | "@types/supertest": "^2.0.8",
59 | "@webpack-cli/init": "^0.3.0",
60 | "babel-minify-webpack-plugin": "^0.3.1",
61 | "babel-plugin-syntax-dynamic-import": "^6.18.0",
62 | "file-loader": "^5.0.2",
63 | "jest": "^25.1.0",
64 | "module": "^1.2.5",
65 | "node-loader": "^0.6.0",
66 | "require_optional": "^1.0.1",
67 | "snyk": "^1.301.0",
68 | "supertest": "^4.0.2",
69 | "terser-webpack-plugin": "^2.3.4",
70 | "ts-loader": "^6.2.1",
71 | "typescript": "^3.7.5",
72 | "uglifyjs-webpack-plugin": "^2.2.0",
73 | "webpack": "^4.41.6",
74 | "webpack-cli": "^4.0.0-beta.2",
75 | "workbox-webpack-plugin": "^5.0.0"
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/pm2-server.json:
--------------------------------------------------------------------------------
1 | {
2 | "apps": [
3 | {
4 | "name": "nodejs-starter-kit",
5 | "instances": "max",
6 | "exec_mode": "cluster",
7 | "script": "./dist/main.js",
8 | "node_args": "--max_old_space_size=8192",
9 | "args": [
10 | "env=production"
11 | ],
12 | "env": {
13 | "NODE_ENV": "production",
14 | "JWT_SECRET": "",
15 | "MONGODB_URI": "mongodb://127.0.0.1:27017/all",
16 | "DB_USER": "allDev",
17 | "DB_PASSWORD": "allDev@api",
18 | "PORT": 4000,
19 | "LOG_LEVEL": "debug"
20 | }
21 | }
22 | ]
23 | }
24 |
--------------------------------------------------------------------------------
/src/api/index.ts:
--------------------------------------------------------------------------------
1 | import express from "express";
2 |
3 | import restAPIs from './rest';
4 |
5 | export default {
6 | loadRestEndPoints: (expressInstance: express.Application)=>{
7 | restAPIs(expressInstance)
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/api/rest/handlers/index.ts:
--------------------------------------------------------------------------------
1 | export * from './users.handler';
2 |
3 |
--------------------------------------------------------------------------------
/src/api/rest/handlers/orders.handler.ts:
--------------------------------------------------------------------------------
1 | import {Service} from "typedi";
2 | import {Request, Response} from "express";
3 |
4 | import {OrdersService} from "../../../services/orders.service";
5 | import * as common from "../../../common";
6 |
7 | @Service()
8 | export class OrdersHandler {
9 |
10 | constructor(
11 | private ordersService: OrdersService,
12 | ) {
13 | }
14 |
15 | getOrdersAPIHandler() {
16 | return async (req: Request, res: Response) => {
17 | if (req.query.orders_date) {
18 |
19 | const userId = req.body.authData.userId;
20 | const options = {userId: userId, ordersDate: req.query.orders_date};
21 | const role = req.body.authData.role;
22 | const result = await this.ordersService.getOrders(options, role);
23 |
24 | if (result.error) {
25 | res.status(400).send(result);
26 | return
27 | }
28 | const response = common.formatSuccessMessage({
29 | msg: 'Success',
30 | data: result,
31 | sessionToken: req?.headers.authorization
32 | });
33 | res.status(200).send(response);
34 | return
35 | }
36 |
37 | res.status(400).send({error: 'Send neccessary params'})
38 | }
39 | }
40 |
41 | saveOrderAPIHandler() {
42 |
43 | return async (req: Request, res: Response) => {
44 |
45 | req.body.userId = req.body.authData.userId;
46 | delete req.body.authData;
47 | const result = await this.ordersService.postOrders(req.body);
48 |
49 | if (result.error) {
50 | res.status(400).send(result);
51 | return
52 | }
53 |
54 | const response = common.formatSuccessMessage({
55 | msg: 'Success',
56 | data: result,
57 | sessionToken: req?.headers?.authorization
58 | });
59 | res.status(200).send(response);
60 | }
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/src/api/rest/handlers/users.handler.ts:
--------------------------------------------------------------------------------
1 | import {Service} from "typedi";
2 | import {NextFunction, Request, Response} from "express";
3 |
4 | import {UsersService} from "../../../services";
5 | import * as common from "../../../common";
6 | import session from "express-session";
7 | import {JwtProvider} from "../../../core/jwt.provider";
8 |
9 | @Service()
10 | export class UsersHandler {
11 |
12 | constructor(
13 | private usersService: UsersService
14 | ) {
15 | }
16 |
17 | getUsersAPIHandler() {
18 | return async (req: Request, res: Response) => {
19 | debugger
20 | const users = await this.usersService.getUsers();
21 | const response = common.formatSuccessMessage({
22 | msg: 'Success',
23 | data: users,
24 | sessionToken: 'Auth Token'
25 | });
26 |
27 | res.status(200).send(response);
28 |
29 | }
30 | }
31 |
32 | signUpAPIHandler() {
33 | return async (req: Request, res: Response) => {
34 | const payload = req.body;
35 | try {
36 | if (payload) {
37 |
38 | const result: any = await this.usersService.registerUser(payload);
39 |
40 | if (!result.error) {
41 | res.status(202).send(result);
42 | return
43 | }
44 |
45 | const token: string = JwtProvider.generateToken(result._doc._id.toString(), result._doc.role.toString());
46 | const response = common.formatSuccessMessage({
47 | msg: 'Success',
48 | data: JSON.parse(JSON.stringify(result._doc)),
49 | sessionToken: token
50 | });
51 |
52 |
53 | response.status.code = 400;
54 | response.status.message = result?.message;
55 |
56 | res.status(200).send(response);
57 |
58 | }
59 | } catch (e) {
60 | console.log('Exception', e);
61 | const errorResponse = common.formatErrorMessage({msg: 'Something happend in the server', code: 500});
62 | res.status(400).send(errorResponse);
63 | }
64 |
65 | }
66 | }
67 |
68 | signInAPIHandler() {
69 | return async (req: Request, res: Response) => {
70 | const result = await this.usersService.login(req.body);
71 | if(result.error){
72 | res.status(400).send({error: result.error});
73 | return
74 | }
75 |
76 | const token = JwtProvider.generateToken(result._id, result.role);
77 | const response = common.formatSuccessMessage({
78 | msg: 'Success',
79 | data: result,
80 | sessionToken: token
81 | });
82 |
83 | const sess: any = req.session;
84 | sess.userId = result._id;
85 |
86 | res.status(201).send(response);
87 | }
88 | }
89 |
90 | forgetPasswordAPIHandler() {
91 | return async (req: Request, res: Response) => {
92 | res.status(200).send(await this.usersService.getUsers());
93 | }
94 | }
95 |
96 | resetPasswordAPIHandler() {
97 | return async (req: Request, res: Response) => {
98 | res.status(200).send(await this.usersService.getUsers());
99 | }
100 | }
101 |
102 | logoutAPIHandler() {
103 | return async (req: Request, res: Response, next: NextFunction)=> {
104 | if (req.session) {
105 | // delete session object
106 | const sessionId = req.session.userId;
107 | const self = this;
108 | req.session.destroy(function (err) {
109 | if (err) {
110 | return res.status(400).send({error: 'Something went wrong', message: 'Could not able to logout'});
111 | } else {
112 | self.usersService.logout(sessionId);
113 | return res.status(200).send({error: '', message: 'Success'});
114 | }
115 | });
116 | }
117 | }
118 | }
119 |
120 | }
121 |
--------------------------------------------------------------------------------
/src/api/rest/index.ts:
--------------------------------------------------------------------------------
1 | import express, {Request, Response} from 'express';
2 | import {UsersRoutes} from "./routes/users.routes";
3 | import config from '../../config';
4 | import {OrdersRoutes} from "./routes/orders.routes";
5 |
6 | export default ( app: express.Application )=> {
7 |
8 | app.get('/', async (req: Request, res: Response)=>{
9 | res.status(200).send(` APP IS RUNNING
`)
10 | });
11 | app.use(config.api.prefix + '/users', UsersRoutes.getUserRoutes());
12 | app.use(config.api.prefix + '/orders', OrdersRoutes.getOrdersRoutes());
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/api/rest/middleware/auth.middleware.ts:
--------------------------------------------------------------------------------
1 | import {NextFunction, Request, Response} from "express";
2 | import {JwtProvider} from "../../../core/jwt.provider";
3 |
4 | export async function authMiddleware(req: Request, res: Response, next: NextFunction) {
5 |
6 | const authToken = req.headers['authorization'];
7 | const decoded: any = JwtProvider.verifyToken(authToken as string);
8 | req.body.authData = decoded;
9 | if (decoded && decoded.exp > new Date().getTime()/1000 ) {
10 | return next();
11 | } else {
12 | res.status(401).send({error: 'You must be logged in to view this page.'});
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/api/rest/middleware/index.ts:
--------------------------------------------------------------------------------
1 | export * from './auth.middleware';
2 |
--------------------------------------------------------------------------------
/src/api/rest/routes/orders.routes.ts:
--------------------------------------------------------------------------------
1 | import container, {Service} from "typedi";
2 |
3 | import {CustomRouter} from "../../../core";
4 | import {OrdersService} from "../../../services/orders.service";
5 | import {OrdersHandler} from "../handlers/orders.handler";
6 | import {RouterMethodsEnum} from "../../../common/enums";
7 | import {authMiddleware} from "../middleware";
8 | import bodyParser from "body-parser";
9 |
10 | @Service()
11 | export class OrdersRoutes {
12 |
13 | constructor(
14 | private orderService: OrdersService,
15 | private customRouter: CustomRouter,
16 | private ordersHandler: OrdersHandler
17 | ) {
18 | this.customRouter.init('orders')
19 | }
20 |
21 | setUserRoutes() {
22 | this.saveOrder();
23 | this.getOrders();
24 | return this.customRouter.exportRouterInstance();
25 | }
26 |
27 |
28 | getOrders() {
29 |
30 | this.customRouter.setRoute({
31 | path: '/',
32 | method: RouterMethodsEnum.get,
33 | handler: this.ordersHandler.getOrdersAPIHandler(),
34 | middleware: [
35 | authMiddleware
36 | ],
37 | description: 'Get orders api'
38 | });
39 |
40 | }
41 |
42 | saveOrder() {
43 |
44 | this.customRouter.setRoute({
45 | path: '/',
46 | method: RouterMethodsEnum.post,
47 | handler: this.ordersHandler.saveOrderAPIHandler(),
48 | middleware: [
49 | bodyParser.json(),
50 | bodyParser.urlencoded({extended: true}),
51 | authMiddleware,
52 | ],
53 | description: 'save orders api'
54 | });
55 |
56 | }
57 |
58 | public static getOrdersRoutes() {
59 | return container.get(OrdersRoutes).setUserRoutes();
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/api/rest/routes/users.routes.ts:
--------------------------------------------------------------------------------
1 | import container, {Service} from "typedi";
2 | import bodyParser from 'body-parser';
3 |
4 | import {UsersService} from "../../../services";
5 | import {authMiddleware} from "../middleware";
6 | import {CustomRouter} from "../../../core";
7 | import {RouterMethodsEnum} from "../../../common/enums";
8 | import responseModel from "../../../config/response";
9 | import {UsersHandler} from "../handlers";
10 |
11 | @Service()
12 | export class UsersRoutes {
13 |
14 | constructor(
15 | private userService: UsersService,
16 | private customRouter: CustomRouter,
17 | private usersHandler: UsersHandler
18 | ) {
19 | this.customRouter.init('users')
20 | }
21 |
22 | setUserRoutes() {
23 | this.getUsers();
24 | this.signUp();
25 | this.signIn();
26 | this.forgetPassword();
27 | this.resetPassword();
28 | return this.customRouter.exportRouterInstance();
29 | }
30 |
31 | getUsers() {
32 |
33 | this.customRouter.setRoute({
34 | path: '/',
35 | method: RouterMethodsEnum.get,
36 | middleware: [authMiddleware],
37 | handler: this.usersHandler.getUsersAPIHandler(),
38 | description: `This api used to get the users list`,
39 | responseModel: {
40 | ...responseModel,
41 | data: {
42 | users: [
43 | {
44 | id: 0,
45 | name: 'xyz'
46 | }
47 | ]
48 | }
49 | }
50 | });
51 |
52 | }
53 |
54 | signUp() {
55 |
56 | this.customRouter.setRoute({
57 | path: '/register',
58 | method: RouterMethodsEnum.post,
59 | handler: this.usersHandler.signUpAPIHandler(),
60 | middleware: [
61 | bodyParser.json(),
62 | bodyParser.urlencoded({extended: true}),
63 | ],
64 | description: 'Sign up api'
65 | });
66 |
67 | }
68 |
69 | signIn() {
70 |
71 | this.customRouter.setRoute({
72 | path: '/login',
73 | method: RouterMethodsEnum.post,
74 | handler: this.usersHandler.signInAPIHandler(),
75 | middleware: [
76 | bodyParser.json(),
77 | bodyParser.urlencoded({extended: true}),
78 | ],
79 | description: 'Sign in api'
80 | });
81 |
82 | }
83 |
84 | forgetPassword() {
85 |
86 | this.customRouter.setRoute({
87 | path: '/forget-password',
88 | method: RouterMethodsEnum.post,
89 | handler: this.usersHandler.forgetPasswordAPIHandler(),
90 | middleware: [
91 | bodyParser.json(),
92 | bodyParser.urlencoded({extended: true}),
93 | ],
94 | description: 'forget password api'
95 | });
96 |
97 | }
98 |
99 | resetPassword() {
100 |
101 | this.customRouter.setRoute({
102 | path: '/reset-password',
103 | method: RouterMethodsEnum.put,
104 | handler: this.usersHandler.resetPasswordAPIHandler(),
105 | middleware: [
106 | bodyParser.json(),
107 | authMiddleware
108 | ],
109 | description: 'logout the session'
110 | });
111 |
112 | }
113 |
114 | logout(){
115 | this.customRouter.setRoute({
116 | path: '/logout',
117 | method: RouterMethodsEnum.get,
118 | handler: this.usersHandler.logoutAPIHandler(),
119 | middleware: [
120 | bodyParser.urlencoded({extended: true}),
121 | authMiddleware
122 | ],
123 | description: 'reset password api'
124 | })
125 | }
126 |
127 | public static getUserRoutes() {
128 | return container.get(UsersRoutes).setUserRoutes();
129 | }
130 |
131 | }
132 |
--------------------------------------------------------------------------------
/src/common/decarators.ts.practice:
--------------------------------------------------------------------------------
1 | import "reflect-metadata";
2 |
3 | function color(value: string) { // this is the decorator factory
4 | return function (target, propertyKey: string, descriptor: PropertyDescriptor) { // this is the decorator
5 | // do something with 'target' and 'value'...
6 | console.log(target, propertyKey, descriptor, value)
7 | }
8 | }
9 |
10 | class Test{
11 |
12 | constructor() {
13 | }
14 |
15 | @color('red')
16 | method(){
17 | console.log('blue')
18 | }
19 |
20 |
21 | }
22 |
23 | function f() {
24 | console.log("f(): evaluated");
25 | return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
26 | console.log("f(): called");
27 | }
28 | }
29 |
30 | function g() {
31 | console.log("g(): evaluated");
32 | return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
33 | console.log("g(): called");
34 | }
35 | }
36 |
37 | // class C {
38 | // @f()
39 | // @g()
40 | // method() {}
41 | // }
42 |
43 | new Test().method();
44 |
45 | const formatMetadataKey = Symbol("format");
46 | const requiredMetadataKey = Symbol("required");
47 |
48 | class Greeter {
49 |
50 | @format("Hello, %s")
51 | greeting: string;
52 |
53 | constructor(message: string) {
54 | this.greeting = message;
55 | }
56 |
57 | @validate()
58 | greet(@required name: string, @required age: any) {
59 | let formatString = getFormat(this, "greeting");
60 | console.log(name);
61 | return formatString.replace("%s", this.greeting);
62 | }
63 | }
64 |
65 | console.log(formatMetadataKey);
66 | function format(formatString: string) {
67 | return Reflect.metadata(formatMetadataKey, formatString);
68 | }
69 |
70 | function getFormat(target: any, propertyKey: string) {
71 | return Reflect.getMetadata(formatMetadataKey, target, propertyKey);
72 | }
73 |
74 |
75 |
76 | function required(target: Object, propertyKey: string | symbol, parameterIndex: number) {
77 | let existingRequiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyKey) || [];
78 | console.log(existingRequiredParameters);
79 | console.log(parameterIndex);
80 | existingRequiredParameters.push(parameterIndex);
81 | Reflect.defineMetadata(requiredMetadataKey, existingRequiredParameters, target, propertyKey);
82 | }
83 |
84 | function validate() {
85 | return (target: any, propertyName: string, descriptor: TypedPropertyDescriptor)=>{
86 | let method = descriptor.value;
87 | descriptor.value = function () {
88 | let requiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyName);
89 | console.log(requiredParameters);
90 | if (requiredParameters) {
91 | for (let parameterIndex of requiredParameters) {
92 | console.log('arg', arguments[parameterIndex]);
93 | arguments[parameterIndex] += 'jdsf'
94 | if (parameterIndex >= arguments.length || arguments[parameterIndex] === undefined) {
95 | throw new Error("Missing required argument.");
96 | }
97 | }
98 | }
99 |
100 | return method.apply(this, arguments);
101 | }
102 | }
103 | }
104 | console.log(new Greeter('Test').greet('king', 18));
105 |
106 |
107 | // Design-time type annotations
108 | function Type(type) { return Reflect.metadata("design:type", type); }
109 | function ParamTypes(...types) { return Reflect.metadata("design:paramtypes", types); }
110 | function ReturnType(type) { return Reflect.metadata("design:returntype", type); }
111 |
112 | // Decorator application
113 | @ParamTypes(String, Number)
114 | class C {
115 | constructor(text, i) {
116 | }
117 |
118 | @Type(String)
119 | get name() { return "text"; }
120 |
121 | @Type(Function)
122 | @ParamTypes(Number, Number)
123 | @ReturnType(Number)
124 | add(x, y) {
125 | return x + y;
126 | }
127 | }
128 |
129 | // Metadata introspection
130 | let obj = new C(`a`, 5);
131 | let paramTypes = Reflect.getMetadata("design:type", obj, "add");
132 | console.log(paramTypes);
133 |
134 | function classDecorator(constructor:T) {
135 | return class extends constructor {
136 | newProperty = "new property";
137 | hello = "override";
138 | }
139 | }
140 |
141 | @classDecorator
142 | class Greeter2 {
143 | property = "property";
144 | hello: string;
145 | constructor(m: string) {
146 | this.hello = m;
147 | }
148 | }
149 |
150 | console.log(new Greeter2("world"));
151 |
--------------------------------------------------------------------------------
/src/common/enums/event-dispatcher-names.enum.ts:
--------------------------------------------------------------------------------
1 | export namespace EventDispatcherNamesEnum {
2 | export const users = {
3 | signIn: 'onUsersSignin',
4 | register: 'onUsersregister',
5 | logout: 'onUsersLogout',
6 | }
7 | export const orders = {
8 | create: 'onCreate'
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/common/enums/index.ts:
--------------------------------------------------------------------------------
1 | export * from "./router-methods.enum";
2 |
--------------------------------------------------------------------------------
/src/common/enums/router-methods.enum.ts:
--------------------------------------------------------------------------------
1 | export enum RouterMethodsEnum {
2 | get = 'get',
3 | post = 'post',
4 | put = 'put',
5 | patch = 'patch',
6 | delete = 'delete'
7 | }
8 |
--------------------------------------------------------------------------------
/src/common/index.ts:
--------------------------------------------------------------------------------
1 | export * from "./response.common";
2 | export * from "./utilities.common";
3 | export * from "./enums"
4 |
--------------------------------------------------------------------------------
/src/common/response.common.ts:
--------------------------------------------------------------------------------
1 | import outputData from "../config/response";
2 |
3 |
4 | /**
5 | * @description
6 | *
7 | * Sending the error response message.
8 | *
9 | * @param msg - error message
10 | * @param code - error code
11 | * @param sessionValidity
12 | * @param sessionToken
13 | */
14 | export function formatErrorMessage({msg, code = 400, sessionToken = null}: { msg: any, code?: number, sessionToken?: any }) {
15 | outputData.session.token = sessionToken;
16 | outputData.session.validity = !sessionToken ? 0 : 1;
17 | outputData.session.message = null;
18 |
19 | outputData.data = {};
20 | outputData.status.code = code;
21 | outputData.status.message = msg;
22 | return outputData;
23 | }
24 |
25 | /**
26 | * @description
27 | *
28 | * Sending the success message
29 | *
30 | * @param msg - status message
31 | * @param data - response data
32 | * @param sessionToken
33 | * @param sessionValidity
34 | * @param sessionMessage
35 | * @param statusCode
36 | */
37 | export function formatSuccessMessage(
38 | {msg, data = {}, sessionToken = null, sessionValidity = 1, sessionMessage = 'Session is valid', statusCode = 200}:
39 | { msg: any, data?: {}, sessionToken?: any, sessionValidity?: number, sessionMessage?: any, statusCode?: number }
40 | ) {
41 | outputData.session.token = sessionToken;
42 | outputData.session.validity = sessionValidity;
43 | outputData.session.message = sessionMessage;
44 |
45 | outputData.data = data;
46 | outputData.status.code = statusCode;
47 | outputData.status.message = msg;
48 |
49 | return outputData;
50 | }
51 |
--------------------------------------------------------------------------------
/src/common/utilities.common.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * @description
3 | * Deep cloning the JS Object
4 | *
5 | * @param data
6 | * @return {*} - cloned object or null
7 | */
8 | export function deepClone (data: T) : T | null {
9 | try {
10 | return JSON.parse(JSON.stringify(data));
11 | } catch (e) {
12 | return null;
13 | }
14 | }
15 |
16 | /**
17 | * @description
18 | *
19 | * Shallow cloning the JS Object. which is used to clone the
20 | * first child keys of the object not nested object or nested array.
21 | *
22 | * @param data
23 | * @return {*} - cloned object or null
24 | */
25 | export function shallowClone (data: T): T | null {
26 | if (!data) return null;
27 | if (typeof data === 'object') {
28 | return {
29 | ...data
30 | };
31 | } else {
32 | return null;
33 | }
34 | }
35 |
36 | /**
37 | * @description
38 | *
39 | * This function is used to test the data is array or not.
40 | *
41 | * @param data
42 | * @return {*}
43 | */
44 | export function isArray (data: Array): boolean {
45 | if (!data) return false;
46 |
47 | try {
48 | return Array.isArray(data);
49 | } catch (e) {
50 | return false;
51 | }
52 | }
53 |
54 | /**
55 | * @description
56 | *
57 | * This function is used to validate the data empty or not
58 | *
59 | * @param data
60 | * @return {boolean}
61 | */
62 | export function isEmpty (data: T): boolean {
63 | return !data;
64 | }
65 |
66 | /**
67 | * @description
68 | * Format an Date / Date String to mm/dd/yyyy format
69 | *
70 | * @param data
71 | * @return {*} - Date format in mm/dd/yyyy
72 | */
73 | export function toDateformat (data: Date) {
74 | try {
75 | data = new Date(data);
76 |
77 | let dd = data.getDate().toString();
78 |
79 | let mm = (data.getMonth() + 1).toString();
80 |
81 | const yyyy = data.getFullYear();
82 |
83 | if (+dd < 10) dd = '0' + dd;
84 |
85 | if (+mm < 10) mm = '0' + mm;
86 |
87 | return mm + '/' + dd + '/' + yyyy;
88 | } catch (e) {
89 | return null;
90 | }
91 | }
92 |
93 | /**
94 | * @description
95 | * extract Time (hh:mm) from an Date / Date String
96 | *
97 | * @param data
98 | * @return {*} - Time format in hh:mm
99 | */
100 | export function toTimeformat (data: Date) {
101 | try {
102 | return new Date(data).toISOString().replace(/^[^:]*([0-2]\d:[0-5]\d).*$/, '$1');
103 | } catch (e) {
104 | return null;
105 | }
106 | }
107 |
108 | export function mapValuesToArray (mapData: Object): T[] | any {
109 | try {
110 | if (!mapData) return null;
111 | const tempArr: T[] = [];
112 | Object.keys(mapData).forEach((key) => {
113 | // @ts-ignore
114 | tempArr.push(mapData[key] as T);
115 | });
116 | return tempArr;
117 | } catch (e) {
118 | return null;
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/config/index.ts:
--------------------------------------------------------------------------------
1 | import dotenv from 'dotenv';
2 | import appRoot from 'app-root-path';
3 |
4 | // Set the NODE_ENV to 'development' by default
5 | // process.env.NODE_ENV = process.env.NODE_ENV || 'development';
6 | debugger
7 | console.log(appRoot.path);
8 | if(process.env.NODE_ENV == 'development'){
9 |
10 | const envFound = dotenv.config({path: `${appRoot.path}/environments/${process.env.NODE_ENV}.env`});
11 | if (!envFound) {
12 | console.log(appRoot);
13 | throw new Error("⚠️ Couldn't find .env file ⚠️");
14 | }
15 | console.log(envFound)
16 |
17 | }
18 |
19 | export default {
20 | /**
21 | * Your favorite port
22 | */
23 | port: parseInt(process.env.PORT || '3000', 10),
24 |
25 | /**
26 | * mongodb config
27 | */
28 | db: {
29 | url: process.env.MONGODB_URI,
30 | user: process.env.DB_USER,
31 | password: process.env.DB_PASSWORD
32 | },
33 | /**
34 | * Your secret sauce
35 | */
36 | jwtSecret: process.env.JWT_SECRET,
37 |
38 | sessionSecret: 'MsSinErt',
39 |
40 | /**
41 | * Used by winston logger
42 | */
43 | logs: {
44 | level: process.env.LOG_LEVEL || 'silly',
45 | },
46 |
47 |
48 | /**
49 | * Agendash config
50 | */
51 | agendash: {
52 | user: 'agendash',
53 | password: '123456'
54 | },
55 | /**
56 | * API configs
57 | */
58 | api: {
59 | prefix: '/api/v1',
60 | },
61 | /**
62 | * Mailgun email credentials
63 | */
64 | emails: {
65 | apiKey: 'API key from mailgun',
66 | domain: 'Domain Name from mailgun'
67 | }
68 | };
69 |
--------------------------------------------------------------------------------
/src/config/response.ts:
--------------------------------------------------------------------------------
1 | export default {
2 | "session": {
3 | "token": null,
4 | "validity": 0,
5 | "message": null
6 | },
7 | "data": {},
8 | "status": {
9 | "code": 400,
10 | "message": "Success"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/core/custom-router.ts:
--------------------------------------------------------------------------------
1 | import express, {RequestHandler, Router} from 'express';
2 | import {IRouterParams} from "../types/IRouterParams";
3 | import {RouterMethodsEnum} from "../common/enums/router-methods.enum";
4 | import {Service} from "typedi";
5 |
6 | @Service()
7 | export class CustomRouter {
8 |
9 | // @ts-ignore
10 | router: express.Router;
11 |
12 | // For future purpose
13 | // @ts-ignore
14 | baseURL: string;
15 |
16 | init(baseURL: string) {
17 | this.baseURL = baseURL;
18 | this.router = Router();
19 | }
20 |
21 | setRoute(routerParams: IRouterParams) {
22 |
23 | switch (routerParams.method) {
24 | case RouterMethodsEnum.get: {
25 | this.router.get(routerParams.path, routerParams.middleware, routerParams.handler);
26 | break
27 | }
28 | case RouterMethodsEnum.post: {
29 | this.router.post(routerParams.path, routerParams.middleware, routerParams.handler);
30 | break;
31 | }
32 |
33 | case RouterMethodsEnum.put: {
34 | this.router.put(routerParams.path, routerParams.middleware, routerParams.handler);
35 | break;
36 | }
37 | case RouterMethodsEnum.patch: {
38 | this.router.patch(routerParams.path, routerParams.middleware, routerParams.handler);
39 | break;
40 | }
41 | case RouterMethodsEnum.delete: {
42 | this.router.delete(routerParams.path, routerParams.middleware, routerParams.handler);
43 | break;
44 | }
45 | default:
46 | // @ts-ignore
47 | this.router[routerParams.method] && this.router[routerParams.method](routerParams.path, routerParams.middleware, routerParams.handler);
48 |
49 | }
50 |
51 | }
52 |
53 | exportRouterInstance() {
54 | return this.router;
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/src/core/index.ts:
--------------------------------------------------------------------------------
1 | export * from './custom-router';
2 |
--------------------------------------------------------------------------------
/src/core/jwt.provider.ts:
--------------------------------------------------------------------------------
1 | import {Service} from "typedi";
2 | import * as jwt from 'jsonwebtoken';
3 |
4 | import config from '../config';
5 |
6 | export class JwtProvider {
7 |
8 | public static generateToken(userId: string, role: string) {
9 | return jwt.sign({userId: userId, role}, config.jwtSecret as string, {
10 | expiresIn: 86400 // expires in 24 hours
11 | });
12 | }
13 |
14 | public static verifyToken(token: string) {
15 | if(!token) return;
16 | return jwt.verify(token, config.jwtSecret as string)
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/loaders/dependencyInjector.ts:
--------------------------------------------------------------------------------
1 | import { Container } from 'typedi';
2 | import LoggerInstance from './loggers.loader';
3 |
4 | export default function dependencyInjector(mongoConnection: any, models: Array<{name:string, model: any}> ) {
5 | try {
6 | models.forEach(m => {
7 | Container.set(m.name, m.model);
8 | });
9 | Container.set('LoggerInstance', LoggerInstance);
10 | Container.set('mongoConnection', mongoConnection);
11 | }catch (e) {
12 | LoggerInstance.error(e.message)
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/loaders/express.loader.ts:
--------------------------------------------------------------------------------
1 | import express, {Request} from 'express';
2 | import bodyParser from "body-parser";
3 | import morgan from "morgan";
4 | import {Container, Inject} from "typedi";
5 | import {Logger} from "winston";
6 | import helmet from 'helmet';
7 | import session from 'express-session';
8 | import cookieParser from 'cookie-parser'
9 | import connectMongoDBSession from 'connect-mongodb-session';
10 |
11 | import APIs from '../api';
12 | import LoggerInstance from "./loggers.loader";
13 | import config from '../config';
14 |
15 |
16 | export class ExpressLoader {
17 |
18 | private constructor(
19 | private app: express.Application,
20 | ) {
21 | }
22 |
23 |
24 | public static async load(app: express.Application) {
25 | const expressLoader = new ExpressLoader(app);
26 | expressLoader.config();
27 | return expressLoader.app
28 | }
29 |
30 | public config() {
31 |
32 | this.setSecurityConfig();
33 | this.setExpressSession();
34 |
35 | // Logging all the inbound request
36 | const wintsonLogger: Logger = Container.get('LoggerInstance');
37 | const stream = {
38 | write: function (message: string) {
39 | wintsonLogger.info(message);
40 | },
41 | };
42 | const logger = morgan("combined", {stream});
43 | this.app.use(logger);
44 |
45 | // we use it for only post calls instead of middleware for low latency
46 | // this.app.use(bodyParser.json());
47 | // this.app.use(bodyParser.urlencoded({extended: true}));
48 |
49 | this.app.use(express.urlencoded({extended: false}));
50 |
51 | APIs.loadRestEndPoints(this.app);
52 | }
53 |
54 | setExpressSession() {
55 |
56 | //use sessions for tracking logins
57 | const MongoDBStore = connectMongoDBSession(session);
58 | const wintsonLogger: Logger = Container.get('LoggerInstance');
59 | const store = new MongoDBStore({
60 | uri: config.db.url as string,
61 | collection: 'sessions',
62 | connectionOptions: {
63 | logger: (msg, option) => {
64 | if (option?.type == 'info') msg && wintsonLogger.info(msg);
65 | if (option?.type == 'error') msg && wintsonLogger.error(msg);
66 | },
67 | auth: {
68 | user: config.db.user as string,
69 | password: config.db.password as string
70 | }
71 | },
72 |
73 | });
74 |
75 | this.app.use(cookieParser());
76 | this.app.use(session({
77 | name: 'app.sid',
78 | secret: config.sessionSecret,
79 | resave: true,
80 | saveUninitialized: true,
81 | cookie: {
82 | domain: 'http://localhost:4200',
83 | maxAge: 24 * 6 * 60 * 10000
84 | },
85 | store: store,
86 | }));
87 |
88 | }
89 |
90 | /**
91 | * {@link https://blog.risingstack.com/node-js-security-checklist/,
92 | * https://www.owasp.org/index.php/Web_Application_Security_Testing_Cheat_Sheet,
93 | * https://expressjs.com/en/advanced/best-practice-security.html}
94 | */
95 | private setSecurityConfig() {
96 |
97 | // setting the request headers to express app instance
98 | // this is for sample you need to do it as per your requirements
99 | this.app.use(function (req: Request, res, next) {
100 | console.log('origin', req.get('origin'));
101 |
102 | res.header('Access-Control-Allow-Credentials', true as any);
103 | res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
104 | res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PATCH, DELETE');
105 | res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, x-access-token, X-Requested-With, Content-Type, Accept, Cache-Control, Authorization, WWW-Authenticate');
106 | res.header('Access-Control-Expose-Headers', 'WWW-Authenticate, x-access-token');
107 | return next();
108 | });
109 |
110 | // Helmet can help protect your app from some well-known web vulnerabilities by setting HTTP headers
111 | // appropriately. Helmet is actually just a collection of smaller middleware functions that set
112 | // security-related HTTP response headers:
113 | this.app.use(helmet());
114 |
115 | }
116 |
117 | }
118 |
119 | export default ExpressLoader;
120 |
--------------------------------------------------------------------------------
/src/loaders/index.ts:
--------------------------------------------------------------------------------
1 | import mongoose from 'mongoose';
2 | import "reflect-metadata";
3 |
4 | import ExpressLoader from './express.loader';
5 | import Logger from './loggers.loader';
6 | import MongoDBLoader from './mongoose.loader';
7 | import dependencyInjector from './dependencyInjector';
8 | import {OrdersModelSchema, UsersModelSchema} from '../models';
9 |
10 | export async function loadModules(moduleInstance: { expressApp: any }) {
11 |
12 | const mongooseConnection = await MongoDBLoader();
13 | Logger.info('✌️ DB loaded and connected!');
14 |
15 | const usersModel = {name: 'UsersModel', model: mongoose.model('user', UsersModelSchema.getInstance() , 'users')};
16 | const ordersModel = {name: 'OrdersModel', model: mongoose.model('orders', OrdersModelSchema.getInstance() , 'orders')};
17 |
18 | dependencyInjector(
19 | mongooseConnection,
20 | [
21 | usersModel,
22 | ordersModel
23 | ]);
24 |
25 | const app = await ExpressLoader.load(moduleInstance.expressApp);
26 | Logger.info('Express loaded');
27 |
28 | return {
29 | app
30 | }
31 | }
32 |
33 | export default loadModules
34 |
--------------------------------------------------------------------------------
/src/loaders/loggers.loader.ts:
--------------------------------------------------------------------------------
1 | import winston from 'winston';
2 | import config from '../config';
3 | import appRoot from 'app-root-path';
4 |
5 | const transports = [];
6 | if (process.env.NODE_ENV == 'development') {
7 | transports.push(
8 | new winston.transports.Console()
9 | )
10 | } else {
11 | transports.push(
12 | new winston.transports.Console({
13 | format: winston.format.combine(
14 | winston.format.cli(),
15 | winston.format.splat(),
16 | winston.format.timestamp({
17 | format: 'YYYY-MM-DD HH:mm:ss'
18 | })
19 | )
20 | })
21 | );
22 | transports.push(
23 | new winston.transports.File({
24 | filename: 'app.log',
25 | level: 'info',
26 | dirname: appRoot.path + '/logs',
27 | }))
28 | }
29 |
30 | const LoggerInstance = winston.createLogger({
31 | level: config.logs.level,
32 | levels: winston.config.npm.levels,
33 | format: winston.format.combine(
34 | winston.format.timestamp({
35 | format: 'YYYY-MM-DD HH:mm:ss'
36 | }),
37 | winston.format.errors({stack: true}),
38 | winston.format.splat(),
39 | winston.format.json()
40 | ),
41 | transports
42 | });
43 |
44 | export default LoggerInstance;
45 |
--------------------------------------------------------------------------------
/src/loaders/mongoose.loader.ts:
--------------------------------------------------------------------------------
1 | import mongoose from 'mongoose';
2 | import config from '../config';
3 |
4 | export default async (): Promise => {
5 | try {
6 | console.log(config);
7 | const mongooseInstance = await mongoose.connect(config.db.url as string, {
8 | keepAlive: true,
9 | keepAliveInitialDelay: 300000,
10 | socketTimeoutMS: 2000000,
11 | useNewUrlParser: true,
12 | useUnifiedTopology: true,
13 | useCreateIndex: true,
14 | user: config.db.user,
15 | pass: config.db.password
16 | });
17 | return mongooseInstance.connection.db;
18 | }catch (e) {
19 | console.error(e);
20 | }
21 | };
22 |
--------------------------------------------------------------------------------
/src/models/index.ts:
--------------------------------------------------------------------------------
1 | export * from './users.model';
2 | export * from './orders.model';
3 |
--------------------------------------------------------------------------------
/src/models/orders.model.ts:
--------------------------------------------------------------------------------
1 | import mongoose, {NativeError, Schema} from "mongoose";
2 |
3 |
4 | export class OrdersModelSchema {
5 |
6 | schema: Schema;
7 |
8 | constructor() {
9 | this.schema = new mongoose.Schema({
10 | "_id": {type: mongoose.Types.ObjectId, auto: true},
11 | "name": {type: String},
12 | "unitType": {type: String, default: 'kg'},
13 | "units": {type: String},
14 | "userId": {type: mongoose.Types.ObjectId},
15 | }, {capped: false, timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}, versionKey: false});
16 |
17 | this.configStaticsExtensionMethods();
18 | }
19 |
20 | configStaticsExtensionMethods() {
21 | this.getOrdersExtension();
22 | this.postOrdersExtension();
23 | }
24 |
25 | getOrdersExtension() {
26 |
27 | this.schema.statics.getOrders = function (options: { userId: string, ordersDate: Date }, role: string) {
28 |
29 | return new Promise((resolve, reject) => {
30 |
31 | const startDate = new Date(options.ordersDate).setHours(0, 0, 1);
32 | const endDate = new Date(options.ordersDate).setHours(24, 0);
33 | const query: any = {
34 | created_at: {
35 | $gte: new Date(startDate).toISOString(),
36 | $lt: new Date(endDate).toISOString()
37 | }
38 | };
39 |
40 | if(role == 'admin'){
41 | query.userId = options.userId;
42 | }
43 |
44 | this.find(query).exec((err: NativeError, orders: any) => {
45 | if (!err) {
46 | resolve(orders);
47 | } else {
48 | resolve({error: 'No orders found'})
49 | }
50 | })
51 | })
52 | }
53 |
54 | }
55 |
56 | postOrdersExtension() {
57 |
58 | this.schema.statics.saveOrder = function (orderDetails: any) {
59 | return new Promise((resolve, reject) => {
60 | console.log('orders', orderDetails);
61 | this.create(orderDetails, (err: NativeError) => {
62 | if (!err) {
63 | resolve({message: 'Order created successfully'})
64 | } else {
65 | resolve({error: 'Order not created'})
66 | }
67 | })
68 | });
69 | }
70 | }
71 |
72 |
73 | static getInstance() {
74 | const ins = new OrdersModelSchema();
75 | ins.configStaticsExtensionMethods();
76 | return ins.schema;
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/models/users.model.ts:
--------------------------------------------------------------------------------
1 | import mongoose, {NativeError, Schema} from 'mongoose';
2 | import * as bcrypt from "bcrypt";
3 |
4 | import {IUser} from "../types";
5 |
6 | const SchemaTypes = mongoose.Schema.Types;
7 |
8 | export class UsersModelSchema {
9 |
10 | schema: Schema;
11 |
12 | constructor() {
13 | this.schema = new mongoose.Schema({
14 | "_id": {type: mongoose.Types.ObjectId, auto: true},
15 | "name": {type: String},
16 | "email": {type: String},
17 | "password": String,
18 | "role": {type: String, default: 'user',},
19 | }, {timestamps: true, versionKey: false});
20 | }
21 |
22 | configStaticsExtensionMethods() {
23 | this.hooksExtention();
24 | this.getUsersExtention();
25 | this.registerUserDetailsExtention();
26 | this.authenticateExtention();
27 | }
28 |
29 | hooksExtention(){
30 | this.schema.pre('save', function(next){
31 | const user: any = this;
32 | bcrypt.hash(user.password, 10, function (err, hash){
33 | if (err) {
34 | return next(err);
35 | }
36 | user.password = hash;
37 | next();
38 | })
39 | })
40 | }
41 |
42 |
43 | getUsersExtention() {
44 | this.schema.statics.getUsers = function (query: any) {
45 | return new Promise((resolve, reject) => {
46 | this.find(query).then((result: any) => {
47 | resolve(result);
48 | }).catch((err: Error) => {
49 | reject(err);
50 | });
51 | });
52 | }
53 | }
54 |
55 | registerUserDetailsExtention() {
56 |
57 | this.schema.statics.registerUserDetails = function (user: IUser) {
58 |
59 | return new Promise((resolve, reject) => {
60 | this.find({email: user.email})
61 | .then((result: any) => {
62 | if (!result || result.length === 0) {
63 | this.create(user, ((err: Error, doc: any) => {
64 | if (!err) {
65 | resolve(doc);
66 | return
67 | }
68 |
69 | resolve({error: 'Something went wrong', isSuccess: false});
70 | return;
71 | }));
72 | } else {
73 | console.log('Error',result);
74 | resolve({error: 'Email is already exsits', isSuccess: false})
75 | }
76 | }).catch((err: Error) => reject(err))
77 | ;
78 | });
79 |
80 | }
81 | }
82 |
83 | authenticateExtention() {
84 | this.schema.statics.authenticate = function (auth: { email: string, password: string }) {
85 | return new Promise((resolve, reject) => {
86 | this.findOne({email: auth.email})
87 | .exec((err: NativeError, user: any) => {
88 | if (!err) {
89 | bcrypt.compare(user.password, auth.password, (err, callback) => {
90 | if (!err) {
91 | const output = JSON.parse(JSON.stringify(user));
92 | delete output.password;
93 | resolve(output)
94 | } else {
95 | resolve({error: 'Password not matched'});
96 | }
97 | })
98 | }else resolve({error: 'user not found'});
99 | });
100 | });
101 | }
102 | }
103 |
104 | static getInstance() {
105 | const ins = new UsersModelSchema();
106 | ins.configStaticsExtensionMethods();
107 | return ins.schema;
108 | }
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/src/server.ts:
--------------------------------------------------------------------------------
1 | import express from 'express';
2 | import http2, {Server} from 'http';
3 | import {Container} from "typedi";
4 | import {Logger} from "winston";
5 |
6 | import loaders from './loaders'
7 | import config from './config';
8 |
9 |
10 | export class AppServer {
11 |
12 | public PORT = config.port || '3000';
13 | logger: Logger | null = null;
14 |
15 | constructor() {
16 | }
17 |
18 | public static async start(){
19 |
20 | const appServer = new AppServer();
21 | const app = express();
22 | const loadedModules = await loaders({ expressApp: app});
23 | appServer.logger = Container.get('LoggerInstance');
24 | const server = http2.createServer(loadedModules?.app)
25 | .listen(appServer.PORT);
26 |
27 | server.on( 'listening', appServer.onListening(server));
28 | server.on('error', appServer.onError(server));
29 | appServer.prepareAppToExitWhileCrashes(server);
30 | appServer.exceptionHandling();
31 |
32 | }
33 |
34 | private onListening(server: Server){
35 | return ()=>{
36 | const addr = server.address();
37 | console.log('listening');
38 | }
39 | }
40 |
41 | private onError(server: Server){
42 | return (error: Error | any)=>{
43 |
44 | const logger: Logger = Container.get('LoggerInstance');
45 |
46 |
47 | if (error.syscall !== 'listen') {
48 | throw error;
49 | }
50 |
51 | var bind = typeof this.PORT === 'string'
52 | ? 'Pipe ' + this.PORT
53 | : 'Port ' + this.PORT;
54 |
55 | // handle specific listen errors with friendly messages
56 | switch (error.code) {
57 | case 'EACCES':
58 | logger.error(bind + ' requires elevated privileges');
59 | process.exit(1);
60 | break;
61 | case 'EADDRINUSE':
62 | logger.error(bind + ' is already in use');
63 | process.exit(1);
64 | break;
65 | default:
66 | throw error;
67 | }
68 |
69 | }
70 | }
71 |
72 | prepareAppToExitWhileCrashes(server: Server) {
73 | process.on('SIGINT', function () {
74 | server.close(function () {
75 | process.exit(0);
76 | });
77 | });
78 | }
79 |
80 | exceptionHandling(){
81 |
82 | process.on('uncaughtException', (err) => {
83 | this.logger?.error(err);
84 | process.exit(1); // process will start the server again by pm2 in production
85 | });
86 |
87 | const unhandledRejections = new Map();
88 | process.on('unhandledRejection', (reason, promise) => {
89 | unhandledRejections.set(promise, reason);
90 | console.log(reason);
91 | });
92 |
93 | process.on('rejectionHandled', async (promise) => {
94 | unhandledRejections.delete(promise);
95 | console.log(await promise);
96 | });
97 |
98 | }
99 |
100 | }
101 |
102 |
103 | AppServer.start();
104 |
--------------------------------------------------------------------------------
/src/services/index.ts:
--------------------------------------------------------------------------------
1 | export * from './users.service';
2 |
--------------------------------------------------------------------------------
/src/services/orders.service.ts:
--------------------------------------------------------------------------------
1 | import {Inject, Service} from "typedi";
2 | import {EventDispatcher} from "event-dispatch";
3 |
4 | @Service()
5 | export class OrdersService {
6 |
7 | eventDispatcher = new EventDispatcher();
8 |
9 | constructor(
10 | @Inject('OrdersModel') private ordersModel: any
11 | ) {
12 | }
13 |
14 | public async getOrders(options: any, role: string) {
15 | const result = await this.ordersModel.getOrders(options, role);
16 | return result;
17 | }
18 |
19 | public async postOrders(orderDetails: any) {
20 | const order = this.ordersModel(orderDetails);
21 | const result = await this.ordersModel.saveOrder(orderDetails);
22 | return result;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/services/users.service.ts:
--------------------------------------------------------------------------------
1 | import {Inject, Service} from "typedi";
2 | import {EventDispatcher} from "event-dispatch";
3 |
4 | import "../subscribers/users.events-subscriber";
5 | import {IUser} from "../types";
6 | import {EventDispatcherNamesEnum} from "../common/enums/event-dispatcher-names.enum";
7 |
8 | @Service()
9 | export class UsersService {
10 |
11 | eventDispatcher = new EventDispatcher();
12 |
13 | constructor(
14 | @Inject('UsersModel') private usersModel: any
15 | ) {
16 | }
17 |
18 | public async getUsers() {
19 |
20 | return await this.usersModel.getUsers({});
21 | }
22 |
23 | public async registerUser(payload: IUser) {
24 | const result = await this.usersModel.registerUserDetails(payload);
25 | this.eventDispatcher.dispatch(EventDispatcherNamesEnum.users.register, {payload, result})
26 | return result;
27 | }
28 |
29 | public async login(payload: {email: string, password: string}) {
30 | const result = await this.usersModel.authenticate(payload);
31 | this.eventDispatcher.dispatch(EventDispatcherNamesEnum.users.signIn, {payload, result});
32 | return result;
33 | }
34 |
35 | public async logout(sessionId: string){
36 | this.eventDispatcher.dispatch(EventDispatcherNamesEnum.users.logout, {sessionId})
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/subscribers/orders-event.subscriber.ts:
--------------------------------------------------------------------------------
1 | import {EventSubscriber, On} from "event-dispatch";
2 | import {EventDispatcherNamesEnum} from "../common/enums/event-dispatcher-names.enum";
3 |
4 | @EventSubscriber()
5 | export class OrdersEventSubscriber {
6 |
7 | @On(EventDispatcherNamesEnum.orders.create)
8 | create(data: any) {
9 |
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/subscribers/users.events-subscriber.ts:
--------------------------------------------------------------------------------
1 | import {EventSubscriber, On} from "event-dispatch";
2 |
3 | import {IUser} from "../types";
4 | import {EventDispatcherNamesEnum} from "../common/enums/event-dispatcher-names.enum";
5 |
6 | @EventSubscriber()
7 | export class UsersEventsSubscriber {
8 |
9 |
10 | @On(EventDispatcherNamesEnum.users.register)
11 | register(user: IUser) {
12 |
13 | }
14 |
15 | @On(EventDispatcherNamesEnum.users.signIn)
16 | signIn(user: IUser) {
17 |
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/types/IRouterParams.ts:
--------------------------------------------------------------------------------
1 | import {RequestHandler} from "express";
2 |
3 | export interface IRouterParams {
4 | path: string,
5 | method: string,
6 | handler: RequestHandler,
7 | middleware: RequestHandler[],
8 | description: string,
9 | responseModel?: any,
10 | samplePayload?: any,
11 | }
12 |
--------------------------------------------------------------------------------
/src/types/IUser.ts:
--------------------------------------------------------------------------------
1 | export interface IUser {
2 | _id: string;
3 | name: string;
4 | email: string;
5 | password: string,
6 | role: string
7 | }
8 |
--------------------------------------------------------------------------------
/src/types/index.ts:
--------------------------------------------------------------------------------
1 | export * from './IRouterParams';
2 | export * from './IUser';
3 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "commonjs",
5 | "outDir": "./dist",
6 | "strict": true,
7 | "baseUrl": "./",
8 | "esModuleInterop": true,
9 | "experimentalDecorators": true,
10 | "emitDecoratorMetadata": true,
11 | "forceConsistentCasingInFileNames": true,
12 | "allowSyntheticDefaultImports": true,
13 | // "noImplicitAny": true,
14 | "allowJs": true,
15 | "lib": [
16 | "es2015"
17 | ]
18 | },
19 | "typeRoots": [
20 | "node_modules/@types"
21 | ],
22 | "includes": [
23 | "./src/**/*.ts"
24 | ],
25 | "exclude": [
26 | "node_modules"
27 | ]
28 | }
29 |
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const webpack = require('webpack');
3 |
4 | /*
5 | * SplitChunksPlugin is enabled by default and replaced
6 | * deprecated CommonsChunkPlugin. It automatically identifies modules which
7 | * should be splitted of chunk by heuristics using module duplication count and
8 | * module category (i. e. node_modules). And splits the chunks…
9 | *
10 | * It is safe to remove "splitChunks" from the generated configuration
11 | * and was added as an educational example.
12 | *
13 | * https://webpack.js.org/plugins/split-chunks-plugin/
14 | *
15 | */
16 |
17 | /*
18 | * We've enabled TerserPlugin for you! This minifies your app
19 | * in order to load faster and run less javascript.
20 | *
21 | * https://github.com/webpack-contrib/terser-webpack-plugin
22 | *
23 | */
24 |
25 | const TerserPlugin = require('terser-webpack-plugin');
26 |
27 | const workboxPlugin = require('workbox-webpack-plugin');
28 |
29 | module.exports = {
30 | mode: 'development',
31 | entry: './src/server.ts',
32 | target: "node",
33 | output: {
34 | path: path.join(__dirname, 'dist/'), // express static folder is at /app/lib
35 | filename: '[name].js', // the file name of the bundle to create. [name] is,
36 | },
37 | devtool: 'source-map',
38 | plugins: [
39 | new webpack.ProgressPlugin(),
40 | new workboxPlugin.GenerateSW({
41 | swDest: 'sw.js',
42 | clientsClaim: true,
43 | skipWaiting: false
44 | })
45 | ],
46 |
47 | module: {
48 | rules: [
49 | {
50 | test: /.(ts|tsx)?$/,
51 | loader: 'ts-loader',
52 | include: [path.resolve(__dirname, 'src')],
53 | exclude: [/node_modules/]
54 | },
55 | {
56 | test: /\.(env)?$/,
57 | include: path.join(__dirname, 'environments'),
58 | use: [{
59 | loader: 'file-loader',
60 | options: {
61 | name: '[name].[ext]',
62 | outputPath: 'environment/'
63 | }
64 | }]
65 | }
66 | ]
67 | },
68 |
69 | resolve: {
70 | extensions: ['.tsx', '.ts', '.js'],
71 | },
72 |
73 | optimization: {
74 | minimize: false,
75 | minimizer: [
76 | new TerserPlugin({
77 | test: /\.js(\?.*)?$/i
78 | }),
79 | ],
80 |
81 | splitChunks: {
82 | cacheGroups: {
83 | vendors: {
84 | priority: -10,
85 | test: /[\\/]node_modules[\\/]/
86 | }
87 | },
88 |
89 | chunks: 'async',
90 | minChunks: 1,
91 | minSize: 30000,
92 | name: true
93 | }
94 | }
95 | };
96 |
--------------------------------------------------------------------------------