├── .docker-node-api ├── .data │ └── .gitignore ├── docker-compose.yml └── redis │ ├── Dockerfile │ └── redis.conf ├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ └── test.yml ├── .nvmrc ├── README.md └── api ├── .env.example ├── .gitignore ├── .prettierrc ├── eslint.config.mjs ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app-cache │ ├── app-cache.module.ts │ └── services │ │ └── cache-config │ │ ├── cache-config.service.spec.ts │ │ └── cache-config.service.ts ├── app.module.ts ├── db │ ├── db.module.ts │ └── migrations │ │ └── 1636917857168-Users.ts ├── global │ ├── constants.ts │ ├── global.module.ts │ ├── middleware │ │ └── async-storage │ │ │ ├── async-storage.middleware.spec.ts │ │ │ └── async-storage.middleware.ts │ └── services │ │ └── mail │ │ ├── mail.service.ts │ │ └── mailer.service.spec.ts ├── health │ ├── health.controller.spec.ts │ ├── health.controller.ts │ ├── health.module.ts │ └── indicators │ │ └── cache │ │ ├── cache.health-indicator.spec.ts │ │ └── cache.health-indicator.ts ├── logger │ ├── interceptors │ │ ├── request-logger.interceptor.spec.ts │ │ └── request-logger.interceptor.ts │ ├── logger.module.ts │ └── services │ │ └── app-logger │ │ ├── app-logger.service.spec.ts │ │ └── app-logger.service.ts ├── main.ts ├── services │ └── app-config │ │ ├── configuration.spec.ts │ │ └── configuration.ts └── user │ ├── dto │ ├── create-user.dto.ts │ └── login.dto.ts │ ├── entities │ ├── __fixtures__ │ │ └── user-entity.fixture.ts │ └── user.entity.ts │ ├── guards │ └── jwt-auth │ │ └── jwt-auth.guard.ts │ ├── services │ ├── auth │ │ ├── auth.service.spec.ts │ │ ├── auth.service.ts │ │ └── strategies │ │ │ └── jwt │ │ │ ├── jwt.strategy.spec.ts │ │ │ └── jwt.strategy.ts │ ├── jwt │ │ ├── jwt.service.spec.ts │ │ └── jwt.service.ts │ ├── password │ │ ├── password.service.spec.ts │ │ └── password.service.ts │ └── user │ │ ├── user.service.spec.ts │ │ └── user.service.ts │ ├── user.controller.spec.ts │ ├── user.controller.ts │ └── user.module.ts ├── test ├── app.e2e-spec.ts ├── jest-e2e.json └── test-utils │ └── cache.mock.ts ├── tsconfig.build.json ├── tsconfig.json └── type-orm.config.ts /.docker-node-api/.data/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore 3 | -------------------------------------------------------------------------------- /.docker-node-api/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | 5 | ### DB ################################################ 6 | db: 7 | image: postgres 8 | restart: always 9 | environment: 10 | POSTGRES_PASSWORD: secret 11 | POSTGRES_DB: api 12 | volumes: 13 | - ./.data/db:/var/lib/postgresql/data 14 | ports: 15 | - "5432:5432" 16 | 17 | ### Redis ################################################ 18 | redis: 19 | build: ./redis 20 | volumes: 21 | - ./.data/redis:/data 22 | ports: 23 | - "6379:6379" 24 | 25 | ### Mail trap ################################################ 26 | mailhog: 27 | image: mailhog/mailhog 28 | restart: always 29 | ports: ['1025:1025', '8025:8025'] 30 | -------------------------------------------------------------------------------- /.docker-node-api/redis/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM redis:latest 2 | 3 | ## For security settings uncomment, make the dir, copy conf, and also start with the conf, to use it 4 | #RUN mkdir -p /usr/local/etc/redis 5 | #COPY redis.conf /usr/local/etc/redis/redis.conf 6 | 7 | VOLUME /data 8 | 9 | EXPOSE 6379 10 | 11 | #CMD ["redis-server", "/usr/local/etc/redis/redis.conf"] 12 | CMD ["redis-server"] 13 | -------------------------------------------------------------------------------- /.docker-node-api/redis/redis.conf: -------------------------------------------------------------------------------- 1 | # Redis configuration file example. 2 | # 3 | # Note that in order to read the configuration file, Redis must be 4 | # started with the file path as first argument: 5 | # 6 | # ./redis-server /path/to/redis.conf 7 | 8 | # Note on units: when memory size is needed, it is possible to specify 9 | # it in the usual form of 1k 5GB 4M and so forth: 10 | # 11 | # 1k => 1000 bytes 12 | # 1kb => 1024 bytes 13 | # 1m => 1000000 bytes 14 | # 1mb => 1024*1024 bytes 15 | # 1g => 1000000000 bytes 16 | # 1gb => 1024*1024*1024 bytes 17 | # 18 | # units are case insensitive so 1GB 1Gb 1gB are all the same. 19 | 20 | ################################## INCLUDES ################################### 21 | 22 | # Include one or more other config files here. This is useful if you 23 | # have a standard template that goes to all Redis servers but also need 24 | # to customize a few per-server settings. Include files can include 25 | # other files, so use this wisely. 26 | # 27 | # Notice option "include" won't be rewritten by command "CONFIG REWRITE" 28 | # from admin or Redis Sentinel. Since Redis always uses the last processed 29 | # line as value of a configuration directive, you'd better put includes 30 | # at the beginning of this file to avoid overwriting config change at runtime. 31 | # 32 | # If instead you are interested in using includes to override configuration 33 | # options, it is better to use include as the last line. 34 | # 35 | # include /path/to/local.conf 36 | # include /path/to/other.conf 37 | 38 | ################################## MODULES ##################################### 39 | 40 | # Load modules at startup. If the server is not able to load modules 41 | # it will abort. It is possible to use multiple loadmodule directives. 42 | # 43 | # loadmodule /path/to/my_module.so 44 | # loadmodule /path/to/other_module.so 45 | 46 | ################################## NETWORK ##################################### 47 | 48 | # By default, if no "bind" configuration directive is specified, Redis listens 49 | # for connections from all the network interfaces available on the server. 50 | # It is possible to listen to just one or multiple selected interfaces using 51 | # the "bind" configuration directive, followed by one or more IP addresses. 52 | # 53 | # Examples: 54 | # 55 | # bind 192.168.1.100 10.0.0.1 56 | # bind 127.0.0.1 ::1 57 | # 58 | # ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the 59 | # internet, binding to all the interfaces is dangerous and will expose the 60 | # instance to everybody on the internet. So by default we uncomment the 61 | # following bind directive, that will force Redis to listen only into 62 | # the IPv4 loopback interface address (this means Redis will be able to 63 | # accept connections only from clients running into the same computer it 64 | # is running). 65 | # 66 | # IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES 67 | # JUST COMMENT THE FOLLOWING LINE. 68 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 69 | bind 127.0.0.1 70 | 71 | # Protected mode is a layer of security protection, in order to avoid that 72 | # Redis instances left open on the internet are accessed and exploited. 73 | # 74 | # When protected mode is on and if: 75 | # 76 | # 1) The server is not binding explicitly to a set of addresses using the 77 | # "bind" directive. 78 | # 2) No password is configured. 79 | # 80 | # The server only accepts connections from clients connecting from the 81 | # IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain 82 | # sockets. 83 | # 84 | # By default protected mode is enabled. You should disable it only if 85 | # you are sure you want clients from other hosts to connect to Redis 86 | # even if no authentication is configured, nor a specific set of interfaces 87 | # are explicitly listed using the "bind" directive. 88 | protected-mode yes 89 | 90 | # Accept connections on the specified port, default is 6379 (IANA #815344). 91 | # If port 0 is specified Redis will not listen on a TCP socket. 92 | port 6379 93 | 94 | # TCP listen() backlog. 95 | # 96 | # In high requests-per-second environments you need an high backlog in order 97 | # to avoid slow clients connections issues. Note that the Linux kernel 98 | # will silently truncate it to the value of /proc/sys/net/core/somaxconn so 99 | # make sure to raise both the value of somaxconn and tcp_max_syn_backlog 100 | # in order to get the desired effect. 101 | tcp-backlog 511 102 | 103 | # Unix socket. 104 | # 105 | # Specify the path for the Unix socket that will be used to listen for 106 | # incoming connections. There is no default, so Redis will not listen 107 | # on a unix socket when not specified. 108 | # 109 | # unixsocket /tmp/redis.sock 110 | # unixsocketperm 700 111 | 112 | # Close the connection after a client is idle for N seconds (0 to disable) 113 | timeout 0 114 | 115 | # TCP keepalive. 116 | # 117 | # If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence 118 | # of communication. This is useful for two reasons: 119 | # 120 | # 1) Detect dead peers. 121 | # 2) Take the connection alive from the point of view of network 122 | # equipment in the middle. 123 | # 124 | # On Linux, the specified value (in seconds) is the period used to send ACKs. 125 | # Note that to close the connection the double of the time is needed. 126 | # On other kernels the period depends on the kernel configuration. 127 | # 128 | # A reasonable value for this option is 300 seconds, which is the new 129 | # Redis default starting with Redis 3.2.1. 130 | tcp-keepalive 300 131 | 132 | ################################# GENERAL ##################################### 133 | 134 | # By default Redis does not run as a daemon. Use 'yes' if you need it. 135 | # Note that Redis will write a pid file in /var/run/redis.pid when daemonized. 136 | daemonize no 137 | 138 | # If you run Redis from upstart or systemd, Redis can interact with your 139 | # supervision tree. Options: 140 | # supervised no - no supervision interaction 141 | # supervised upstart - signal upstart by putting Redis into SIGSTOP mode 142 | # supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET 143 | # supervised auto - detect upstart or systemd method based on 144 | # UPSTART_JOB or NOTIFY_SOCKET environment variables 145 | # Note: these supervision methods only signal "process is ready." 146 | # They do not enable continuous liveness pings back to your supervisor. 147 | supervised no 148 | 149 | # If a pid file is specified, Redis writes it where specified at startup 150 | # and removes it at exit. 151 | # 152 | # When the server runs non daemonized, no pid file is created if none is 153 | # specified in the configuration. When the server is daemonized, the pid file 154 | # is used even if not specified, defaulting to "/var/run/redis.pid". 155 | # 156 | # Creating a pid file is best effort: if Redis is not able to create it 157 | # nothing bad happens, the server will start and run normally. 158 | pidfile /var/run/redis_6379.pid 159 | 160 | # Specify the server verbosity level. 161 | # This can be one of: 162 | # debug (a lot of information, useful for development/testing) 163 | # verbose (many rarely useful info, but not a mess like the debug level) 164 | # notice (moderately verbose, what you want in production probably) 165 | # warning (only very important / critical messages are logged) 166 | loglevel notice 167 | 168 | # Specify the log file name. Also the empty string can be used to force 169 | # Redis to log on the standard output. Note that if you use standard 170 | # output for logging but daemonize, logs will be sent to /dev/null 171 | logfile "" 172 | 173 | # To enable logging to the system logger, just set 'syslog-enabled' to yes, 174 | # and optionally update the other syslog parameters to suit your needs. 175 | # syslog-enabled no 176 | 177 | # Specify the syslog identity. 178 | # syslog-ident redis 179 | 180 | # Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7. 181 | # syslog-facility local0 182 | 183 | # Set the number of databases. The default database is DB 0, you can select 184 | # a different one on a per-connection basis using SELECT where 185 | # dbid is a number between 0 and 'databases'-1 186 | databases 16 187 | 188 | # By default Redis shows an ASCII art logo only when started to log to the 189 | # standard output and if the standard output is a TTY. Basically this means 190 | # that normally a logo is displayed only in interactive sessions. 191 | # 192 | # However it is possible to force the pre-4.0 behavior and always show a 193 | # ASCII art logo in startup logs by setting the following option to yes. 194 | always-show-logo yes 195 | 196 | ################################ SNAPSHOTTING ################################ 197 | # 198 | # Save the DB on disk: 199 | # 200 | # save 201 | # 202 | # Will save the DB if both the given number of seconds and the given 203 | # number of write operations against the DB occurred. 204 | # 205 | # In the example below the behaviour will be to save: 206 | # after 900 sec (15 min) if at least 1 key changed 207 | # after 300 sec (5 min) if at least 10 keys changed 208 | # after 60 sec if at least 10000 keys changed 209 | # 210 | # Note: you can disable saving completely by commenting out all "save" lines. 211 | # 212 | # It is also possible to remove all the previously configured save 213 | # points by adding a save directive with a single empty string argument 214 | # like in the following example: 215 | # 216 | # save "" 217 | 218 | save 900 1 219 | save 300 10 220 | save 60 10000 221 | 222 | # By default Redis will stop accepting writes if RDB snapshots are enabled 223 | # (at least one save point) and the latest background save failed. 224 | # This will make the user aware (in a hard way) that data is not persisting 225 | # on disk properly, otherwise chances are that no one will notice and some 226 | # disaster will happen. 227 | # 228 | # If the background saving process will start working again Redis will 229 | # automatically allow writes again. 230 | # 231 | # However if you have setup your proper monitoring of the Redis server 232 | # and persistence, you may want to disable this feature so that Redis will 233 | # continue to work as usual even if there are problems with disk, 234 | # permissions, and so forth. 235 | stop-writes-on-bgsave-error yes 236 | 237 | # Compress string objects using LZF when dump .rdb databases? 238 | # For default that's set to 'yes' as it's almost always a win. 239 | # If you want to save some CPU in the saving child set it to 'no' but 240 | # the dataset will likely be bigger if you have compressible values or keys. 241 | rdbcompression yes 242 | 243 | # Since version 5 of RDB a CRC64 checksum is placed at the end of the file. 244 | # This makes the format more resistant to corruption but there is a performance 245 | # hit to pay (around 10%) when saving and loading RDB files, so you can disable it 246 | # for maximum performances. 247 | # 248 | # RDB files created with checksum disabled have a checksum of zero that will 249 | # tell the loading code to skip the check. 250 | rdbchecksum yes 251 | 252 | # The filename where to dump the DB 253 | dbfilename dump.rdb 254 | 255 | # The working directory. 256 | # 257 | # The DB will be written inside this directory, with the filename specified 258 | # above using the 'dbfilename' configuration directive. 259 | # 260 | # The Append Only File will also be created inside this directory. 261 | # 262 | # Note that you must specify a directory here, not a file name. 263 | dir ./ 264 | 265 | ################################# REPLICATION ################################# 266 | 267 | # Master-Replica replication. Use replicaof to make a Redis instance a copy of 268 | # another Redis server. A few things to understand ASAP about Redis replication. 269 | # 270 | # +------------------+ +---------------+ 271 | # | Master | ---> | Replica | 272 | # | (receive writes) | | (exact copy) | 273 | # +------------------+ +---------------+ 274 | # 275 | # 1) Redis replication is asynchronous, but you can configure a master to 276 | # stop accepting writes if it appears to be not connected with at least 277 | # a given number of replicas. 278 | # 2) Redis replicas are able to perform a partial resynchronization with the 279 | # master if the replication link is lost for a relatively small amount of 280 | # time. You may want to configure the replication backlog size (see the next 281 | # sections of this file) with a sensible value depending on your needs. 282 | # 3) Replication is automatic and does not need user intervention. After a 283 | # network partition replicas automatically try to reconnect to masters 284 | # and resynchronize with them. 285 | # 286 | # replicaof 287 | 288 | # If the master is password protected (using the "requirepass" configuration 289 | # directive below) it is possible to tell the replica to authenticate before 290 | # starting the replication synchronization process, otherwise the master will 291 | # refuse the replica request. 292 | # 293 | # masterauth 294 | 295 | # When a replica loses its connection with the master, or when the replication 296 | # is still in progress, the replica can act in two different ways: 297 | # 298 | # 1) if replica-serve-stale-data is set to 'yes' (the default) the replica will 299 | # still reply to client requests, possibly with out of date data, or the 300 | # data set may just be empty if this is the first synchronization. 301 | # 302 | # 2) if replica-serve-stale-data is set to 'no' the replica will reply with 303 | # an error "SYNC with master in progress" to all the kind of commands 304 | # but to INFO, replicaOF, AUTH, PING, SHUTDOWN, REPLCONF, ROLE, CONFIG, 305 | # SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBLISH, PUBSUB, 306 | # COMMAND, POST, HOST: and LATENCY. 307 | # 308 | replica-serve-stale-data yes 309 | 310 | # You can configure a replica instance to accept writes or not. Writing against 311 | # a replica instance may be useful to store some ephemeral data (because data 312 | # written on a replica will be easily deleted after resync with the master) but 313 | # may also cause problems if clients are writing to it because of a 314 | # misconfiguration. 315 | # 316 | # Since Redis 2.6 by default replicas are read-only. 317 | # 318 | # Note: read only replicas are not designed to be exposed to untrusted clients 319 | # on the internet. It's just a protection layer against misuse of the instance. 320 | # Still a read only replica exports by default all the administrative commands 321 | # such as CONFIG, DEBUG, and so forth. To a limited extent you can improve 322 | # security of read only replicas using 'rename-command' to shadow all the 323 | # administrative / dangerous commands. 324 | replica-read-only yes 325 | 326 | # Replication SYNC strategy: disk or socket. 327 | # 328 | # ------------------------------------------------------- 329 | # WARNING: DISKLESS REPLICATION IS EXPERIMENTAL CURRENTLY 330 | # ------------------------------------------------------- 331 | # 332 | # New replicas and reconnecting replicas that are not able to continue the replication 333 | # process just receiving differences, need to do what is called a "full 334 | # synchronization". An RDB file is transmitted from the master to the replicas. 335 | # The transmission can happen in two different ways: 336 | # 337 | # 1) Disk-backed: The Redis master creates a new process that writes the RDB 338 | # file on disk. Later the file is transferred by the parent 339 | # process to the replicas incrementally. 340 | # 2) Diskless: The Redis master creates a new process that directly writes the 341 | # RDB file to replica sockets, without touching the disk at all. 342 | # 343 | # With disk-backed replication, while the RDB file is generated, more replicas 344 | # can be queued and served with the RDB file as soon as the current child producing 345 | # the RDB file finishes its work. With diskless replication instead once 346 | # the transfer starts, new replicas arriving will be queued and a new transfer 347 | # will start when the current one terminates. 348 | # 349 | # When diskless replication is used, the master waits a configurable amount of 350 | # time (in seconds) before starting the transfer in the hope that multiple replicas 351 | # will arrive and the transfer can be parallelized. 352 | # 353 | # With slow disks and fast (large bandwidth) networks, diskless replication 354 | # works better. 355 | repl-diskless-sync no 356 | 357 | # When diskless replication is enabled, it is possible to configure the delay 358 | # the server waits in order to spawn the child that transfers the RDB via socket 359 | # to the replicas. 360 | # 361 | # This is important since once the transfer starts, it is not possible to serve 362 | # new replicas arriving, that will be queued for the next RDB transfer, so the server 363 | # waits a delay in order to let more replicas arrive. 364 | # 365 | # The delay is specified in seconds, and by default is 5 seconds. To disable 366 | # it entirely just set it to 0 seconds and the transfer will start ASAP. 367 | repl-diskless-sync-delay 5 368 | 369 | # Replicas send PINGs to server in a predefined interval. It's possible to change 370 | # this interval with the repl_ping_replica_period option. The default value is 10 371 | # seconds. 372 | # 373 | # repl-ping-replica-period 10 374 | 375 | # The following option sets the replication timeout for: 376 | # 377 | # 1) Bulk transfer I/O during SYNC, from the point of view of replica. 378 | # 2) Master timeout from the point of view of replicas (data, pings). 379 | # 3) Replica timeout from the point of view of masters (REPLCONF ACK pings). 380 | # 381 | # It is important to make sure that this value is greater than the value 382 | # specified for repl-ping-replica-period otherwise a timeout will be detected 383 | # every time there is low traffic between the master and the replica. 384 | # 385 | # repl-timeout 60 386 | 387 | # Disable TCP_NODELAY on the replica socket after SYNC? 388 | # 389 | # If you select "yes" Redis will use a smaller number of TCP packets and 390 | # less bandwidth to send data to replicas. But this can add a delay for 391 | # the data to appear on the replica side, up to 40 milliseconds with 392 | # Linux kernels using a default configuration. 393 | # 394 | # If you select "no" the delay for data to appear on the replica side will 395 | # be reduced but more bandwidth will be used for replication. 396 | # 397 | # By default we optimize for low latency, but in very high traffic conditions 398 | # or when the master and replicas are many hops away, turning this to "yes" may 399 | # be a good idea. 400 | repl-disable-tcp-nodelay no 401 | 402 | # Set the replication backlog size. The backlog is a buffer that accumulates 403 | # replica data when replicas are disconnected for some time, so that when a replica 404 | # wants to reconnect again, often a full resync is not needed, but a partial 405 | # resync is enough, just passing the portion of data the replica missed while 406 | # disconnected. 407 | # 408 | # The bigger the replication backlog, the longer the time the replica can be 409 | # disconnected and later be able to perform a partial resynchronization. 410 | # 411 | # The backlog is only allocated once there is at least a replica connected. 412 | # 413 | # repl-backlog-size 1mb 414 | 415 | # After a master has no longer connected replicas for some time, the backlog 416 | # will be freed. The following option configures the amount of seconds that 417 | # need to elapse, starting from the time the last replica disconnected, for 418 | # the backlog buffer to be freed. 419 | # 420 | # Note that replicas never free the backlog for timeout, since they may be 421 | # promoted to masters later, and should be able to correctly "partially 422 | # resynchronize" with the replicas: hence they should always accumulate backlog. 423 | # 424 | # A value of 0 means to never release the backlog. 425 | # 426 | # repl-backlog-ttl 3600 427 | 428 | # The replica priority is an integer number published by Redis in the INFO output. 429 | # It is used by Redis Sentinel in order to select a replica to promote into a 430 | # master if the master is no longer working correctly. 431 | # 432 | # A replica with a low priority number is considered better for promotion, so 433 | # for instance if there are three replicas with priority 10, 100, 25 Sentinel will 434 | # pick the one with priority 10, that is the lowest. 435 | # 436 | # However a special priority of 0 marks the replica as not able to perform the 437 | # role of master, so a replica with priority of 0 will never be selected by 438 | # Redis Sentinel for promotion. 439 | # 440 | # By default the priority is 100. 441 | replica-priority 100 442 | 443 | # It is possible for a master to stop accepting writes if there are less than 444 | # N replicas connected, having a lag less or equal than M seconds. 445 | # 446 | # The N replicas need to be in "online" state. 447 | # 448 | # The lag in seconds, that must be <= the specified value, is calculated from 449 | # the last ping received from the replica, that is usually sent every second. 450 | # 451 | # This option does not GUARANTEE that N replicas will accept the write, but 452 | # will limit the window of exposure for lost writes in case not enough replicas 453 | # are available, to the specified number of seconds. 454 | # 455 | # For example to require at least 3 replicas with a lag <= 10 seconds use: 456 | # 457 | # min-replicas-to-write 3 458 | # min-replicas-max-lag 10 459 | # 460 | # Setting one or the other to 0 disables the feature. 461 | # 462 | # By default min-replicas-to-write is set to 0 (feature disabled) and 463 | # min-replicas-max-lag is set to 10. 464 | 465 | # A Redis master is able to list the address and port of the attached 466 | # replicas in different ways. For example the "INFO replication" section 467 | # offers this information, which is used, among other tools, by 468 | # Redis Sentinel in order to discover replica instances. 469 | # Another place where this info is available is in the output of the 470 | # "ROLE" command of a master. 471 | # 472 | # The listed IP and address normally reported by a replica is obtained 473 | # in the following way: 474 | # 475 | # IP: The address is auto detected by checking the peer address 476 | # of the socket used by the replica to connect with the master. 477 | # 478 | # Port: The port is communicated by the replica during the replication 479 | # handshake, and is normally the port that the replica is using to 480 | # listen for connections. 481 | # 482 | # However when port forwarding or Network Address Translation (NAT) is 483 | # used, the replica may be actually reachable via different IP and port 484 | # pairs. The following two options can be used by a replica in order to 485 | # report to its master a specific set of IP and port, so that both INFO 486 | # and ROLE will report those values. 487 | # 488 | # There is no need to use both the options if you need to override just 489 | # the port or the IP address. 490 | # 491 | # replica-announce-ip 5.5.5.5 492 | # replica-announce-port 1234 493 | 494 | ################################## SECURITY ################################### 495 | 496 | # Require clients to issue AUTH before processing any other 497 | # commands. This might be useful in environments in which you do not trust 498 | # others with access to the host running redis-server. 499 | # 500 | # This should stay commented out for backward compatibility and because most 501 | # people do not need auth (e.g. they run their own servers). 502 | # 503 | # Warning: since Redis is pretty fast an outside user can try up to 504 | # 150k passwords per second against a good box. This means that you should 505 | # use a very strong password otherwise it will be very easy to break. 506 | # 507 | # requirepass foobared 508 | 509 | # Command renaming. 510 | # 511 | # It is possible to change the name of dangerous commands in a shared 512 | # environment. For instance the CONFIG command may be renamed into something 513 | # hard to guess so that it will still be available for internal-use tools 514 | # but not available for general clients. 515 | # 516 | # Example: 517 | # 518 | # rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 519 | # 520 | # It is also possible to completely kill a command by renaming it into 521 | # an empty string: 522 | # 523 | # rename-command CONFIG "" 524 | # 525 | # Please note that changing the name of commands that are logged into the 526 | # AOF file or transmitted to replicas may cause problems. 527 | 528 | ################################### CLIENTS #################################### 529 | 530 | # Set the max number of connected clients at the same time. By default 531 | # this limit is set to 10000 clients, however if the Redis server is not 532 | # able to configure the process file limit to allow for the specified limit 533 | # the max number of allowed clients is set to the current file limit 534 | # minus 32 (as Redis reserves a few file descriptors for internal uses). 535 | # 536 | # Once the limit is reached Redis will close all the new connections sending 537 | # an error 'max number of clients reached'. 538 | # 539 | # maxclients 10000 540 | 541 | ############################## MEMORY MANAGEMENT ################################ 542 | 543 | # Set a memory usage limit to the specified amount of bytes. 544 | # When the memory limit is reached Redis will try to remove keys 545 | # according to the eviction policy selected (see maxmemory-policy). 546 | # 547 | # If Redis can't remove keys according to the policy, or if the policy is 548 | # set to 'noeviction', Redis will start to reply with errors to commands 549 | # that would use more memory, like SET, LPUSH, and so on, and will continue 550 | # to reply to read-only commands like GET. 551 | # 552 | # This option is usually useful when using Redis as an LRU or LFU cache, or to 553 | # set a hard memory limit for an instance (using the 'noeviction' policy). 554 | # 555 | # WARNING: If you have replicas attached to an instance with maxmemory on, 556 | # the size of the output buffers needed to feed the replicas are subtracted 557 | # from the used memory count, so that network problems / resyncs will 558 | # not trigger a loop where keys are evicted, and in turn the output 559 | # buffer of replicas is full with DELs of keys evicted triggering the deletion 560 | # of more keys, and so forth until the database is completely emptied. 561 | # 562 | # In short... if you have replicas attached it is suggested that you set a lower 563 | # limit for maxmemory so that there is some free RAM on the system for replica 564 | # output buffers (but this is not needed if the policy is 'noeviction'). 565 | # 566 | # maxmemory 567 | 568 | # MAXMEMORY POLICY: how Redis will select what to remove when maxmemory 569 | # is reached. You can select among five behaviors: 570 | # 571 | # volatile-lru -> Evict using approximated LRU among the keys with an expire set. 572 | # allkeys-lru -> Evict any key using approximated LRU. 573 | # volatile-lfu -> Evict using approximated LFU among the keys with an expire set. 574 | # allkeys-lfu -> Evict any key using approximated LFU. 575 | # volatile-random -> Remove a random key among the ones with an expire set. 576 | # allkeys-random -> Remove a random key, any key. 577 | # volatile-ttl -> Remove the key with the nearest expire time (minor TTL) 578 | # noeviction -> Don't evict anything, just return an error on write operations. 579 | # 580 | # LRU means Least Recently Used 581 | # LFU means Least Frequently Used 582 | # 583 | # Both LRU, LFU and volatile-ttl are implemented using approximated 584 | # randomized algorithms. 585 | # 586 | # Note: with any of the above policies, Redis will return an error on write 587 | # operations, when there are no suitable keys for eviction. 588 | # 589 | # At the date of writing these commands are: set setnx setex append 590 | # incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd 591 | # sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby 592 | # zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby 593 | # getset mset msetnx exec sort 594 | # 595 | # The default is: 596 | # 597 | # maxmemory-policy noeviction 598 | 599 | # LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated 600 | # algorithms (in order to save memory), so you can tune it for speed or 601 | # accuracy. For default Redis will check five keys and pick the one that was 602 | # used less recently, you can change the sample size using the following 603 | # configuration directive. 604 | # 605 | # The default of 5 produces good enough results. 10 Approximates very closely 606 | # true LRU but costs more CPU. 3 is faster but not very accurate. 607 | # 608 | # maxmemory-samples 5 609 | 610 | # Starting from Redis 5, by default a replica will ignore its maxmemory setting 611 | # (unless it is promoted to master after a failover or manually). It means 612 | # that the eviction of keys will be just handled by the master, sending the 613 | # DEL commands to the replica as keys evict in the master side. 614 | # 615 | # This behavior ensures that masters and replicas stay consistent, and is usually 616 | # what you want, however if your replica is writable, or you want the replica to have 617 | # a different memory setting, and you are sure all the writes performed to the 618 | # replica are idempotent, then you may change this default (but be sure to understand 619 | # what you are doing). 620 | # 621 | # Note that since the replica by default does not evict, it may end using more 622 | # memory than the one set via maxmemory (there are certain buffers that may 623 | # be larger on the replica, or data structures may sometimes take more memory and so 624 | # forth). So make sure you monitor your replicas and make sure they have enough 625 | # memory to never hit a real out-of-memory condition before the master hits 626 | # the configured maxmemory setting. 627 | # 628 | # replica-ignore-maxmemory yes 629 | 630 | ############################# LAZY FREEING #################################### 631 | 632 | # Redis has two primitives to delete keys. One is called DEL and is a blocking 633 | # deletion of the object. It means that the server stops processing new commands 634 | # in order to reclaim all the memory associated with an object in a synchronous 635 | # way. If the key deleted is associated with a small object, the time needed 636 | # in order to execute the DEL command is very small and comparable to most other 637 | # O(1) or O(log_N) commands in Redis. However if the key is associated with an 638 | # aggregated value containing millions of elements, the server can block for 639 | # a long time (even seconds) in order to complete the operation. 640 | # 641 | # For the above reasons Redis also offers non blocking deletion primitives 642 | # such as UNLINK (non blocking DEL) and the ASYNC option of FLUSHALL and 643 | # FLUSHDB commands, in order to reclaim memory in background. Those commands 644 | # are executed in constant time. Another thread will incrementally free the 645 | # object in the background as fast as possible. 646 | # 647 | # DEL, UNLINK and ASYNC option of FLUSHALL and FLUSHDB are user-controlled. 648 | # It's up to the design of the application to understand when it is a good 649 | # idea to use one or the other. However the Redis server sometimes has to 650 | # delete keys or flush the whole database as a side effect of other operations. 651 | # Specifically Redis deletes objects independently of a user call in the 652 | # following scenarios: 653 | # 654 | # 1) On eviction, because of the maxmemory and maxmemory policy configurations, 655 | # in order to make room for new data, without going over the specified 656 | # memory limit. 657 | # 2) Because of expire: when a key with an associated time to live (see the 658 | # EXPIRE command) must be deleted from memory. 659 | # 3) Because of a side effect of a command that stores data on a key that may 660 | # already exist. For example the RENAME command may delete the old key 661 | # content when it is replaced with another one. Similarly SUNIONSTORE 662 | # or SORT with STORE option may delete existing keys. The SET command 663 | # itself removes any old content of the specified key in order to replace 664 | # it with the specified string. 665 | # 4) During replication, when a replica performs a full resynchronization with 666 | # its master, the content of the whole database is removed in order to 667 | # load the RDB file just transferred. 668 | # 669 | # In all the above cases the default is to delete objects in a blocking way, 670 | # like if DEL was called. However you can configure each case specifically 671 | # in order to instead release memory in a non-blocking way like if UNLINK 672 | # was called, using the following configuration directives: 673 | 674 | lazyfree-lazy-eviction no 675 | lazyfree-lazy-expire no 676 | lazyfree-lazy-server-del no 677 | replica-lazy-flush no 678 | 679 | ############################## APPEND ONLY MODE ############################### 680 | 681 | # By default Redis asynchronously dumps the dataset on disk. This mode is 682 | # good enough in many applications, but an issue with the Redis process or 683 | # a power outage may result into a few minutes of writes lost (depending on 684 | # the configured save points). 685 | # 686 | # The Append Only File is an alternative persistence mode that provides 687 | # much better durability. For instance using the default data fsync policy 688 | # (see later in the config file) Redis can lose just one second of writes in a 689 | # dramatic event like a server power outage, or a single write if something 690 | # wrong with the Redis process itself happens, but the operating system is 691 | # still running correctly. 692 | # 693 | # AOF and RDB persistence can be enabled at the same time without problems. 694 | # If the AOF is enabled on startup Redis will load the AOF, that is the file 695 | # with the better durability guarantees. 696 | # 697 | # Please check http://redis.io/topics/persistence for more information. 698 | 699 | appendonly no 700 | 701 | # The name of the append only file (default: "appendonly.aof") 702 | 703 | appendfilename "appendonly.aof" 704 | 705 | # The fsync() call tells the Operating System to actually write data on disk 706 | # instead of waiting for more data in the output buffer. Some OS will really flush 707 | # data on disk, some other OS will just try to do it ASAP. 708 | # 709 | # Redis supports three different modes: 710 | # 711 | # no: don't fsync, just let the OS flush the data when it wants. Faster. 712 | # always: fsync after every write to the append only log. Slow, Safest. 713 | # everysec: fsync only one time every second. Compromise. 714 | # 715 | # The default is "everysec", as that's usually the right compromise between 716 | # speed and data safety. It's up to you to understand if you can relax this to 717 | # "no" that will let the operating system flush the output buffer when 718 | # it wants, for better performances (but if you can live with the idea of 719 | # some data loss consider the default persistence mode that's snapshotting), 720 | # or on the contrary, use "always" that's very slow but a bit safer than 721 | # everysec. 722 | # 723 | # More details please check the following article: 724 | # http://antirez.com/post/redis-persistence-demystified.html 725 | # 726 | # If unsure, use "everysec". 727 | 728 | # appendfsync always 729 | appendfsync everysec 730 | # appendfsync no 731 | 732 | # When the AOF fsync policy is set to always or everysec, and a background 733 | # saving process (a background save or AOF log background rewriting) is 734 | # performing a lot of I/O against the disk, in some Linux configurations 735 | # Redis may block too long on the fsync() call. Note that there is no fix for 736 | # this currently, as even performing fsync in a different thread will block 737 | # our synchronous write(2) call. 738 | # 739 | # In order to mitigate this problem it's possible to use the following option 740 | # that will prevent fsync() from being called in the main process while a 741 | # BGSAVE or BGREWRITEAOF is in progress. 742 | # 743 | # This means that while another child is saving, the durability of Redis is 744 | # the same as "appendfsync none". In practical terms, this means that it is 745 | # possible to lose up to 30 seconds of log in the worst scenario (with the 746 | # default Linux settings). 747 | # 748 | # If you have latency problems turn this to "yes". Otherwise leave it as 749 | # "no" that is the safest pick from the point of view of durability. 750 | 751 | no-appendfsync-on-rewrite no 752 | 753 | # Automatic rewrite of the append only file. 754 | # Redis is able to automatically rewrite the log file implicitly calling 755 | # BGREWRITEAOF when the AOF log size grows by the specified percentage. 756 | # 757 | # This is how it works: Redis remembers the size of the AOF file after the 758 | # latest rewrite (if no rewrite has happened since the restart, the size of 759 | # the AOF at startup is used). 760 | # 761 | # This base size is compared to the current size. If the current size is 762 | # bigger than the specified percentage, the rewrite is triggered. Also 763 | # you need to specify a minimal size for the AOF file to be rewritten, this 764 | # is useful to avoid rewriting the AOF file even if the percentage increase 765 | # is reached but it is still pretty small. 766 | # 767 | # Specify a percentage of zero in order to disable the automatic AOF 768 | # rewrite feature. 769 | 770 | auto-aof-rewrite-percentage 100 771 | auto-aof-rewrite-min-size 64mb 772 | 773 | # An AOF file may be found to be truncated at the end during the Redis 774 | # startup process, when the AOF data gets loaded back into memory. 775 | # This may happen when the system where Redis is running 776 | # crashes, especially when an ext4 filesystem is mounted without the 777 | # data=ordered option (however this can't happen when Redis itself 778 | # crashes or aborts but the operating system still works correctly). 779 | # 780 | # Redis can either exit with an error when this happens, or load as much 781 | # data as possible (the default now) and start if the AOF file is found 782 | # to be truncated at the end. The following option controls this behavior. 783 | # 784 | # If aof-load-truncated is set to yes, a truncated AOF file is loaded and 785 | # the Redis server starts emitting a log to inform the user of the event. 786 | # Otherwise if the option is set to no, the server aborts with an error 787 | # and refuses to start. When the option is set to no, the user requires 788 | # to fix the AOF file using the "redis-check-aof" utility before to restart 789 | # the server. 790 | # 791 | # Note that if the AOF file will be found to be corrupted in the middle 792 | # the server will still exit with an error. This option only applies when 793 | # Redis will try to read more data from the AOF file but not enough bytes 794 | # will be found. 795 | aof-load-truncated yes 796 | 797 | # When rewriting the AOF file, Redis is able to use an RDB preamble in the 798 | # AOF file for faster rewrites and recoveries. When this option is turned 799 | # on the rewritten AOF file is composed of two different stanzas: 800 | # 801 | # [RDB file][AOF tail] 802 | # 803 | # When loading Redis recognizes that the AOF file starts with the "REDIS" 804 | # string and loads the prefixed RDB file, and continues loading the AOF 805 | # tail. 806 | aof-use-rdb-preamble yes 807 | 808 | ################################ LUA SCRIPTING ############################### 809 | 810 | # Max execution time of a Lua script in milliseconds. 811 | # 812 | # If the maximum execution time is reached Redis will log that a script is 813 | # still in execution after the maximum allowed time and will start to 814 | # reply to queries with an error. 815 | # 816 | # When a long running script exceeds the maximum execution time only the 817 | # SCRIPT KILL and SHUTDOWN NOSAVE commands are available. The first can be 818 | # used to stop a script that did not yet called write commands. The second 819 | # is the only way to shut down the server in the case a write command was 820 | # already issued by the script but the user doesn't want to wait for the natural 821 | # termination of the script. 822 | # 823 | # Set it to 0 or a negative value for unlimited execution without warnings. 824 | lua-time-limit 5000 825 | 826 | ################################ REDIS CLUSTER ############################### 827 | # 828 | # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 829 | # WARNING EXPERIMENTAL: Redis Cluster is considered to be stable code, however 830 | # in order to mark it as "mature" we need to wait for a non trivial percentage 831 | # of users to deploy it in production. 832 | # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 833 | # 834 | # Normal Redis instances can't be part of a Redis Cluster; only nodes that are 835 | # started as cluster nodes can. In order to start a Redis instance as a 836 | # cluster node enable the cluster support uncommenting the following: 837 | # 838 | # cluster-enabled yes 839 | 840 | # Every cluster node has a cluster configuration file. This file is not 841 | # intended to be edited by hand. It is created and updated by Redis nodes. 842 | # Every Redis Cluster node requires a different cluster configuration file. 843 | # Make sure that instances running in the same system do not have 844 | # overlapping cluster configuration file names. 845 | # 846 | # cluster-config-file nodes-6379.conf 847 | 848 | # Cluster node timeout is the amount of milliseconds a node must be unreachable 849 | # for it to be considered in failure state. 850 | # Most other internal time limits are multiple of the node timeout. 851 | # 852 | # cluster-node-timeout 15000 853 | 854 | # A replica of a failing master will avoid to start a failover if its data 855 | # looks too old. 856 | # 857 | # There is no simple way for a replica to actually have an exact measure of 858 | # its "data age", so the following two checks are performed: 859 | # 860 | # 1) If there are multiple replicas able to failover, they exchange messages 861 | # in order to try to give an advantage to the replica with the best 862 | # replication offset (more data from the master processed). 863 | # Replicas will try to get their rank by offset, and apply to the start 864 | # of the failover a delay proportional to their rank. 865 | # 866 | # 2) Every single replica computes the time of the last interaction with 867 | # its master. This can be the last ping or command received (if the master 868 | # is still in the "connected" state), or the time that elapsed since the 869 | # disconnection with the master (if the replication link is currently down). 870 | # If the last interaction is too old, the replica will not try to failover 871 | # at all. 872 | # 873 | # The point "2" can be tuned by user. Specifically a replica will not perform 874 | # the failover if, since the last interaction with the master, the time 875 | # elapsed is greater than: 876 | # 877 | # (node-timeout * replica-validity-factor) + repl-ping-replica-period 878 | # 879 | # So for example if node-timeout is 30 seconds, and the replica-validity-factor 880 | # is 10, and assuming a default repl-ping-replica-period of 10 seconds, the 881 | # replica will not try to failover if it was not able to talk with the master 882 | # for longer than 310 seconds. 883 | # 884 | # A large replica-validity-factor may allow replicas with too old data to failover 885 | # a master, while a too small value may prevent the cluster from being able to 886 | # elect a replica at all. 887 | # 888 | # For maximum availability, it is possible to set the replica-validity-factor 889 | # to a value of 0, which means, that replicas will always try to failover the 890 | # master regardless of the last time they interacted with the master. 891 | # (However they'll always try to apply a delay proportional to their 892 | # offset rank). 893 | # 894 | # Zero is the only value able to guarantee that when all the partitions heal 895 | # the cluster will always be able to continue. 896 | # 897 | # cluster-replica-validity-factor 10 898 | 899 | # Cluster replicas are able to migrate to orphaned masters, that are masters 900 | # that are left without working replicas. This improves the cluster ability 901 | # to resist to failures as otherwise an orphaned master can't be failed over 902 | # in case of failure if it has no working replicas. 903 | # 904 | # Replicas migrate to orphaned masters only if there are still at least a 905 | # given number of other working replicas for their old master. This number 906 | # is the "migration barrier". A migration barrier of 1 means that a replica 907 | # will migrate only if there is at least 1 other working replica for its master 908 | # and so forth. It usually reflects the number of replicas you want for every 909 | # master in your cluster. 910 | # 911 | # Default is 1 (replicas migrate only if their masters remain with at least 912 | # one replica). To disable migration just set it to a very large value. 913 | # A value of 0 can be set but is useful only for debugging and dangerous 914 | # in production. 915 | # 916 | # cluster-migration-barrier 1 917 | 918 | # By default Redis Cluster nodes stop accepting queries if they detect there 919 | # is at least an hash slot uncovered (no available node is serving it). 920 | # This way if the cluster is partially down (for example a range of hash slots 921 | # are no longer covered) all the cluster becomes, eventually, unavailable. 922 | # It automatically returns available as soon as all the slots are covered again. 923 | # 924 | # However sometimes you want the subset of the cluster which is working, 925 | # to continue to accept queries for the part of the key space that is still 926 | # covered. In order to do so, just set the cluster-require-full-coverage 927 | # option to no. 928 | # 929 | # cluster-require-full-coverage yes 930 | 931 | # This option, when set to yes, prevents replicas from trying to failover its 932 | # master during master failures. However the master can still perform a 933 | # manual failover, if forced to do so. 934 | # 935 | # This is useful in different scenarios, especially in the case of multiple 936 | # data center operations, where we want one side to never be promoted if not 937 | # in the case of a total DC failure. 938 | # 939 | # cluster-replica-no-failover no 940 | 941 | # In order to setup your cluster make sure to read the documentation 942 | # available at http://redis.io web site. 943 | 944 | ########################## CLUSTER DOCKER/NAT support ######################## 945 | 946 | # In certain deployments, Redis Cluster nodes address discovery fails, because 947 | # addresses are NAT-ted or because ports are forwarded (the typical case is 948 | # Docker and other containers). 949 | # 950 | # In order to make Redis Cluster working in such environments, a static 951 | # configuration where each node knows its public address is needed. The 952 | # following two options are used for this scope, and are: 953 | # 954 | # * cluster-announce-ip 955 | # * cluster-announce-port 956 | # * cluster-announce-bus-port 957 | # 958 | # Each instruct the node about its address, client port, and cluster message 959 | # bus port. The information is then published in the header of the bus packets 960 | # so that other nodes will be able to correctly map the address of the node 961 | # publishing the information. 962 | # 963 | # If the above options are not used, the normal Redis Cluster auto-detection 964 | # will be used instead. 965 | # 966 | # Note that when remapped, the bus port may not be at the fixed offset of 967 | # clients port + 10000, so you can specify any port and bus-port depending 968 | # on how they get remapped. If the bus-port is not set, a fixed offset of 969 | # 10000 will be used as usually. 970 | # 971 | # Example: 972 | # 973 | # cluster-announce-ip 10.1.1.5 974 | # cluster-announce-port 6379 975 | # cluster-announce-bus-port 6380 976 | 977 | ################################## SLOW LOG ################################### 978 | 979 | # The Redis Slow Log is a system to log queries that exceeded a specified 980 | # execution time. The execution time does not include the I/O operations 981 | # like talking with the client, sending the reply and so forth, 982 | # but just the time needed to actually execute the command (this is the only 983 | # stage of command execution where the thread is blocked and can not serve 984 | # other requests in the meantime). 985 | # 986 | # You can configure the slow log with two parameters: one tells Redis 987 | # what is the execution time, in microseconds, to exceed in order for the 988 | # command to get logged, and the other parameter is the length of the 989 | # slow log. When a new command is logged the oldest one is removed from the 990 | # queue of logged commands. 991 | 992 | # The following time is expressed in microseconds, so 1000000 is equivalent 993 | # to one second. Note that a negative number disables the slow log, while 994 | # a value of zero forces the logging of every command. 995 | slowlog-log-slower-than 10000 996 | 997 | # There is no limit to this length. Just be aware that it will consume memory. 998 | # You can reclaim memory used by the slow log with SLOWLOG RESET. 999 | slowlog-max-len 128 1000 | 1001 | ################################ LATENCY MONITOR ############################## 1002 | 1003 | # The Redis latency monitoring subsystem samples different operations 1004 | # at runtime in order to collect data related to possible sources of 1005 | # latency of a Redis instance. 1006 | # 1007 | # Via the LATENCY command this information is available to the user that can 1008 | # print graphs and obtain reports. 1009 | # 1010 | # The system only logs operations that were performed in a time equal or 1011 | # greater than the amount of milliseconds specified via the 1012 | # latency-monitor-threshold configuration directive. When its value is set 1013 | # to zero, the latency monitor is turned off. 1014 | # 1015 | # By default latency monitoring is disabled since it is mostly not needed 1016 | # if you don't have latency issues, and collecting data has a performance 1017 | # impact, that while very small, can be measured under big load. Latency 1018 | # monitoring can easily be enabled at runtime using the command 1019 | # "CONFIG SET latency-monitor-threshold " if needed. 1020 | latency-monitor-threshold 0 1021 | 1022 | ############################# EVENT NOTIFICATION ############################## 1023 | 1024 | # Redis can notify Pub/Sub clients about events happening in the key space. 1025 | # This feature is documented at http://redis.io/topics/notifications 1026 | # 1027 | # For instance if keyspace events notification is enabled, and a client 1028 | # performs a DEL operation on key "foo" stored in the Database 0, two 1029 | # messages will be published via Pub/Sub: 1030 | # 1031 | # PUBLISH __keyspace@0__:foo del 1032 | # PUBLISH __keyevent@0__:del foo 1033 | # 1034 | # It is possible to select the events that Redis will notify among a set 1035 | # of classes. Every class is identified by a single character: 1036 | # 1037 | # K Keyspace events, published with __keyspace@__ prefix. 1038 | # E Keyevent events, published with __keyevent@__ prefix. 1039 | # g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... 1040 | # $ String commands 1041 | # l List commands 1042 | # s Set commands 1043 | # h Hash commands 1044 | # z Sorted set commands 1045 | # x Expired events (events generated every time a key expires) 1046 | # e Evicted events (events generated when a key is evicted for maxmemory) 1047 | # A Alias for g$lshzxe, so that the "AKE" string means all the events. 1048 | # 1049 | # The "notify-keyspace-events" takes as argument a string that is composed 1050 | # of zero or multiple characters. The empty string means that notifications 1051 | # are disabled. 1052 | # 1053 | # Example: to enable list and generic events, from the point of view of the 1054 | # event name, use: 1055 | # 1056 | # notify-keyspace-events Elg 1057 | # 1058 | # Example 2: to get the stream of the expired keys subscribing to channel 1059 | # name __keyevent@0__:expired use: 1060 | # 1061 | # notify-keyspace-events Ex 1062 | # 1063 | # By default all notifications are disabled because most users don't need 1064 | # this feature and the feature has some overhead. Note that if you don't 1065 | # specify at least one of K or E, no events will be delivered. 1066 | notify-keyspace-events "" 1067 | 1068 | ############################### ADVANCED CONFIG ############################### 1069 | 1070 | # Hashes are encoded using a memory efficient data structure when they have a 1071 | # small number of entries, and the biggest entry does not exceed a given 1072 | # threshold. These thresholds can be configured using the following directives. 1073 | hash-max-ziplist-entries 512 1074 | hash-max-ziplist-value 64 1075 | 1076 | # Lists are also encoded in a special way to save a lot of space. 1077 | # The number of entries allowed per internal list node can be specified 1078 | # as a fixed maximum size or a maximum number of elements. 1079 | # For a fixed maximum size, use -5 through -1, meaning: 1080 | # -5: max size: 64 Kb <-- not recommended for normal workloads 1081 | # -4: max size: 32 Kb <-- not recommended 1082 | # -3: max size: 16 Kb <-- probably not recommended 1083 | # -2: max size: 8 Kb <-- good 1084 | # -1: max size: 4 Kb <-- good 1085 | # Positive numbers mean store up to _exactly_ that number of elements 1086 | # per list node. 1087 | # The highest performing option is usually -2 (8 Kb size) or -1 (4 Kb size), 1088 | # but if your use case is unique, adjust the settings as necessary. 1089 | list-max-ziplist-size -2 1090 | 1091 | # Lists may also be compressed. 1092 | # Compress depth is the number of quicklist ziplist nodes from *each* side of 1093 | # the list to *exclude* from compression. The head and tail of the list 1094 | # are always uncompressed for fast push/pop operations. Settings are: 1095 | # 0: disable all list compression 1096 | # 1: depth 1 means "don't start compressing until after 1 node into the list, 1097 | # going from either the head or tail" 1098 | # So: [head]->node->node->...->node->[tail] 1099 | # [head], [tail] will always be uncompressed; inner nodes will compress. 1100 | # 2: [head]->[next]->node->node->...->node->[prev]->[tail] 1101 | # 2 here means: don't compress head or head->next or tail->prev or tail, 1102 | # but compress all nodes between them. 1103 | # 3: [head]->[next]->[next]->node->node->...->node->[prev]->[prev]->[tail] 1104 | # etc. 1105 | list-compress-depth 0 1106 | 1107 | # Sets have a special encoding in just one case: when a set is composed 1108 | # of just strings that happen to be integers in radix 10 in the range 1109 | # of 64 bit signed integers. 1110 | # The following configuration setting sets the limit in the size of the 1111 | # set in order to use this special memory saving encoding. 1112 | set-max-intset-entries 512 1113 | 1114 | # Similarly to hashes and lists, sorted sets are also specially encoded in 1115 | # order to save a lot of space. This encoding is only used when the length and 1116 | # elements of a sorted set are below the following limits: 1117 | zset-max-ziplist-entries 128 1118 | zset-max-ziplist-value 64 1119 | 1120 | # HyperLogLog sparse representation bytes limit. The limit includes the 1121 | # 16 bytes header. When an HyperLogLog using the sparse representation crosses 1122 | # this limit, it is converted into the dense representation. 1123 | # 1124 | # A value greater than 16000 is totally useless, since at that point the 1125 | # dense representation is more memory efficient. 1126 | # 1127 | # The suggested value is ~ 3000 in order to have the benefits of 1128 | # the space efficient encoding without slowing down too much PFADD, 1129 | # which is O(N) with the sparse encoding. The value can be raised to 1130 | # ~ 10000 when CPU is not a concern, but space is, and the data set is 1131 | # composed of many HyperLogLogs with cardinality in the 0 - 15000 range. 1132 | hll-sparse-max-bytes 3000 1133 | 1134 | # Streams macro node max size / items. The stream data structure is a radix 1135 | # tree of big nodes that encode multiple items inside. Using this configuration 1136 | # it is possible to configure how big a single node can be in bytes, and the 1137 | # maximum number of items it may contain before switching to a new node when 1138 | # appending new stream entries. If any of the following settings are set to 1139 | # zero, the limit is ignored, so for instance it is possible to set just a 1140 | # max entires limit by setting max-bytes to 0 and max-entries to the desired 1141 | # value. 1142 | stream-node-max-bytes 4096 1143 | stream-node-max-entries 100 1144 | 1145 | # Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in 1146 | # order to help rehashing the main Redis hash table (the one mapping top-level 1147 | # keys to values). The hash table implementation Redis uses (see dict.c) 1148 | # performs a lazy rehashing: the more operation you run into a hash table 1149 | # that is rehashing, the more rehashing "steps" are performed, so if the 1150 | # server is idle the rehashing is never complete and some more memory is used 1151 | # by the hash table. 1152 | # 1153 | # The default is to use this millisecond 10 times every second in order to 1154 | # actively rehash the main dictionaries, freeing memory when possible. 1155 | # 1156 | # If unsure: 1157 | # use "activerehashing no" if you have hard latency requirements and it is 1158 | # not a good thing in your environment that Redis can reply from time to time 1159 | # to queries with 2 milliseconds delay. 1160 | # 1161 | # use "activerehashing yes" if you don't have such hard requirements but 1162 | # want to free memory asap when possible. 1163 | activerehashing yes 1164 | 1165 | # The client output buffer limits can be used to force disconnection of clients 1166 | # that are not reading data from the server fast enough for some reason (a 1167 | # common reason is that a Pub/Sub client can't consume messages as fast as the 1168 | # publisher can produce them). 1169 | # 1170 | # The limit can be set differently for the three different classes of clients: 1171 | # 1172 | # normal -> normal clients including MONITOR clients 1173 | # replica -> replica clients 1174 | # pubsub -> clients subscribed to at least one pubsub channel or pattern 1175 | # 1176 | # The syntax of every client-output-buffer-limit directive is the following: 1177 | # 1178 | # client-output-buffer-limit 1179 | # 1180 | # A client is immediately disconnected once the hard limit is reached, or if 1181 | # the soft limit is reached and remains reached for the specified number of 1182 | # seconds (continuously). 1183 | # So for instance if the hard limit is 32 megabytes and the soft limit is 1184 | # 16 megabytes / 10 seconds, the client will get disconnected immediately 1185 | # if the size of the output buffers reach 32 megabytes, but will also get 1186 | # disconnected if the client reaches 16 megabytes and continuously overcomes 1187 | # the limit for 10 seconds. 1188 | # 1189 | # By default normal clients are not limited because they don't receive data 1190 | # without asking (in a push way), but just after a request, so only 1191 | # asynchronous clients may create a scenario where data is requested faster 1192 | # than it can read. 1193 | # 1194 | # Instead there is a default limit for pubsub and replica clients, since 1195 | # subscribers and replicas receive data in a push fashion. 1196 | # 1197 | # Both the hard or the soft limit can be disabled by setting them to zero. 1198 | client-output-buffer-limit normal 0 0 0 1199 | client-output-buffer-limit replica 256mb 64mb 60 1200 | client-output-buffer-limit pubsub 32mb 8mb 60 1201 | 1202 | # Client query buffers accumulate new commands. They are limited to a fixed 1203 | # amount by default in order to avoid that a protocol desynchronization (for 1204 | # instance due to a bug in the client) will lead to unbound memory usage in 1205 | # the query buffer. However you can configure it here if you have very special 1206 | # needs, such us huge multi/exec requests or alike. 1207 | # 1208 | # client-query-buffer-limit 1gb 1209 | 1210 | # In the Redis protocol, bulk requests, that are, elements representing single 1211 | # strings, are normally limited ot 512 mb. However you can change this limit 1212 | # here. 1213 | # 1214 | # proto-max-bulk-len 512mb 1215 | 1216 | # Redis calls an internal function to perform many background tasks, like 1217 | # closing connections of clients in timeout, purging expired keys that are 1218 | # never requested, and so forth. 1219 | # 1220 | # Not all tasks are performed with the same frequency, but Redis checks for 1221 | # tasks to perform according to the specified "hz" value. 1222 | # 1223 | # By default "hz" is set to 10. Raising the value will use more CPU when 1224 | # Redis is idle, but at the same time will make Redis more responsive when 1225 | # there are many keys expiring at the same time, and timeouts may be 1226 | # handled with more precision. 1227 | # 1228 | # The range is between 1 and 500, however a value over 100 is usually not 1229 | # a good idea. Most users should use the default of 10 and raise this up to 1230 | # 100 only in environments where very low latency is required. 1231 | hz 10 1232 | 1233 | # Normally it is useful to have an HZ value which is proportional to the 1234 | # number of clients connected. This is useful in order, for instance, to 1235 | # avoid too many clients are processed for each background task invocation 1236 | # in order to avoid latency spikes. 1237 | # 1238 | # Since the default HZ value by default is conservatively set to 10, Redis 1239 | # offers, and enables by default, the ability to use an adaptive HZ value 1240 | # which will temporary raise when there are many connected clients. 1241 | # 1242 | # When dynamic HZ is enabled, the actual configured HZ will be used as 1243 | # as a baseline, but multiples of the configured HZ value will be actually 1244 | # used as needed once more clients are connected. In this way an idle 1245 | # instance will use very little CPU time while a busy instance will be 1246 | # more responsive. 1247 | dynamic-hz yes 1248 | 1249 | # When a child rewrites the AOF file, if the following option is enabled 1250 | # the file will be fsync-ed every 32 MB of data generated. This is useful 1251 | # in order to commit the file to the disk more incrementally and avoid 1252 | # big latency spikes. 1253 | aof-rewrite-incremental-fsync yes 1254 | 1255 | # When redis saves RDB file, if the following option is enabled 1256 | # the file will be fsync-ed every 32 MB of data generated. This is useful 1257 | # in order to commit the file to the disk more incrementally and avoid 1258 | # big latency spikes. 1259 | rdb-save-incremental-fsync yes 1260 | 1261 | # Redis LFU eviction (see maxmemory setting) can be tuned. However it is a good 1262 | # idea to start with the default settings and only change them after investigating 1263 | # how to improve the performances and how the keys LFU change over time, which 1264 | # is possible to inspect via the OBJECT FREQ command. 1265 | # 1266 | # There are two tunable parameters in the Redis LFU implementation: the 1267 | # counter logarithm factor and the counter decay time. It is important to 1268 | # understand what the two parameters mean before changing them. 1269 | # 1270 | # The LFU counter is just 8 bits per key, it's maximum value is 255, so Redis 1271 | # uses a probabilistic increment with logarithmic behavior. Given the value 1272 | # of the old counter, when a key is accessed, the counter is incremented in 1273 | # this way: 1274 | # 1275 | # 1. A random number R between 0 and 1 is extracted. 1276 | # 2. A probability P is calculated as 1/(old_value*lfu_log_factor+1). 1277 | # 3. The counter is incremented only if R < P. 1278 | # 1279 | # The default lfu-log-factor is 10. This is a table of how the frequency 1280 | # counter changes with a different number of accesses with different 1281 | # logarithmic factors: 1282 | # 1283 | # +--------+------------+------------+------------+------------+------------+ 1284 | # | factor | 100 hits | 1000 hits | 100K hits | 1M hits | 10M hits | 1285 | # +--------+------------+------------+------------+------------+------------+ 1286 | # | 0 | 104 | 255 | 255 | 255 | 255 | 1287 | # +--------+------------+------------+------------+------------+------------+ 1288 | # | 1 | 18 | 49 | 255 | 255 | 255 | 1289 | # +--------+------------+------------+------------+------------+------------+ 1290 | # | 10 | 10 | 18 | 142 | 255 | 255 | 1291 | # +--------+------------+------------+------------+------------+------------+ 1292 | # | 100 | 8 | 11 | 49 | 143 | 255 | 1293 | # +--------+------------+------------+------------+------------+------------+ 1294 | # 1295 | # NOTE: The above table was obtained by running the following commands: 1296 | # 1297 | # redis-benchmark -n 1000000 incr foo 1298 | # redis-cli object freq foo 1299 | # 1300 | # NOTE 2: The counter initial value is 5 in order to give new objects a chance 1301 | # to accumulate hits. 1302 | # 1303 | # The counter decay time is the time, in minutes, that must elapse in order 1304 | # for the key counter to be divided by two (or decremented if it has a value 1305 | # less <= 10). 1306 | # 1307 | # The default value for the lfu-decay-time is 1. A Special value of 0 means to 1308 | # decay the counter every time it happens to be scanned. 1309 | # 1310 | # lfu-log-factor 10 1311 | # lfu-decay-time 1 1312 | 1313 | ########################### ACTIVE DEFRAGMENTATION ####################### 1314 | # 1315 | # WARNING THIS FEATURE IS EXPERIMENTAL. However it was stress tested 1316 | # even in production and manually tested by multiple engineers for some 1317 | # time. 1318 | # 1319 | # What is active defragmentation? 1320 | # ------------------------------- 1321 | # 1322 | # Active (online) defragmentation allows a Redis server to compact the 1323 | # spaces left between small allocations and deallocations of data in memory, 1324 | # thus allowing to reclaim back memory. 1325 | # 1326 | # Fragmentation is a natural process that happens with every allocator (but 1327 | # less so with Jemalloc, fortunately) and certain workloads. Normally a server 1328 | # restart is needed in order to lower the fragmentation, or at least to flush 1329 | # away all the data and create it again. However thanks to this feature 1330 | # implemented by Oran Agra for Redis 4.0 this process can happen at runtime 1331 | # in an "hot" way, while the server is running. 1332 | # 1333 | # Basically when the fragmentation is over a certain level (see the 1334 | # configuration options below) Redis will start to create new copies of the 1335 | # values in contiguous memory regions by exploiting certain specific Jemalloc 1336 | # features (in order to understand if an allocation is causing fragmentation 1337 | # and to allocate it in a better place), and at the same time, will release the 1338 | # old copies of the data. This process, repeated incrementally for all the keys 1339 | # will cause the fragmentation to drop back to normal values. 1340 | # 1341 | # Important things to understand: 1342 | # 1343 | # 1. This feature is disabled by default, and only works if you compiled Redis 1344 | # to use the copy of Jemalloc we ship with the source code of Redis. 1345 | # This is the default with Linux builds. 1346 | # 1347 | # 2. You never need to enable this feature if you don't have fragmentation 1348 | # issues. 1349 | # 1350 | # 3. Once you experience fragmentation, you can enable this feature when 1351 | # needed with the command "CONFIG SET activedefrag yes". 1352 | # 1353 | # The configuration parameters are able to fine tune the behavior of the 1354 | # defragmentation process. If you are not sure about what they mean it is 1355 | # a good idea to leave the defaults untouched. 1356 | 1357 | # Enabled active defragmentation 1358 | # activedefrag yes 1359 | 1360 | # Minimum amount of fragmentation waste to start active defrag 1361 | # active-defrag-ignore-bytes 100mb 1362 | 1363 | # Minimum percentage of fragmentation to start active defrag 1364 | # active-defrag-threshold-lower 10 1365 | 1366 | # Maximum percentage of fragmentation at which we use maximum effort 1367 | # active-defrag-threshold-upper 100 1368 | 1369 | # Minimal effort for defrag in CPU percentage 1370 | # active-defrag-cycle-min 5 1371 | 1372 | # Maximal effort for defrag in CPU percentage 1373 | # active-defrag-cycle-max 75 1374 | 1375 | # Maximum number of set/hash/zset/list fields that will be processed from 1376 | # the main dictionary scan 1377 | # active-defrag-max-scan-fields 1000 1378 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | patreon: rodion_arr 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: "/api" 5 | schedule: 6 | interval: weekly 7 | time: "03:00" 8 | open-pull-requests-limit: 100 9 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - main 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | matrix: 12 | node-version: [22.x, 20.x] 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: Use Node.js ${{ matrix.node-version }} 16 | uses: actions/setup-node@v1 17 | with: 18 | node-version: ${{ matrix.node-version }} 19 | - name: test 20 | run: | 21 | cd api 22 | npm ci 23 | npm run test:cov 24 | - name: npm run build 25 | run: | 26 | cd api 27 | npm run build 28 | - name: Upload coverage to Codecov 29 | uses: codecov/codecov-action@v1 30 | with: 31 | token: ${{ secrets.CODECOV_TOKEN }} 32 | file: ./api/coverage/clover.xml 33 | flags: unittests 34 | name: lib 35 | fail_ci_if_error: false 36 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | lts/* 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nest.js starter kit 2 | 3 | [![Test](https://github.com/rodion-arr/nestjs-starter-kit/actions/workflows/test.yml/badge.svg)](https://github.com/rodion-arr/nestjs-starter-kit/actions/workflows/test.yml) [![codecov](https://codecov.io/gh/rodion-arr/nestjs-starter-kit/branch/main/graph/badge.svg?token=NGR0C23CMW)](https://codecov.io/gh/rodion-arr/nestjs-starter-kit) 4 | 5 | This is a starter kit for typical Nest.js REST API project. 6 | 7 | ## Motivation 8 | 9 | The main goal of this project is to provide fully functional [Nest.js](https://nestjs.com/) app which can be used as a started kit for creating your own REST APIs. 10 | 11 | Usually it is not enough to just run `$ nest new project` and start writing required business logic. Nest.js provides a minimal application out of the box with only one controller and service. In most cases it is required to pull and setup a bunch of additional packages from Nest.js ecosystem like `typeorm`, `passport`, `cache-manager`, DTO validators etc. 12 | 13 | This repo provides an already configured REST API project with commonly used Nest.js packages (full list below) so you can just copy it and start writing your business logic and not waste your time for boilerplate configuration. 14 | 15 | ## Features 16 | 17 | - [Dockerized local development](#dockerized-local-development) 18 | - [Configuration via ENV variables](#configuration-via-env-variables) 19 | - [Validation via DTO](#validation-via-dto) 20 | - [DB migrations](#db-migrations) 21 | - [Redis cache](#redis-cache) 22 | - [JWT auth with passport.js](#jwt-auth-with-passportjs) 23 | - [Logger with TraceID generation](#logger-with-trace-id-generation) 24 | - [Graceful shutdown](#graceful-shutdown) 25 | - [Automatic APIs documentation with Swagger](#automatic-apis-documentation-with-swagger) 26 | - [Sending emails](#e-mail-service-with-local-mail-trap) 27 | - [Unit tests](#unit-tests) 28 | - [Health check](#health-check) 29 | 30 | ### Dockerized local development 31 | 32 | You are getting fully functional docker environment for development with Postgres DB, Redis and utility services such as local SMTP server. You can spin-up all server dependencies with only 1 command without need of setting up DB and Redis servers manually. 33 | 34 | Check out [.docker-node-api](./.docker-node-api) folder and [installation guide](#installation) for more details. 35 | 36 | ### Configuration via ENV variables 37 | 38 | According to [12 factor app](https://12factor.net/config) - it is recommended to store application config in Environment Variables. This technique allows you to build the bundle once and deploy it to multiple target server (e.g. QA, Staging, Prod) without code modifications. Each target environment will have different configuration values which application retrieves from environment variables. 39 | 40 | This project provides a set of config values out of the box e.g. for connecting to DB and Cache server. Check out [app.module.ts](./api/src/app.module.ts#L14) and [configuration.ts](./api/src/services/app-config/configuration.ts) for more details. 41 | 42 | ### Validation via DTO 43 | 44 | Global [ValidationPipeline](./api/src/main.ts) enabled and requests to APIs are validated via [DTOs](./api/src/user/dto). 45 | 46 | ### DB migrations 47 | 48 | `TypeORM` DB migrations are already set up for you in [./api/src/db/migrations](./api/src/db/migrations) folder. 49 | 50 | To generate new migration run: 51 | 52 | ```console 53 | npm run migrations:new -- src/db/migrations/Roles 54 | ``` 55 | 56 | To apply migrations run: 57 | 58 | ```console 59 | npm run migrations:up 60 | ``` 61 | 62 | To revert migrations run: 63 | 64 | ```console 65 | npm run migrations:revert 66 | ``` 67 | 68 | ### Redis cache 69 | 70 | [cache-manager](https://github.com/BryanDonovan/node-cache-manager#readme) package with Redis store is available in [app-cache.module.ts](./api/src/app-cache/app-cache.module.ts). 71 | 72 | So it is possible to use [`CacheInterceptor`](./api/src/user/user.controller.ts#L50) above you controller methods or classes: 73 | 74 | ```typescript 75 | @UseInterceptors(CacheInterceptor) 76 | @Get() 77 | async getUsers() {} 78 | ``` 79 | 80 | Or inject `CacheManager` and use it directly: 81 | 82 | ```typescript 83 | constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {} 84 | 85 | await this.cacheManager.set('test', 'test', { 86 | ttl: 10, // in seconds 87 | } as any); 88 | 89 | await this.cacheManager.get('key'); 90 | ``` 91 | 92 | ### JWT auth with passport.js 93 | 94 | JWT authentication is configured and available to use. 95 | 96 | User registration, login and JWT-protected API examples were added in [user.controller.ts](./api/src/user/user.controller.ts) 97 | 98 | ### Logger with Trace ID generation 99 | 100 | [Pino](https://github.com/pinojs/pino) added as application logger. 101 | 102 | Each request to API is signed with unique TraceID and passed to logger via [AsyncLocalStorage](https://nodejs.org/api/async_context.html#class-asynclocalstorage). 103 | 104 | Code can be found in [async-storage.middleware.ts](./api/src/global/middleware/async-storage/async-storage.middleware.ts) and [app-logger.service.ts](./api/src/logger/services/app-logger/app-logger.service.ts) 105 | 106 | TraceID in logs example 107 | 108 | ### Graceful shutdown 109 | 110 | Nest.js [shutdown hooks](https://docs.nestjs.com/fundamentals/lifecycle-events#application-shutdown) are enabled. 111 | 112 | This starter kit subscribed to `OnModuleDestroy` event and [disconnects](./api/src/app-cache/app-cache.module.ts) from Redis gracefully. 113 | 114 | ### Automatic APIs documentation with Swagger 115 | 116 | Nest.js swagger module configured with the use of [Swagger CLI plugin](https://docs.nestjs.com/openapi/cli-plugin). 117 | 118 | API docs are generated with the start of app server automatically and available at [http://localhost:3000/api](http://localhost:3000/api): 119 | 120 | Swagger doc generated 121 | 122 | ### E-mail service with local mail trap 123 | 124 | Mail service is available out of the box and can be used like this: 125 | 126 | Inject in constructor: 127 | ```typescript 128 | constructor( 129 | private readonly mailer: MailService, 130 | ) {} 131 | ``` 132 | 133 | Send mail: 134 | ```typescript 135 | await this.mailer.send({ 136 | to: 'to-mail@example.com', 137 | from: this.mailer.from(), 138 | subject: 'User registered', 139 | text: 'Mail body', 140 | }); 141 | ``` 142 | 143 | You can check sent mails by opening http://localhost:8025/ and browse MailHog UI. 144 | 145 | ![MailHog UI](https://user-images.githubusercontent.com/5843270/143854275-1415cf0d-0003-4744-9f25-4649a1b406c9.png) 146 | 147 | Powered by [nodemailer](https://www.npmjs.com/package/nodemailer). 148 | 149 | ### Unit tests 150 | 151 | All code added in the project is covered with [unit tests](https://github.com/rodion-arr/nestjs-starter-kit/search?q=describe). 152 | 153 | You can find useful tests examples of: 154 | 155 | - DB repository mock [(auth.service.spec.ts)](./api/src/user/services/auth/auth.service.spec.ts). Search for `getRepositoryToken`. 156 | - Controller test [(user.controller.spec.ts)](./api/src/user/user.controller.spec.ts) 157 | - Middleware test [(async-storage.middleware.spec.ts)](./api/src/global/middleware/async-storage/async-storage.middleware.spec.ts) 158 | - Service test [(jwt.service.spec.ts)](./api/src/user/services/jwt/jwt.service.spec.ts) 159 | 160 | ## Health check 161 | 162 | Health check endpoint is available at [http://localhost:3000/health](http://localhost:3000/health) and returns 200 OK if server is healthy. This endpoint also checks DB and Redis connections. 163 | 164 | ## Installation 165 | 166 | ### Prerequisites 167 | 168 | - Docker for Desktop 169 | - Node.js LTS 170 | 171 | ### Getting started 172 | 173 | - Clone the repository 174 | ```console 175 | git clone https://github.com/rodion-arr/nestjs-starter-kit.git 176 | ``` 177 | 178 | - Run docker containers (DB, Redis, etc) 179 | ```console 180 | cd nestjs-starter-kit/.docker-node-api 181 | docker-compose up -d 182 | ``` 183 | 184 | - Go to api folder and copy env file 185 | ```console 186 | cd ../api 187 | cp .env.example .env 188 | ``` 189 | 190 | - Update .env file with credentials if needed 191 | 192 | - Next install dependencies 193 | ```console 194 | npm ci 195 | ``` 196 | 197 | - Init config and run migrations 198 | ```console 199 | npm run migrations:up 200 | ``` 201 | 202 | - Run application 203 | ```console 204 | npm start 205 | ``` 206 | -------------------------------------------------------------------------------- /api/.env.example: -------------------------------------------------------------------------------- 1 | # App 2 | PORT=3000 3 | APP_ENV=dev 4 | 5 | # DB 6 | DB_HOST=localhost 7 | DB_PORT=5432 8 | DB_USER=postgres 9 | DB_PASSWORD=secret 10 | DB_NAME=api 11 | 12 | JWT_SECRET=secret 13 | 14 | REDIS_HOST=localhost 15 | REDIS_PASSWORD= 16 | REDIS_PORT=6379 17 | 18 | LOG_LEVEL=debug 19 | 20 | # Mail 21 | MAIL_FROM=no-reply@nestjs-starter-kit.smtp.com 22 | MAIL_HOST=127.0.0.1 23 | MAIL_PORT=1025 24 | MAIL_AUTH_USER=any-user 25 | MAIL_AUTH_PASS=any-password 26 | -------------------------------------------------------------------------------- /api/.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json 36 | 37 | # Custom 38 | .env 39 | ormconfig.json 40 | -------------------------------------------------------------------------------- /api/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /api/eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import js from '@eslint/js'; 2 | import tseslint from '@typescript-eslint/eslint-plugin'; 3 | import tsParser from '@typescript-eslint/parser'; 4 | import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'; 5 | import globals from 'globals'; 6 | 7 | export default [ 8 | js.configs.recommended, // ESLint base rules 9 | eslintPluginPrettierRecommended, 10 | { 11 | files: ['**/*.ts', '**/*.tsx'], // Apply only to TypeScript files 12 | languageOptions: { 13 | parser: tsParser, 14 | parserOptions: { 15 | project: './tsconfig.json', 16 | sourceType: 'module', 17 | }, 18 | globals: { 19 | ...globals.node, 20 | }, 21 | }, 22 | plugins: { 23 | '@typescript-eslint': tseslint, 24 | }, 25 | rules: { 26 | ...tseslint.configs.recommended.rules, // Apply recommended TypeScript rules 27 | 28 | '@typescript-eslint/interface-name-prefix': 'off', 29 | '@typescript-eslint/explicit-function-return-type': 'off', 30 | '@typescript-eslint/explicit-module-boundary-types': 'off', 31 | '@typescript-eslint/no-explicit-any': 'off', 32 | '@typescript-eslint/no-unused-vars': 'error', 33 | 'no-restricted-imports': [ 34 | 'error', 35 | { 36 | patterns: ['../../../*'], 37 | }, 38 | ], 39 | }, 40 | }, 41 | { 42 | files: ['**/*.test.ts', '**/*.spec.ts', '**/*.e2e-spec.ts', '**/*.mock.ts'], 43 | languageOptions: { 44 | globals: { 45 | ...globals.jest, 46 | ...globals.node, 47 | }, 48 | }, 49 | }, 50 | ]; 51 | -------------------------------------------------------------------------------- /api/nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src", 4 | "compilerOptions": { 5 | "plugins": ["@nestjs/swagger"] 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /api/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "npm run type-check && eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "lint-ci": "npm run type-check && eslint \"{src,apps,libs,test}/**/*.ts\"", 18 | "pretest": "npm run lint-ci", 19 | "test": "jest", 20 | "test:watch": "jest --watch", 21 | "test:cov": "jest --coverage --passWithNoTests", 22 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 23 | "test:e2e": "jest --config ./test/jest-e2e.json", 24 | "typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js", 25 | "migrations:new": "npm run typeorm migration:create", 26 | "migrations:up": "npm run typeorm migration:run -- -d ./type-orm.config.ts", 27 | "migrations:revert": "npm run typeorm migration:revert -- -d ./type-orm.config.ts", 28 | "type-check": "tsc --noEmit" 29 | }, 30 | "dependencies": { 31 | "@keyv/redis": "^4.3.0", 32 | "@nestjs/cache-manager": "^3.0.0", 33 | "@nestjs/common": "^11.0.11", 34 | "@nestjs/config": "^4.0.0", 35 | "@nestjs/core": "^11.0.11", 36 | "@nestjs/jwt": "^11.0.0", 37 | "@nestjs/passport": "^11.0.5", 38 | "@nestjs/platform-express": "^11.0.11", 39 | "@nestjs/swagger": "^11.0.6", 40 | "@nestjs/terminus": "^11.0.0", 41 | "@nestjs/typeorm": "^11.0.0", 42 | "bcryptjs": "^2.4.3", 43 | "cache-manager": "^6.4.0", 44 | "class-transformer": "^0.5.1", 45 | "class-validator": "^0.14.1", 46 | "dotenv": "^16.4.5", 47 | "helmet": "^7.1.0", 48 | "jsonwebtoken": "^9.0.0", 49 | "nodemailer": "^6.9.7", 50 | "nodemailer-smtp-transport": "^2.7.4", 51 | "passport": "^0.7.0", 52 | "passport-jwt": "^4.0.1", 53 | "pg": "^8.11.5", 54 | "pino": "^8.19.0", 55 | "pino-pretty": "^10.3.1", 56 | "reflect-metadata": "^0.1.14", 57 | "rimraf": "^5.0.5", 58 | "rxjs": "^7.8.0", 59 | "swagger-ui-express": "^5.0.0" 60 | }, 61 | "devDependencies": { 62 | "@nestjs/cli": "^11.0.5", 63 | "@nestjs/schematics": "^11.0.1", 64 | "@nestjs/testing": "^11.0.11", 65 | "@types/bcryptjs": "^2.4.6", 66 | "@types/express": "^5.0.0", 67 | "@types/jest": "^29.5.14", 68 | "@types/jsonwebtoken": "^9.0.6", 69 | "@types/node": "^22.13.8", 70 | "@types/nodemailer": "^6.4.13", 71 | "@types/nodemailer-smtp-transport": "^2.7.8", 72 | "@types/passport-jwt": "^4.0.1", 73 | "@types/supertest": "^6.0.2", 74 | "@typescript-eslint/eslint-plugin": "^8.25.0", 75 | "@typescript-eslint/parser": "^8.25.0", 76 | "eslint": "^9.21.0", 77 | "eslint-config-prettier": "^10.0.2", 78 | "eslint-plugin-prettier": "^5.2.3", 79 | "jest": "^29.7.0", 80 | "prettier": "^3.2.5", 81 | "source-map-support": "^0.5.21", 82 | "supertest": "^7.0.0", 83 | "ts-jest": "^29.2.6", 84 | "ts-loader": "^9.5.1", 85 | "ts-node": "^10.9.2", 86 | "tsconfig-paths": "^4.2.0", 87 | "typeorm": "^0.3.20", 88 | "typescript": "^5.7.3" 89 | }, 90 | "jest": { 91 | "moduleFileExtensions": [ 92 | "js", 93 | "json", 94 | "ts" 95 | ], 96 | "rootDir": ".", 97 | "moduleDirectories": [ 98 | "node_modules", 99 | "" 100 | ], 101 | "testRegex": ".*\\.spec\\.ts$", 102 | "transform": { 103 | "^.+\\.(t|j)s$": "ts-jest" 104 | }, 105 | "collectCoverageFrom": [ 106 | "**/*.(t|j)s" 107 | ], 108 | "coveragePathIgnorePatterns": [ 109 | "src/db", 110 | ".module.ts", 111 | "src/main.ts" 112 | ], 113 | "coverageDirectory": "../coverage", 114 | "testEnvironment": "node" 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /api/src/app-cache/app-cache.module.ts: -------------------------------------------------------------------------------- 1 | import { Inject, Logger, Module, OnModuleDestroy } from '@nestjs/common'; 2 | import { CacheModule, CACHE_MANAGER } from '@nestjs/cache-manager'; 3 | import { CacheConfigService } from './services/cache-config/cache-config.service'; 4 | import { ConfigModule } from '@nestjs/config'; 5 | import { Cache } from 'cache-manager'; 6 | import { LoggerModule } from '../logger/logger.module'; 7 | 8 | @Module({ 9 | imports: [ 10 | LoggerModule, 11 | ConfigModule, 12 | CacheModule.registerAsync({ 13 | imports: [ConfigModule], 14 | useClass: CacheConfigService, 15 | isGlobal: true, 16 | }), 17 | ], 18 | providers: [CacheConfigService], 19 | exports: [CacheModule], 20 | }) 21 | export class AppCacheModule implements OnModuleDestroy { 22 | private readonly logger = new Logger(AppCacheModule.name); 23 | 24 | constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {} 25 | 26 | async onModuleDestroy() { 27 | this.logger.log('Disconnecting from cache'); 28 | await this.cacheManager.disconnect(); 29 | this.logger.log('Disconnected from cache'); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /api/src/app-cache/services/cache-config/cache-config.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { CacheConfigService } from './cache-config.service'; 3 | import { ConfigService } from '@nestjs/config'; 4 | import { createKeyv } from '@keyv/redis'; 5 | 6 | jest.mock('@keyv/redis', () => ({ 7 | createKeyv: jest.fn(), 8 | })); 9 | 10 | describe('CacheConfigService', () => { 11 | let service: CacheConfigService; 12 | 13 | beforeEach(async () => { 14 | const module: TestingModule = await Test.createTestingModule({ 15 | providers: [ 16 | CacheConfigService, 17 | { 18 | provide: ConfigService, 19 | useValue: { 20 | get: jest.fn().mockReturnValue({ 21 | host: 'host', 22 | port: 0, 23 | password: 'password', 24 | }), 25 | }, 26 | }, 27 | ], 28 | }).compile(); 29 | 30 | service = module.get(CacheConfigService); 31 | }); 32 | 33 | it('should be defined', () => { 34 | expect(service).toBeDefined(); 35 | }); 36 | 37 | it('should return redis config', async () => { 38 | service.createCacheOptions(); 39 | const redisMock = jest.mocked(createKeyv); 40 | 41 | expect(redisMock).toHaveBeenCalledWith({ 42 | socket: { 43 | host: 'host', 44 | port: 0, 45 | }, 46 | password: 'password', 47 | }); 48 | }); 49 | }); 50 | -------------------------------------------------------------------------------- /api/src/app-cache/services/cache-config/cache-config.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { ConfigService } from '@nestjs/config'; 3 | import { CacheModuleOptions, CacheOptionsFactory } from '@nestjs/cache-manager'; 4 | import { CacheConfig } from 'src/services/app-config/configuration'; 5 | import { createKeyv } from '@keyv/redis'; 6 | 7 | @Injectable() 8 | export class CacheConfigService implements CacheOptionsFactory { 9 | constructor(private readonly configService: ConfigService) {} 10 | 11 | createCacheOptions(): CacheModuleOptions { 12 | const { host, port, password } = this.configService.get( 13 | 'cache', 14 | ) as CacheConfig; 15 | 16 | return { 17 | stores: [ 18 | createKeyv({ 19 | // Store-specific configuration: 20 | socket: { 21 | host, 22 | port, 23 | }, 24 | password: password ?? null, 25 | }), 26 | ], 27 | }; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /api/src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { MiddlewareConsumer, Module } from '@nestjs/common'; 2 | import { UserModule } from './user/user.module'; 3 | import { ConfigModule } from '@nestjs/config'; 4 | import { DbModule } from './db/db.module'; 5 | import { getConfig } from './services/app-config/configuration'; 6 | import { AppCacheModule } from './app-cache/app-cache.module'; 7 | import { LoggerModule } from './logger/logger.module'; 8 | import { AsyncStorageMiddleware } from './global/middleware/async-storage/async-storage.middleware'; 9 | import { GlobalModule } from './global/global.module'; 10 | import { HealthModule } from './health/health.module'; 11 | 12 | @Module({ 13 | imports: [ 14 | GlobalModule, 15 | ConfigModule.forRoot({ 16 | cache: true, 17 | load: [getConfig], 18 | }), 19 | DbModule, 20 | AppCacheModule, 21 | UserModule, 22 | ConfigModule, 23 | LoggerModule, 24 | HealthModule, 25 | ], 26 | }) 27 | export class AppModule { 28 | configure(consumer: MiddlewareConsumer) { 29 | consumer.apply(AsyncStorageMiddleware).forRoutes('{*splat}'); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /api/src/db/db.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { getConfig } from '../services/app-config/configuration'; 4 | 5 | @Module({ 6 | imports: [ 7 | TypeOrmModule.forRootAsync({ 8 | useFactory: async () => { 9 | const { 10 | database: { host, port, password, user, dbName }, 11 | } = getConfig(); 12 | 13 | return { 14 | type: 'postgres', 15 | host, 16 | port, 17 | username: user, 18 | password, 19 | database: dbName, 20 | autoLoadEntities: true, 21 | }; 22 | }, 23 | }), 24 | ], 25 | }) 26 | export class DbModule {} 27 | -------------------------------------------------------------------------------- /api/src/db/migrations/1636917857168-Users.ts: -------------------------------------------------------------------------------- 1 | import { MigrationInterface, QueryRunner, Table, TableIndex } from 'typeorm'; 2 | 3 | export class Users1636917857168 implements MigrationInterface { 4 | public async up(queryRunner: QueryRunner): Promise { 5 | await queryRunner.createTable( 6 | new Table({ 7 | name: 'users', 8 | columns: [ 9 | { 10 | name: 'id', 11 | type: 'int', 12 | isPrimary: true, 13 | isGenerated: true, 14 | generationStrategy: 'increment', 15 | }, 16 | { 17 | name: 'first_name', 18 | type: 'varchar', 19 | }, 20 | { 21 | name: 'last_name', 22 | type: 'varchar', 23 | }, 24 | { 25 | name: 'email', 26 | type: 'varchar', 27 | isUnique: true, 28 | }, 29 | { 30 | name: 'password', 31 | type: 'varchar', 32 | }, 33 | { 34 | name: 'token', 35 | type: 'varchar', 36 | isNullable: true, 37 | }, 38 | { 39 | name: 'created_at', 40 | type: 'timestamp', 41 | default: 'now()', 42 | }, 43 | ], 44 | }), 45 | ); 46 | 47 | await queryRunner.createIndex( 48 | 'users', 49 | new TableIndex({ 50 | name: 'IDX_USERS_NAME', 51 | columnNames: ['email'], 52 | }), 53 | ); 54 | } 55 | 56 | public async down(queryRunner: QueryRunner): Promise { 57 | await queryRunner.dropTable('users'); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /api/src/global/constants.ts: -------------------------------------------------------------------------------- 1 | export const ASYNC_STORAGE = Symbol('async_storage'); 2 | -------------------------------------------------------------------------------- /api/src/global/global.module.ts: -------------------------------------------------------------------------------- 1 | import { Global, Module } from '@nestjs/common'; 2 | import { AsyncLocalStorage } from 'async_hooks'; 3 | import { ASYNC_STORAGE } from './constants'; 4 | import { MailService } from './services/mail/mail.service'; 5 | import { ConfigModule } from '@nestjs/config'; 6 | 7 | @Global() 8 | @Module({ 9 | imports: [ConfigModule], 10 | providers: [ 11 | { 12 | provide: ASYNC_STORAGE, 13 | useValue: new AsyncLocalStorage(), 14 | }, 15 | MailService, 16 | ], 17 | exports: [ASYNC_STORAGE, MailService], 18 | }) 19 | export class GlobalModule {} 20 | -------------------------------------------------------------------------------- /api/src/global/middleware/async-storage/async-storage.middleware.spec.ts: -------------------------------------------------------------------------------- 1 | import { AsyncStorageMiddleware } from './async-storage.middleware'; 2 | import { Test, TestingModule } from '@nestjs/testing'; 3 | import { ASYNC_STORAGE } from '../../constants'; 4 | import { AsyncLocalStorage } from 'async_hooks'; 5 | 6 | jest.mock('node:crypto', () => ({ 7 | randomUUID: jest.fn().mockReturnValue('mock-trace-id'), 8 | })); 9 | 10 | describe('AsyncStorageMiddleware', () => { 11 | let middleware: AsyncStorageMiddleware; 12 | let storage: AsyncLocalStorage>; 13 | 14 | beforeEach(async () => { 15 | const module: TestingModule = await Test.createTestingModule({ 16 | providers: [ 17 | AsyncStorageMiddleware, 18 | { 19 | provide: ASYNC_STORAGE, 20 | useValue: { 21 | run: (store: unknown, callback: () => void) => { 22 | callback(); 23 | }, 24 | }, 25 | }, 26 | ], 27 | }).compile(); 28 | 29 | middleware = module.get(AsyncStorageMiddleware); 30 | storage = module.get>>(ASYNC_STORAGE); 31 | }); 32 | 33 | it('should be defined', () => { 34 | expect(middleware).toBeDefined(); 35 | }); 36 | 37 | it('should accept request id header', () => { 38 | const runSpy = jest.spyOn(storage, 'run'); 39 | const nextMock = jest.fn(); 40 | 41 | middleware.use( 42 | { 43 | headers: { 'x-request-id': 'mocked' }, 44 | }, 45 | null, 46 | nextMock, 47 | ); 48 | 49 | expect(nextMock).toHaveBeenCalledTimes(1); 50 | expect(runSpy).toHaveBeenCalledWith( 51 | new Map().set('traceId', 'mocked'), 52 | expect.anything(), 53 | ); 54 | }); 55 | 56 | it('should generate request id if no header found', () => { 57 | const runSpy = jest.spyOn(storage, 'run'); 58 | const nextMock = jest.fn(); 59 | 60 | middleware.use( 61 | { 62 | headers: {}, 63 | }, 64 | null, 65 | nextMock, 66 | ); 67 | 68 | expect(nextMock).toHaveBeenCalledTimes(1); 69 | expect(runSpy).toHaveBeenCalledWith( 70 | new Map().set('traceId', 'mock-trace-id'), 71 | expect.anything(), 72 | ); 73 | }); 74 | }); 75 | -------------------------------------------------------------------------------- /api/src/global/middleware/async-storage/async-storage.middleware.ts: -------------------------------------------------------------------------------- 1 | import { Inject, Injectable, NestMiddleware } from '@nestjs/common'; 2 | import { randomUUID } from 'node:crypto'; 3 | import { ASYNC_STORAGE } from '../../constants'; 4 | import { AsyncLocalStorage } from 'async_hooks'; 5 | 6 | @Injectable() 7 | export class AsyncStorageMiddleware implements NestMiddleware { 8 | constructor( 9 | @Inject(ASYNC_STORAGE) 10 | private readonly asyncStorage: AsyncLocalStorage>, 11 | ) {} 12 | 13 | use(req: any, res: any, next: () => void) { 14 | const traceId = req.headers['x-request-id'] || randomUUID(); 15 | const store = new Map().set('traceId', traceId); 16 | this.asyncStorage.run(store, () => { 17 | next(); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /api/src/global/services/mail/mail.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { ConfigService } from '@nestjs/config'; 3 | import { createTransport, Transporter } from 'nodemailer'; 4 | import { MailConfig } from 'src/services/app-config/configuration'; 5 | import SMTPTransport from 'nodemailer/lib/smtp-transport'; 6 | import Mail from 'nodemailer/lib/mailer'; 7 | 8 | type MailOptions = Mail.Options; 9 | 10 | @Injectable() 11 | export class MailService { 12 | private readonly fromValue: string; 13 | private transport: Transporter; 14 | 15 | constructor(private readonly configService: ConfigService) { 16 | const { 17 | from, 18 | transportOptions: { 19 | host, 20 | port, 21 | auth: { user, pass }, 22 | }, 23 | } = configService.get('mail') as MailConfig; 24 | 25 | this.fromValue = from; 26 | this.transport = createTransport({ 27 | host, 28 | port, 29 | auth: { 30 | user, 31 | pass, 32 | }, 33 | }); 34 | } 35 | 36 | public async send(options: MailOptions): Promise { 37 | const result = await this.transport.sendMail(options); 38 | 39 | return result.response; 40 | } 41 | 42 | public from(): string { 43 | return this.fromValue; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /api/src/global/services/mail/mailer.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { MailService } from './mail.service'; 3 | import { ConfigService } from '@nestjs/config'; 4 | import { createTransport, Transporter } from 'nodemailer'; 5 | import SMTPTransport from 'nodemailer/lib/smtp-transport'; 6 | 7 | jest.mock('nodemailer'); 8 | 9 | describe('MailerService', () => { 10 | let service: MailService; 11 | const connectMock = jest.mocked(createTransport); 12 | const sendMock = jest.fn().mockResolvedValue({ response: 'mock-response' }); 13 | 14 | beforeEach(async () => { 15 | connectMock.mockReturnValueOnce({ 16 | sendMail: sendMock, 17 | } as unknown as Transporter); 18 | 19 | const module: TestingModule = await Test.createTestingModule({ 20 | providers: [ 21 | MailService, 22 | { 23 | provide: ConfigService, 24 | useValue: { 25 | get: jest.fn().mockReturnValue({ 26 | from: 'from-mail', 27 | transportOptions: { 28 | host: 'smtp-host', 29 | port: 123, 30 | auth: { 31 | user: 'smtp-user', 32 | pass: 'smtp-pass', 33 | }, 34 | }, 35 | }), 36 | }, 37 | }, 38 | ], 39 | }).compile(); 40 | 41 | service = module.get(MailService); 42 | }); 43 | 44 | it('should be defined', () => { 45 | expect(service).toBeDefined(); 46 | }); 47 | 48 | it('should connect to SMTP', () => { 49 | const connectMock = jest.mocked(createTransport); 50 | 51 | expect(connectMock).toHaveBeenCalledWith({ 52 | host: 'smtp-host', 53 | port: 123, 54 | auth: { 55 | user: 'smtp-user', 56 | pass: 'smtp-pass', 57 | }, 58 | }); 59 | }); 60 | 61 | it('should send mail according to options', async () => { 62 | const sendOptions = { 63 | to: 'to-mail@example.com', 64 | from: service.from(), 65 | subject: 'User registered', 66 | }; 67 | const mailResult = await service.send(sendOptions); 68 | 69 | expect(mailResult).toBe('mock-response'); 70 | expect(sendMock).toHaveBeenCalledWith(sendOptions); 71 | }); 72 | 73 | it('should return from mail', () => { 74 | expect(service.from()).toBe('from-mail'); 75 | }); 76 | }); 77 | -------------------------------------------------------------------------------- /api/src/health/health.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test } from '@nestjs/testing'; 2 | import { HealthController } from './health.controller'; 3 | import { HealthCheckService, TypeOrmHealthIndicator } from '@nestjs/terminus'; 4 | import { HealthCheckResult } from '@nestjs/terminus/dist/health-check/health-check-result.interface'; 5 | import Mock = jest.Mock; 6 | import { CacheHealthIndicator } from './indicators/cache/cache.health-indicator'; 7 | 8 | describe('HealthController', () => { 9 | let healthController: HealthController; 10 | let healthCheckService: Partial; 11 | let cacheHealthIndicator: Partial; 12 | let typeOrmHealthIndicator: Partial; 13 | 14 | beforeEach(async () => { 15 | healthCheckService = { 16 | check: jest.fn(), 17 | }; 18 | 19 | typeOrmHealthIndicator = { 20 | pingCheck: jest.fn(), 21 | }; 22 | 23 | cacheHealthIndicator = { 24 | isHealthy: jest.fn(), 25 | }; 26 | 27 | const moduleRef = await Test.createTestingModule({ 28 | controllers: [HealthController], 29 | providers: [ 30 | { provide: HealthCheckService, useValue: healthCheckService }, 31 | { provide: TypeOrmHealthIndicator, useValue: typeOrmHealthIndicator }, 32 | { provide: CacheHealthIndicator, useValue: cacheHealthIndicator }, 33 | ], 34 | }).compile(); 35 | 36 | healthController = moduleRef.get(HealthController); 37 | healthCheckService = moduleRef.get(HealthCheckService); 38 | typeOrmHealthIndicator = moduleRef.get( 39 | TypeOrmHealthIndicator, 40 | ); 41 | }); 42 | 43 | describe('healthCheck', () => { 44 | it('should return health check result', async () => { 45 | (cacheHealthIndicator.isHealthy as Mock).mockResolvedValue({ 46 | cache: { 47 | status: 'up', 48 | }, 49 | }); 50 | const healthCheckResult: HealthCheckResult = { 51 | status: 'ok', 52 | details: { 53 | db: { 54 | status: 'up', 55 | }, 56 | cache: { 57 | status: 'up', 58 | }, 59 | }, 60 | }; 61 | 62 | (healthCheckService.check as Mock).mockImplementation( 63 | async (props: (() => void)[]) => { 64 | props.forEach((propFunction) => propFunction()); 65 | return healthCheckResult; 66 | }, 67 | ); 68 | (typeOrmHealthIndicator.pingCheck as Mock).mockReturnValue(true); 69 | 70 | const result = await healthController.healthCheck(); 71 | 72 | expect(healthCheckService.check).toHaveBeenCalledWith([ 73 | expect.any(Function), 74 | expect.any(Function), 75 | ]); 76 | expect(typeOrmHealthIndicator.pingCheck).toHaveBeenCalledWith('db'); 77 | expect(result).toEqual(healthCheckResult); 78 | }); 79 | }); 80 | }); 81 | -------------------------------------------------------------------------------- /api/src/health/health.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { 3 | HealthCheck, 4 | HealthCheckService, 5 | TypeOrmHealthIndicator, 6 | } from '@nestjs/terminus'; 7 | import { ApiTags } from '@nestjs/swagger'; 8 | import { CacheHealthIndicator } from './indicators/cache/cache.health-indicator'; 9 | 10 | @ApiTags('health') 11 | @Controller('health') 12 | export class HealthController { 13 | constructor( 14 | private readonly health: HealthCheckService, 15 | private readonly db: TypeOrmHealthIndicator, 16 | private readonly cacheHealthIndicator: CacheHealthIndicator, 17 | ) {} 18 | 19 | @Get() 20 | @HealthCheck() 21 | healthCheck() { 22 | return this.health.check([ 23 | () => this.db.pingCheck('db'), 24 | () => this.cacheHealthIndicator.isHealthy(), 25 | ]); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /api/src/health/health.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TerminusModule } from '@nestjs/terminus'; 3 | import { HealthController } from './health.controller'; 4 | import { CacheHealthIndicator } from './indicators/cache/cache.health-indicator'; 5 | 6 | @Module({ 7 | imports: [TerminusModule], 8 | controllers: [HealthController], 9 | providers: [CacheHealthIndicator], 10 | }) 11 | export class HealthModule {} 12 | -------------------------------------------------------------------------------- /api/src/health/indicators/cache/cache.health-indicator.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test } from '@nestjs/testing'; 2 | import Mock = jest.Mock; 3 | import { CacheHealthIndicator } from './cache.health-indicator'; 4 | import { Cache } from 'cache-manager'; 5 | import { CACHE_MANAGER } from '@nestjs/cache-manager'; 6 | import { getCacheMock } from 'test/test-utils/cache.mock'; 7 | 8 | describe('CacheHealthIndicator', () => { 9 | let service: CacheHealthIndicator; 10 | let cacheManagerMock: Partial; 11 | 12 | beforeEach(async () => { 13 | cacheManagerMock = getCacheMock(); 14 | 15 | const moduleRef = await Test.createTestingModule({ 16 | controllers: [CacheHealthIndicator], 17 | providers: [{ provide: CACHE_MANAGER, useValue: cacheManagerMock }], 18 | }).compile(); 19 | 20 | service = moduleRef.get(CacheHealthIndicator); 21 | }); 22 | 23 | describe('isHealthy', () => { 24 | it('should return cache health check result', async () => { 25 | (cacheManagerMock.set as Mock).mockResolvedValueOnce('true'); 26 | (cacheManagerMock.get as Mock).mockResolvedValueOnce('true'); 27 | 28 | const result = await service.isHealthy(); 29 | 30 | expect(result).toEqual({ cache: { status: 'up' } }); 31 | }); 32 | 33 | it('should return cache health error result', async () => { 34 | (cacheManagerMock.set as Mock).mockResolvedValueOnce('true'); 35 | (cacheManagerMock.get as Mock).mockResolvedValueOnce('false'); 36 | 37 | await expect(service.isHealthy()).rejects.toThrowError( 38 | 'CacheHealthIndicator failed', 39 | ); 40 | }); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /api/src/health/indicators/cache/cache.health-indicator.ts: -------------------------------------------------------------------------------- 1 | import { Inject, Injectable } from '@nestjs/common'; 2 | import { 3 | HealthCheckError, 4 | HealthIndicator, 5 | HealthIndicatorResult, 6 | } from '@nestjs/terminus'; 7 | import { CACHE_MANAGER } from '@nestjs/cache-manager'; 8 | import { Cache } from 'cache-manager'; 9 | import { setTimeout } from 'node:timers/promises'; 10 | 11 | @Injectable() 12 | export class CacheHealthIndicator extends HealthIndicator { 13 | constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) { 14 | super(); 15 | } 16 | 17 | async isHealthy(): Promise { 18 | try { 19 | const timeIsUp = async () => { 20 | await setTimeout(1000); 21 | throw new Error('Cache timeout'); 22 | }; 23 | 24 | const cacheIsUp = async () => { 25 | await this.cacheManager.set('healthcheck', 'true', { ttl: 10 } as any); 26 | const result = await this.cacheManager.get('healthcheck'); 27 | 28 | if (result !== 'true') { 29 | throw new Error('Cache is down'); 30 | } 31 | }; 32 | 33 | await Promise.race([cacheIsUp(), timeIsUp()]); 34 | 35 | return this.getStatus('cache', true); 36 | } catch { 37 | throw new HealthCheckError( 38 | 'CacheHealthIndicator failed', 39 | this.getStatus('cache', false), 40 | ); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /api/src/logger/interceptors/request-logger.interceptor.spec.ts: -------------------------------------------------------------------------------- 1 | import { RequestLoggerInterceptor } from './request-logger.interceptor'; 2 | import { Test, TestingModule } from '@nestjs/testing'; 3 | import { ExecutionContext, LoggerService } from '@nestjs/common'; 4 | 5 | describe('RequestLoggerInterceptor', () => { 6 | let interceptor: RequestLoggerInterceptor; 7 | let loggerMock: LoggerService; 8 | 9 | beforeEach(async () => { 10 | loggerMock = { 11 | error: jest.fn(), 12 | warn: jest.fn(), 13 | log: jest.fn(), 14 | }; 15 | 16 | const module: TestingModule = await Test.createTestingModule({ 17 | providers: [RequestLoggerInterceptor], 18 | }) 19 | .setLogger(loggerMock) 20 | .compile(); 21 | 22 | interceptor = module.get( 23 | RequestLoggerInterceptor, 24 | ); 25 | }); 26 | 27 | it('should be defined', () => { 28 | expect(interceptor).toBeDefined(); 29 | }); 30 | 31 | it('should log incoming request', () => { 32 | const nextMock = { 33 | handle: jest.fn(), 34 | }; 35 | const requestMock = () => ({ 36 | method: 'test-method', 37 | url: 'test-url', 38 | query: 'test-query', 39 | body: 'test-body', 40 | }); 41 | const contextMock = { 42 | switchToHttp: () => ({ 43 | getRequest: requestMock, 44 | }), 45 | }; 46 | 47 | interceptor.intercept(contextMock as ExecutionContext, nextMock); 48 | 49 | expect(nextMock.handle).toHaveBeenCalledTimes(1); 50 | expect(loggerMock.log).toHaveBeenCalledWith( 51 | '{"message":"test-method test-url REQUEST","query":"test-query","body":"test-body"}', 52 | 'RequestLoggerInterceptor', 53 | ); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /api/src/logger/interceptors/request-logger.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CallHandler, 3 | ExecutionContext, 4 | Injectable, 5 | Logger, 6 | NestInterceptor, 7 | } from '@nestjs/common'; 8 | import { Observable } from 'rxjs'; 9 | 10 | @Injectable() 11 | export class RequestLoggerInterceptor implements NestInterceptor { 12 | private readonly logger = new Logger(RequestLoggerInterceptor.name); 13 | 14 | intercept(context: ExecutionContext, next: CallHandler): Observable { 15 | const request = context.switchToHttp().getRequest(); 16 | const method = request.method; 17 | const url = request.url; 18 | const query = request.query; 19 | const body = request.body; 20 | 21 | const logMessage = { 22 | message: `${method} ${url} REQUEST`, 23 | query, 24 | body, 25 | }; 26 | 27 | this.logger.log(JSON.stringify(logMessage)); 28 | 29 | return next.handle(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /api/src/logger/logger.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppLoggerService } from './services/app-logger/app-logger.service'; 3 | import { ConfigModule } from '@nestjs/config'; 4 | import { APP_INTERCEPTOR } from '@nestjs/core'; 5 | import { RequestLoggerInterceptor } from './interceptors/request-logger.interceptor'; 6 | 7 | @Module({ 8 | imports: [ConfigModule], 9 | providers: [ 10 | AppLoggerService, 11 | { 12 | provide: APP_INTERCEPTOR, 13 | useClass: RequestLoggerInterceptor, 14 | }, 15 | ], 16 | }) 17 | export class LoggerModule {} 18 | -------------------------------------------------------------------------------- /api/src/logger/services/app-logger/app-logger.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppLoggerService } from './app-logger.service'; 3 | import { ASYNC_STORAGE } from 'src/global/constants'; 4 | import { ConfigService } from '@nestjs/config'; 5 | import { pino } from 'pino'; 6 | 7 | jest.mock('pino', () => ({ 8 | pino: jest.fn(), 9 | })); 10 | 11 | describe('AppLoggerService', () => { 12 | const setUpModule = async (): Promise => { 13 | const storeMap = new Map(); 14 | storeMap.set('traceId', 'uuid'); 15 | 16 | return await Test.createTestingModule({ 17 | providers: [ 18 | AppLoggerService, 19 | { 20 | provide: ASYNC_STORAGE, 21 | useValue: { 22 | getStore: jest.fn().mockReturnValue(storeMap), 23 | }, 24 | }, 25 | { 26 | provide: ConfigService, 27 | useValue: { 28 | get: jest.fn().mockImplementation((key: string) => { 29 | switch (key) { 30 | case 'logLevel': 31 | return 'debug'; 32 | case 'appEnv': 33 | return 'dev'; 34 | } 35 | }), 36 | }, 37 | }, 38 | ], 39 | }).compile(); 40 | }; 41 | 42 | it('should be defined', async () => { 43 | const pinoMock = jest.mocked(pino); 44 | const module = await setUpModule(); 45 | const service = module.get(AppLoggerService); 46 | 47 | expect(service).toBeDefined(); 48 | expect(pinoMock).toHaveBeenCalledWith({ 49 | level: 'debug', 50 | transport: { 51 | target: 'pino-pretty', 52 | }, 53 | }); 54 | }); 55 | 56 | it('should define error logger', async () => { 57 | const pinoMock = jest.mocked(pino); 58 | const errorMock = jest.fn(); 59 | pinoMock.mockReturnValueOnce({ 60 | error: errorMock, 61 | } as unknown as ReturnType); 62 | 63 | const module = await setUpModule(); 64 | const service = module.get(AppLoggerService); 65 | 66 | service.error('message', 'trace', 'context'); 67 | 68 | expect(errorMock).toHaveBeenCalledWith( 69 | { traceId: 'uuid' }, 70 | '[context] message', 71 | ); 72 | expect(errorMock).toHaveBeenCalledWith('trace'); 73 | }); 74 | 75 | it('should define info logger', async () => { 76 | const pinoMock = jest.mocked(pino); 77 | const logMock = jest.fn(); 78 | pinoMock.mockReturnValueOnce({ 79 | info: logMock, 80 | } as unknown as ReturnType); 81 | 82 | const module = await setUpModule(); 83 | const service = module.get(AppLoggerService); 84 | 85 | service.log('message', 'context'); 86 | 87 | expect(logMock).toHaveBeenCalledWith( 88 | { traceId: 'uuid' }, 89 | '[context] message', 90 | ); 91 | }); 92 | 93 | it('should define warn logger', async () => { 94 | const pinoMock = jest.mocked(pino); 95 | const logMock = jest.fn(); 96 | pinoMock.mockReturnValueOnce({ 97 | warn: logMock, 98 | } as unknown as ReturnType); 99 | 100 | const module = await setUpModule(); 101 | const service = module.get(AppLoggerService); 102 | 103 | service.warn('message', 'context'); 104 | 105 | expect(logMock).toHaveBeenCalledWith( 106 | { traceId: 'uuid' }, 107 | '[context] message', 108 | ); 109 | }); 110 | }); 111 | -------------------------------------------------------------------------------- /api/src/logger/services/app-logger/app-logger.service.ts: -------------------------------------------------------------------------------- 1 | import { Inject, Injectable, LoggerService } from '@nestjs/common'; 2 | import { pino, LoggerOptions } from 'pino'; 3 | import { AsyncLocalStorage } from 'async_hooks'; 4 | import { ASYNC_STORAGE } from 'src/global/constants'; 5 | import { ConfigService } from '@nestjs/config'; 6 | import { AppEnv } from 'src/services/app-config/configuration'; 7 | 8 | @Injectable() 9 | export class AppLoggerService implements LoggerService { 10 | private pino: pino.Logger; 11 | 12 | constructor( 13 | @Inject(ASYNC_STORAGE) 14 | private readonly asyncStorage: AsyncLocalStorage>, 15 | private readonly configService: ConfigService, 16 | ) { 17 | const logLevel = configService.get('logLevel'); 18 | const appEnv = configService.get('appEnv'); 19 | 20 | const loggerConfig: LoggerOptions = { 21 | level: logLevel, 22 | }; 23 | 24 | if (appEnv === AppEnv.DEV) { 25 | loggerConfig.transport = { 26 | target: 'pino-pretty', 27 | }; 28 | } 29 | 30 | this.pino = pino(loggerConfig); 31 | } 32 | 33 | error(message: any, trace?: string, context?: string): any { 34 | const traceId = this.asyncStorage.getStore()?.get('traceId'); 35 | this.pino.error({ traceId }, this.getMessage(message, context)); 36 | if (trace) { 37 | this.pino.error(trace); 38 | } 39 | } 40 | 41 | log(message: any, context?: string): any { 42 | const traceId = this.asyncStorage.getStore()?.get('traceId'); 43 | this.pino.info({ traceId }, this.getMessage(message, context)); 44 | } 45 | 46 | warn(message: any, context?: string): any { 47 | const traceId = this.asyncStorage.getStore()?.get('traceId'); 48 | this.pino.warn({ traceId }, this.getMessage(message, context)); 49 | } 50 | 51 | private getMessage(message: any, context?: string) { 52 | return context ? `[${context}] ${message}` : message; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /api/src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { ValidationPipe } from '@nestjs/common'; 4 | import { AppLoggerService } from './logger/services/app-logger/app-logger.service'; 5 | import { json } from 'body-parser'; 6 | import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; 7 | import helmet from 'helmet'; 8 | 9 | async function bootstrap() { 10 | const app = await NestFactory.create(AppModule); 11 | 12 | /* 13 | Required to be executed before async storage middleware 14 | and not loose context on POST requests 15 | */ 16 | app.use(json()); 17 | 18 | app.use(helmet()); 19 | 20 | app.enableShutdownHooks(); 21 | 22 | app.useGlobalPipes( 23 | new ValidationPipe({ 24 | whitelist: true, 25 | transform: true, 26 | }), 27 | ); 28 | 29 | const logger = app.get(AppLoggerService); 30 | app.useLogger(logger); 31 | 32 | // API docs 33 | const config = new DocumentBuilder() 34 | .setTitle('Node API') 35 | .setDescription( 36 | `https://github.com/rodion-arr/nestjs-starter-kit`, 40 | ) 41 | .addBearerAuth() 42 | .build(); 43 | const document = SwaggerModule.createDocument(app, config); 44 | SwaggerModule.setup('api', app, document); 45 | 46 | const port = process.env.PORT || 3000; 47 | 48 | await app.listen(port, '0.0.0.0'); 49 | 50 | logger.log(`App started on http://localhost:${port}`); 51 | } 52 | 53 | bootstrap(); 54 | -------------------------------------------------------------------------------- /api/src/services/app-config/configuration.spec.ts: -------------------------------------------------------------------------------- 1 | import { getConfig } from './configuration'; 2 | import { readFileSync } from 'fs'; 3 | import { join } from 'path'; 4 | 5 | describe('config helper', () => { 6 | it('should be defined', () => { 7 | expect(getConfig).toBeDefined(); 8 | }); 9 | 10 | it('should return configs', () => { 11 | const env = readFileSync(join(process.cwd(), '.env.example'), 'utf8') 12 | .split('\n') 13 | .reduce((vars: any, i) => { 14 | const [variable, value] = i.split('='); 15 | vars[variable] = value; 16 | return vars; 17 | }, {}); 18 | 19 | process.env = Object.assign(process.env, env); 20 | 21 | expect(getConfig()).toStrictEqual({ 22 | cache: { 23 | host: 'localhost', 24 | password: '', 25 | port: 6379, 26 | }, 27 | database: { 28 | dbName: 'api', 29 | host: 'localhost', 30 | password: 'secret', 31 | port: 5432, 32 | user: 'postgres', 33 | }, 34 | appEnv: 'dev', 35 | jwtSecret: 'secret', 36 | logLevel: 'debug', 37 | port: 3000, 38 | mail: { 39 | from: 'no-reply@nestjs-starter-kit.smtp.com', 40 | transportOptions: { 41 | auth: { 42 | pass: 'any-password', 43 | user: 'any-user', 44 | }, 45 | host: '127.0.0.1', 46 | port: 1025, 47 | }, 48 | }, 49 | }); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /api/src/services/app-config/configuration.ts: -------------------------------------------------------------------------------- 1 | export const getConfig = (): AppConfig => { 2 | return { 3 | port: parseInt(process.env.PORT as string, 10) || 3000, 4 | appEnv: process.env.APP_ENV as AppEnv, 5 | jwtSecret: process.env.JWT_SECRET as string, 6 | logLevel: process.env.LOG_LEVEL || 'info', 7 | database: { 8 | host: process.env.DB_HOST as string, 9 | port: parseInt(process.env.DB_PORT as string, 10) || 5432, 10 | user: process.env.DB_USER as string, 11 | password: process.env.DB_PASSWORD as string, 12 | dbName: process.env.DB_NAME as string, 13 | }, 14 | cache: { 15 | host: process.env.REDIS_HOST as string, 16 | port: parseInt(process.env.REDIS_PORT as string, 10) || 6379, 17 | password: process.env.REDIS_PASSWORD as string, 18 | }, 19 | mail: { 20 | from: process.env.MAIL_FROM as string, 21 | transportOptions: { 22 | host: process.env.MAIL_HOST as string, 23 | port: parseInt(process.env.MAIL_PORT as string, 10), 24 | auth: { 25 | user: process.env.MAIL_AUTH_USER as string, 26 | pass: process.env.MAIL_AUTH_PASS as string, 27 | }, 28 | }, 29 | }, 30 | }; 31 | }; 32 | 33 | export interface AppConfig { 34 | port: number; 35 | appEnv: AppEnv; 36 | jwtSecret: string; 37 | logLevel: string; 38 | database: DbConfig; 39 | cache: CacheConfig; 40 | mail: MailConfig; 41 | } 42 | 43 | export enum AppEnv { 44 | DEV = 'dev', 45 | TEST = 'test', 46 | PROD = 'production', 47 | } 48 | 49 | export interface DbConfig { 50 | host: string; 51 | port: number; 52 | user: string; 53 | password: string; 54 | dbName: string; 55 | } 56 | 57 | export interface CacheConfig { 58 | host: string; 59 | port: number; 60 | password: string; 61 | } 62 | 63 | export interface MailConfig { 64 | from: string; 65 | transportOptions: { 66 | host: string; 67 | port: number; 68 | auth: { 69 | user: string; 70 | pass: string; 71 | }; 72 | }; 73 | } 74 | -------------------------------------------------------------------------------- /api/src/user/dto/create-user.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsEmail, IsNotEmpty, IsOptional, IsString } from 'class-validator'; 2 | 3 | export class CreateUserDto { 4 | @IsString() 5 | @IsOptional() 6 | firstName: string; 7 | 8 | @IsString() 9 | @IsOptional() 10 | lastName: string; 11 | 12 | @IsEmail() 13 | email: string; 14 | 15 | @IsString() 16 | @IsNotEmpty() 17 | password: string; 18 | } 19 | -------------------------------------------------------------------------------- /api/src/user/dto/login.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; 2 | 3 | export class LoginDto { 4 | @IsEmail() 5 | email: string; 6 | 7 | @IsString() 8 | @IsNotEmpty() 9 | password: string; 10 | } 11 | -------------------------------------------------------------------------------- /api/src/user/entities/__fixtures__/user-entity.fixture.ts: -------------------------------------------------------------------------------- 1 | import { UserEntity } from '../user.entity'; 2 | 3 | export const mockUserEntity: UserEntity = { 4 | id: 0, 5 | email: 'email', 6 | lastName: 'lName', 7 | firstName: 'fName', 8 | token: 'token', 9 | passwordHash: 'password', 10 | }; 11 | -------------------------------------------------------------------------------- /api/src/user/entities/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; 2 | 3 | @Entity({ 4 | name: 'users', 5 | }) 6 | export class UserEntity { 7 | @PrimaryGeneratedColumn() 8 | id: number; 9 | 10 | @Column({ 11 | name: 'first_name', 12 | }) 13 | firstName: string; 14 | 15 | @Column({ 16 | name: 'last_name', 17 | }) 18 | lastName: string; 19 | 20 | @Column() 21 | email: string; 22 | 23 | @Column({ 24 | name: 'password', 25 | }) 26 | passwordHash: string; 27 | 28 | @Column() 29 | token: string; 30 | } 31 | -------------------------------------------------------------------------------- /api/src/user/guards/jwt-auth/jwt-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { AuthGuard } from '@nestjs/passport'; 3 | 4 | @Injectable() 5 | export class JwtAuthGuard extends AuthGuard('jwt') {} 6 | -------------------------------------------------------------------------------- /api/src/user/services/auth/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthService } from './auth.service'; 3 | import { UserService } from '../user/user.service'; 4 | import { PasswordService } from '../password/password.service'; 5 | import { JwtService } from '../jwt/jwt.service'; 6 | import { getRepositoryToken } from '@nestjs/typeorm'; 7 | import { UserEntity } from '../../entities/user.entity'; 8 | import { ConfigService } from '@nestjs/config'; 9 | import { mockUserEntity } from '../../entities/__fixtures__/user-entity.fixture'; 10 | 11 | describe('AuthService', () => { 12 | let authService: AuthService; 13 | let userService: UserService; 14 | 15 | beforeEach(async () => { 16 | const module: TestingModule = await Test.createTestingModule({ 17 | providers: [ 18 | AuthService, 19 | UserService, 20 | PasswordService, 21 | ConfigService, 22 | JwtService, 23 | { 24 | provide: getRepositoryToken(UserEntity), 25 | useValue: {}, 26 | }, 27 | ], 28 | }).compile(); 29 | 30 | authService = module.get(AuthService); 31 | userService = module.get(UserService); 32 | }); 33 | 34 | it('should be defined', () => { 35 | expect(authService).toBeDefined(); 36 | }); 37 | 38 | describe('register', () => { 39 | it('should check for user existence', async () => { 40 | expect.assertions(3); 41 | 42 | const existSpy = jest 43 | .spyOn(userService, 'isUserExists') 44 | .mockResolvedValue(mockUserEntity); 45 | const createSpy = jest.spyOn(userService, 'createUser'); 46 | 47 | try { 48 | await authService.register({ 49 | email: 'email', 50 | password: 'password', 51 | lastName: 'lName', 52 | firstName: 'fName', 53 | }); 54 | } catch (e) { 55 | expect(e.message).toBe('User already exists'); 56 | } 57 | expect(existSpy).toHaveBeenCalledWith('email'); 58 | expect(createSpy).toHaveBeenCalledTimes(0); 59 | }); 60 | 61 | it('should create user', async () => { 62 | const existSpy = jest 63 | .spyOn(userService, 'isUserExists') 64 | .mockResolvedValue(null); 65 | const createSpy = jest 66 | .spyOn(userService, 'createUser') 67 | .mockResolvedValue(new UserEntity()); 68 | 69 | const newUser = await authService.register({ 70 | email: 'email', 71 | password: 'password', 72 | lastName: 'lName', 73 | firstName: 'fName', 74 | }); 75 | 76 | expect(newUser).toBeInstanceOf(UserEntity); 77 | expect(existSpy).toHaveBeenCalledWith('email'); 78 | expect(createSpy).toHaveBeenCalledWith({ 79 | email: 'email', 80 | password: 'password', 81 | lastName: 'lName', 82 | firstName: 'fName', 83 | }); 84 | }); 85 | }); 86 | 87 | describe('login', () => { 88 | it('should check for user existence', async () => { 89 | expect.assertions(2); 90 | 91 | const existSpy = jest 92 | .spyOn(userService, 'isUserExists') 93 | .mockResolvedValue(null); 94 | 95 | try { 96 | await authService.login({ 97 | email: 'email', 98 | password: 'password', 99 | }); 100 | } catch (e) { 101 | expect(e.message).toBe('Login failed'); 102 | } 103 | expect(existSpy).toHaveBeenCalledWith('email'); 104 | }); 105 | 106 | it('should check for password correct', async () => { 107 | expect.assertions(3); 108 | 109 | const existSpy = jest 110 | .spyOn(userService, 'isUserExists') 111 | .mockResolvedValue(mockUserEntity); 112 | const checkPassSpy = jest 113 | .spyOn(userService, 'checkUserPassword') 114 | .mockResolvedValue(false); 115 | 116 | try { 117 | await authService.login({ 118 | email: 'email', 119 | password: 'password', 120 | }); 121 | } catch (e) { 122 | expect(e.message).toBe('Incorrect password'); 123 | } 124 | expect(existSpy).toHaveBeenCalledWith('email'); 125 | expect(checkPassSpy).toHaveBeenCalledWith(mockUserEntity, 'password'); 126 | }); 127 | 128 | it('should return session token', async () => { 129 | const existSpy = jest 130 | .spyOn(userService, 'isUserExists') 131 | .mockResolvedValue(mockUserEntity); 132 | const checkPassSpy = jest 133 | .spyOn(userService, 'checkUserPassword') 134 | .mockResolvedValue(true); 135 | const userTokenSpy = jest 136 | .spyOn(userService, 'getUserToken') 137 | .mockReturnValue('mock-token'); 138 | const userUpdateSpy = jest 139 | .spyOn(userService, 'updateUser') 140 | .mockResolvedValue(mockUserEntity); 141 | 142 | const token = await authService.login({ 143 | email: 'email', 144 | password: 'password', 145 | }); 146 | 147 | expect(token).toBe('mock-token'); 148 | expect(existSpy).toHaveBeenCalledWith('email'); 149 | expect(checkPassSpy).toHaveBeenCalledWith(mockUserEntity, 'password'); 150 | expect(userTokenSpy).toHaveBeenCalledWith(mockUserEntity); 151 | expect(userUpdateSpy).toHaveBeenCalledWith({ 152 | ...mockUserEntity, 153 | token: 'mock-token', 154 | }); 155 | }); 156 | }); 157 | }); 158 | -------------------------------------------------------------------------------- /api/src/user/services/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; 2 | import { CreateUserDto } from '../../dto/create-user.dto'; 3 | import { UserService } from '../user/user.service'; 4 | import { LoginDto } from '../../dto/login.dto'; 5 | import { UserEntity } from '../../entities/user.entity'; 6 | 7 | @Injectable() 8 | export class AuthService { 9 | constructor(private readonly userService: UserService) {} 10 | 11 | async register(userDto: CreateUserDto): Promise { 12 | // check if user exists and send custom error message 13 | if (await this.userService.isUserExists(userDto.email)) { 14 | throw new HttpException('User already exists', HttpStatus.BAD_REQUEST); 15 | } 16 | 17 | return await this.userService.createUser(userDto); 18 | } 19 | 20 | async login(loginRequest: LoginDto): Promise { 21 | const { email, password } = loginRequest; 22 | const user = await this.userService.isUserExists(email); 23 | 24 | if (!user) { 25 | return this.failLogin(); 26 | } 27 | 28 | if (await this.userService.checkUserPassword(user, password)) { 29 | const token = this.userService.getUserToken(user); 30 | user.token = token; 31 | await this.userService.updateUser(user); 32 | 33 | return token; 34 | } 35 | 36 | this.failLogin('Incorrect password'); 37 | } 38 | 39 | private failLogin(message = 'Login failed') { 40 | throw new HttpException(message, HttpStatus.BAD_REQUEST); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /api/src/user/services/auth/strategies/jwt/jwt.strategy.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { ConfigService } from '@nestjs/config'; 3 | import { JwtStrategy } from './jwt.strategy'; 4 | 5 | describe('JWT Strategy', () => { 6 | let strategy: JwtStrategy; 7 | 8 | beforeEach(async () => { 9 | const module: TestingModule = await Test.createTestingModule({ 10 | providers: [ 11 | JwtStrategy, 12 | { 13 | provide: ConfigService, 14 | useValue: { 15 | get: jest.fn().mockReturnValue('secret'), 16 | }, 17 | }, 18 | ], 19 | }).compile(); 20 | 21 | strategy = module.get(JwtStrategy); 22 | }); 23 | 24 | it('should be defined', () => { 25 | expect(strategy).toBeDefined(); 26 | }); 27 | 28 | it('should return payload on validate', async () => { 29 | expect(await strategy.validate('payload')).toBe('payload'); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /api/src/user/services/auth/strategies/jwt/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { ExtractJwt, Strategy } from 'passport-jwt'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { Injectable } from '@nestjs/common'; 4 | import { ConfigService } from '@nestjs/config'; 5 | 6 | @Injectable() 7 | export class JwtStrategy extends PassportStrategy(Strategy) { 8 | constructor(private readonly configService: ConfigService) { 9 | super({ 10 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 11 | ignoreExpiration: false, 12 | secretOrKey: configService.get('jwtSecret') as string, 13 | }); 14 | } 15 | 16 | async validate(payload: any) { 17 | return payload; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /api/src/user/services/jwt/jwt.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { JwtService } from './jwt.service'; 3 | import { ConfigService } from '@nestjs/config'; 4 | 5 | jest.mock('jsonwebtoken', () => { 6 | return { sign: jest.fn().mockReturnValue('jwt') }; 7 | }); 8 | 9 | describe('JwtService', () => { 10 | let service: JwtService; 11 | let config: ConfigService; 12 | 13 | beforeEach(async () => { 14 | const module: TestingModule = await Test.createTestingModule({ 15 | providers: [ 16 | JwtService, 17 | { 18 | provide: ConfigService, 19 | useValue: { 20 | get: jest.fn(), 21 | }, 22 | }, 23 | ], 24 | }).compile(); 25 | 26 | service = module.get(JwtService); 27 | config = module.get(ConfigService); 28 | }); 29 | 30 | it('should be defined', () => { 31 | expect(service).toBeDefined(); 32 | }); 33 | 34 | it('should be sign jwt tokens', () => { 35 | const configGetSpy = jest.spyOn(config, 'get').mockReturnValue('secret'); 36 | 37 | expect(service.sign('payload')).toBe('jwt'); 38 | expect(configGetSpy).toHaveBeenCalledWith('jwtSecret'); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /api/src/user/services/jwt/jwt.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { sign } from 'jsonwebtoken'; 3 | import { ConfigService } from '@nestjs/config'; 4 | 5 | @Injectable() 6 | export class JwtService { 7 | constructor(private readonly configService: ConfigService) {} 8 | 9 | sign(payload: string | Buffer | object): string { 10 | return sign(payload, this.configService.get('jwtSecret') as string, { 11 | expiresIn: '2h', 12 | }); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /api/src/user/services/password/password.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { PasswordService } from './password.service'; 3 | import { hash, compare } from 'bcryptjs'; 4 | 5 | jest.mock('bcryptjs', () => ({ 6 | hash: jest.fn(), 7 | compare: jest.fn(), 8 | })); 9 | 10 | describe('PasswordService', () => { 11 | let service: PasswordService; 12 | 13 | beforeEach(async () => { 14 | const module: TestingModule = await Test.createTestingModule({ 15 | providers: [PasswordService], 16 | }).compile(); 17 | 18 | service = module.get(PasswordService); 19 | }); 20 | 21 | it('should be defined', () => { 22 | expect(service).toBeDefined(); 23 | }); 24 | 25 | it('should generate passwords', async () => { 26 | const hashMock = jest.mocked(hash); 27 | hashMock.mockResolvedValue('mock-password' as never); 28 | expect(await service.generate('password')).toBe('mock-password'); 29 | }); 30 | 31 | it('should compare password hash', async () => { 32 | const compareMock = jest.mocked(compare); 33 | compareMock.mockResolvedValue(true as never); 34 | expect(await service.compare('password', 'hash')).toBe(true); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /api/src/user/services/password/password.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { hash, compare } from 'bcryptjs'; 3 | 4 | @Injectable() 5 | export class PasswordService { 6 | async generate(rawPassword: string) { 7 | return await hash(rawPassword, 10); 8 | } 9 | 10 | async compare(requestPassword: string, hash: string): Promise { 11 | return await compare(requestPassword, hash); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /api/src/user/services/user/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UserService } from './user.service'; 3 | import { getRepositoryToken } from '@nestjs/typeorm'; 4 | import { UserEntity } from '../../entities/user.entity'; 5 | import { PasswordService } from '../password/password.service'; 6 | import { JwtService } from '../jwt/jwt.service'; 7 | import { ConfigService } from '@nestjs/config'; 8 | import { Repository } from 'typeorm'; 9 | import { mockUserEntity } from '../../entities/__fixtures__/user-entity.fixture'; 10 | 11 | describe('UserService', () => { 12 | let service: UserService; 13 | let repo: Repository; 14 | let passwordService: PasswordService; 15 | let jwtService: JwtService; 16 | 17 | beforeEach(async () => { 18 | const module: TestingModule = await Test.createTestingModule({ 19 | providers: [ 20 | UserService, 21 | ConfigService, 22 | PasswordService, 23 | JwtService, 24 | { 25 | provide: getRepositoryToken(UserEntity), 26 | useValue: { 27 | find: jest.fn(), 28 | findOne: jest.fn(), 29 | create: jest.fn(), 30 | save: jest.fn(), 31 | }, 32 | }, 33 | ], 34 | }).compile(); 35 | 36 | service = module.get(UserService); 37 | passwordService = module.get(PasswordService); 38 | jwtService = module.get(JwtService); 39 | repo = module.get>(getRepositoryToken(UserEntity)); 40 | }); 41 | 42 | it('should be defined', () => { 43 | expect(service).toBeDefined(); 44 | }); 45 | 46 | it('should be able to check user existence', async () => { 47 | const findOneSpy = jest.spyOn(repo, 'findOne').mockResolvedValue(null); 48 | 49 | expect(await service.isUserExists('mail')).toBe(null); 50 | expect(findOneSpy).toHaveBeenCalledWith({ 51 | where: { 52 | email: 'mail', 53 | }, 54 | }); 55 | }); 56 | 57 | it('should be able to create user', async () => { 58 | const passwordSpy = jest 59 | .spyOn(passwordService, 'generate') 60 | .mockResolvedValue('password-hash'); 61 | const jwtSpy = jest.spyOn(jwtService, 'sign').mockReturnValue('jwt'); 62 | const createSpy = jest 63 | .spyOn(repo, 'create') 64 | .mockReturnValue(mockUserEntity); 65 | const saveSpy = jest.spyOn(repo, 'save').mockResolvedValue(mockUserEntity); 66 | 67 | const newUser = await service.createUser({ 68 | email: 'EMAIL', 69 | firstName: 'fName', 70 | lastName: 'lName', 71 | password: 'password', 72 | }); 73 | 74 | expect(newUser).toStrictEqual(mockUserEntity); 75 | expect(passwordSpy).toHaveBeenCalledWith('password'); 76 | expect(saveSpy).toHaveBeenCalledTimes(2); 77 | expect(jwtSpy).toHaveBeenCalledWith({ 78 | id: 0, 79 | email: 'email', 80 | firstName: 'fName', 81 | lastName: 'lName', 82 | }); 83 | expect(createSpy).toHaveBeenCalledWith({ 84 | email: 'email', 85 | firstName: 'fName', 86 | lastName: 'lName', 87 | passwordHash: 'password-hash', 88 | }); 89 | }); 90 | 91 | it('should check user password', async () => { 92 | const compareSpy = jest 93 | .spyOn(passwordService, 'compare') 94 | .mockResolvedValue(true); 95 | 96 | expect( 97 | await service.checkUserPassword(mockUserEntity, 'request-password'), 98 | ).toBe(true); 99 | expect(compareSpy).toHaveBeenCalledWith( 100 | 'request-password', 101 | mockUserEntity.passwordHash, 102 | ); 103 | }); 104 | 105 | it('should get all users', async () => { 106 | const repoSpy = jest 107 | .spyOn(repo, 'find') 108 | .mockResolvedValue([mockUserEntity]); 109 | 110 | expect(await service.getAll()).toStrictEqual([mockUserEntity]); 111 | expect(repoSpy).toHaveBeenCalledWith({ 112 | select: ['id', 'email', 'lastName', 'firstName'], 113 | }); 114 | }); 115 | }); 116 | -------------------------------------------------------------------------------- /api/src/user/services/user/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { InjectRepository } from '@nestjs/typeorm'; 3 | import { UserEntity } from '../../entities/user.entity'; 4 | import { Repository } from 'typeorm'; 5 | import { CreateUserDto } from '../../dto/create-user.dto'; 6 | import { PasswordService } from '../password/password.service'; 7 | import { JwtService } from '../jwt/jwt.service'; 8 | 9 | @Injectable() 10 | export class UserService { 11 | constructor( 12 | @InjectRepository(UserEntity) 13 | private usersRepository: Repository, 14 | private readonly passwordService: PasswordService, 15 | private readonly jwtService: JwtService, 16 | ) {} 17 | 18 | async isUserExists(email: string): Promise { 19 | return this.usersRepository.findOne({ 20 | where: { 21 | email: email.toLowerCase(), 22 | }, 23 | }); 24 | } 25 | 26 | async createUser(userDto: CreateUserDto): Promise { 27 | const userPayload = { 28 | email: userDto.email.toLowerCase(), 29 | firstName: userDto.firstName, 30 | lastName: userDto.lastName, 31 | passwordHash: await this.passwordService.generate(userDto.password), 32 | }; 33 | 34 | let newUser = this.usersRepository.create(userPayload); 35 | newUser = await this.updateUser(newUser); 36 | 37 | newUser.token = this.getUserToken(newUser); 38 | return await this.updateUser(newUser); 39 | } 40 | 41 | async updateUser(newUser: UserEntity): Promise { 42 | return await this.usersRepository.save(newUser); 43 | } 44 | 45 | async checkUserPassword( 46 | user: UserEntity, 47 | requestPassword: string, 48 | ): Promise { 49 | return this.passwordService.compare(requestPassword, user.passwordHash); 50 | } 51 | 52 | public getUserToken(user: UserEntity): string { 53 | return this.jwtService.sign({ 54 | id: user.id, 55 | email: user.email.toLowerCase(), 56 | firstName: user.firstName, 57 | lastName: user.lastName, 58 | }); 59 | } 60 | 61 | public getAll(): Promise { 62 | return this.usersRepository.find({ 63 | select: ['id', 'email', 'lastName', 'firstName'], 64 | }); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /api/src/user/user.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UserController } from './user.controller'; 3 | import { AuthService } from './services/auth/auth.service'; 4 | import { UserService } from './services/user/user.service'; 5 | import { PasswordService } from './services/password/password.service'; 6 | import { ConfigService } from '@nestjs/config'; 7 | import { JwtService } from './services/jwt/jwt.service'; 8 | import { getRepositoryToken } from '@nestjs/typeorm'; 9 | import { UserEntity } from './entities/user.entity'; 10 | import { mockUserEntity } from './entities/__fixtures__/user-entity.fixture'; 11 | 12 | describe('UserController', () => { 13 | let controller: UserController; 14 | let authService: AuthService; 15 | let userService: UserService; 16 | 17 | beforeEach(async () => { 18 | const module: TestingModule = await Test.createTestingModule({ 19 | controllers: [UserController], 20 | providers: [ 21 | AuthService, 22 | UserService, 23 | PasswordService, 24 | ConfigService, 25 | JwtService, 26 | { 27 | provide: getRepositoryToken(UserEntity), 28 | useValue: {}, 29 | }, 30 | { 31 | provide: 'CACHE_MANAGER', 32 | useValue: jest.fn(), 33 | }, 34 | ], 35 | }).compile(); 36 | 37 | controller = module.get(UserController); 38 | authService = module.get(AuthService); 39 | userService = module.get(UserService); 40 | }); 41 | 42 | it('should be defined', () => { 43 | expect(controller).toBeDefined(); 44 | }); 45 | 46 | describe('register method', () => { 47 | it('should register user', async () => { 48 | jest.spyOn(authService, 'register').mockResolvedValue({ 49 | id: 0, 50 | token: 'token', 51 | firstName: 'firstName', 52 | lastName: 'lastName', 53 | email: 'email', 54 | passwordHash: 'p', 55 | }); 56 | 57 | expect( 58 | await controller.register({ 59 | firstName: 'firstName', 60 | lastName: 'lastName', 61 | email: 'email', 62 | password: 'p', 63 | }), 64 | ).toStrictEqual({ 65 | message: 'User created', 66 | user: { 67 | id: 0, 68 | token: 'token', 69 | }, 70 | }); 71 | }); 72 | }); 73 | 74 | describe('login method', () => { 75 | it('should login user', async () => { 76 | jest.spyOn(authService, 'login').mockResolvedValue('mock-token'); 77 | 78 | expect( 79 | await controller.login({ 80 | email: 'email', 81 | password: 'p', 82 | }), 83 | ).toStrictEqual({ 84 | message: 'Login successful', 85 | token: 'mock-token', 86 | }); 87 | }); 88 | }); 89 | 90 | describe('getUsers method', () => { 91 | it('should retrieve all users', async () => { 92 | const userServiceSpy = jest 93 | .spyOn(userService, 'getAll') 94 | .mockResolvedValue([mockUserEntity]); 95 | 96 | expect(await controller.getUsers()).toStrictEqual({ 97 | message: 'Users retrieved successfully', 98 | users: [mockUserEntity], 99 | }); 100 | expect(userServiceSpy).toHaveBeenCalledTimes(1); 101 | }); 102 | }); 103 | }); 104 | -------------------------------------------------------------------------------- /api/src/user/user.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, 3 | Controller, 4 | Get, 5 | Post, 6 | UseGuards, 7 | UseInterceptors, 8 | } from '@nestjs/common'; 9 | import { CreateUserDto } from './dto/create-user.dto'; 10 | import { AuthService } from './services/auth/auth.service'; 11 | import { LoginDto } from './dto/login.dto'; 12 | import { UserService } from './services/user/user.service'; 13 | import { JwtAuthGuard } from './guards/jwt-auth/jwt-auth.guard'; 14 | import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; 15 | import { CacheInterceptor } from '@nestjs/cache-manager'; 16 | 17 | @ApiTags('user') 18 | @Controller('user') 19 | export class UserController { 20 | constructor( 21 | private readonly authService: AuthService, 22 | private readonly userService: UserService, 23 | ) {} 24 | 25 | @Post('register') 26 | async register(@Body() user: CreateUserDto) { 27 | const newUser = await this.authService.register(user); 28 | 29 | return { 30 | message: 'User created', 31 | user: { 32 | id: newUser.id, 33 | token: newUser.token, 34 | }, 35 | }; 36 | } 37 | 38 | @Post('login') 39 | async login(@Body() login: LoginDto) { 40 | const token = await this.authService.login(login); 41 | 42 | return { 43 | message: 'Login successful', 44 | token, 45 | }; 46 | } 47 | 48 | @ApiBearerAuth() 49 | @UseGuards(JwtAuthGuard) 50 | @UseInterceptors(CacheInterceptor) 51 | @Get() 52 | async getUsers() { 53 | const users = await this.userService.getAll(); 54 | 55 | return { 56 | message: 'Users retrieved successfully', 57 | users, 58 | }; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /api/src/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UserController } from './user.controller'; 3 | import { AuthService } from './services/auth/auth.service'; 4 | import { TypeOrmModule } from '@nestjs/typeorm'; 5 | import { UserEntity } from './entities/user.entity'; 6 | import { UserService } from './services/user/user.service'; 7 | import { PasswordService } from './services/password/password.service'; 8 | import { JwtService } from './services/jwt/jwt.service'; 9 | import { ConfigModule } from '@nestjs/config'; 10 | import { JwtStrategy } from './services/auth/strategies/jwt/jwt.strategy'; 11 | import { AppCacheModule } from '../app-cache/app-cache.module'; 12 | 13 | @Module({ 14 | imports: [ 15 | TypeOrmModule.forFeature([UserEntity]), 16 | ConfigModule, 17 | AppCacheModule, 18 | ], 19 | controllers: [UserController], 20 | providers: [ 21 | AuthService, 22 | UserService, 23 | PasswordService, 24 | JwtService, 25 | JwtStrategy, 26 | ], 27 | }) 28 | export class UserModule {} 29 | -------------------------------------------------------------------------------- /api/test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /api/test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /api/test/test-utils/cache.mock.ts: -------------------------------------------------------------------------------- 1 | import { Cache } from 'cache-manager'; 2 | 3 | export const getCacheMock = (): Partial => { 4 | return { 5 | get: jest.fn(), 6 | set: jest.fn(), 7 | del: jest.fn(), 8 | }; 9 | }; 10 | -------------------------------------------------------------------------------- /api/tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /api/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "forceConsistentCasingInFileNames": false, 16 | "noFallthroughCasesInSwitch": false, 17 | "strictNullChecks": true, 18 | "noImplicitAny": true, 19 | "strictBindCallApply": true 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /api/type-orm.config.ts: -------------------------------------------------------------------------------- 1 | import { DataSource } from 'typeorm'; 2 | import * as dotenv from 'dotenv'; 3 | import { getConfig } from './src/services/app-config/configuration'; 4 | 5 | dotenv.config(); 6 | 7 | const { 8 | database: { host, port, password, user, dbName }, 9 | } = getConfig(); 10 | 11 | export default new DataSource({ 12 | type: 'postgres', 13 | host, 14 | port, 15 | username: user, 16 | password, 17 | database: dbName, 18 | entities: ['src/**/*.entity.ts'], 19 | migrations: ['src/**/migrations/*.ts'], 20 | subscribers: ['src/**/subscribers/*.ts'], 21 | }); 22 | --------------------------------------------------------------------------------