Coder Social home page Coder Social logo

andrechristikan / ack-nestjs-boilerplate Goto Github PK

View Code? Open in Web Editor NEW
478.0 16.0 159.0 7.56 MB

NestJs v10.x Boilerplate. Repository Design Pattern. MongoDB (Mongoose). Containerization.

License: MIT License

TypeScript 99.99% Shell 0.01%
nestjs nestjs-backend nestjs-starter-template nestjs-boilerplate nestjs-example typescript mongoose nodejs mongodb nestjs-mongo

ack-nestjs-boilerplate's Introduction

Contributors Forks Stargazers Issues MIT License

NestJs NodeJs Typescript MongoDB JWT Jest Yarn Docker

ACK NestJs Boilerplate 🔥 🚀

This repo will representative of authentication service and authorization service

ACK NestJs is a Http NestJs v10.x boilerplate. Best uses for backend service.

You can request feature or report bug with following this link

Table of contents

Important

Very limited documentation

  • The features will be relate with AWS / Amazon web service
  • Stateless Authorization
  • If you want to implement database transactions. You must run MongoDB as a replication set.
  • If you want to implement Google SSO. You must have google cloud console account, then create your own SSO / Credential API to get the clientId and clientSecret.
  • If you change the environment value of APP_ENV to production, that will trigger.
    1. CorsMiddleware will implement config from src/configs/middleware.config.ts.
    2. Documentation will disable.
  • For monitoring, this project will use sentry.io, and only send 500 or internal server error.

Todo

  • Remove Debugger HTTP
  • Setting Move to Modules
  • Debugger env change
  • Add exception filter to Sentry.io
  • Add Email Module with AWS SES
  • CI Push docker image to AWS ECR, currently using Docker Hub
  • CD Using AWS ECS and deploy to AWS EC2, currently only using AWS EC2
  • Update Package, and remove unused package
  • Update Documentation, add behaviors
  • Update Documentation, and include an diagram for easier comprehension
  • Add Redis / Move to stateful Authorization Token (security and ux reason)
  • Implement GraphQL, just an options for running ?

Documentation

Documentation of ack-nestjs-boilerplate in /docs

License

Distributed under MIT licensed.

Contribute

How to contribute in this repo

  1. Fork the project with click Fork button of this repo.

  2. Clone the fork project

    git clone "url you just copied"
  3. Make necessary changes and commit those changes

  4. Commit the changes

    git commit -m "your message"
  5. Push changes to fork project

    git push origin -u main
  6. Back to browser, goto your fork repo github. Then, click Compare & pull request

If your code behind commit with the original, please update your code and resolve the conflict. Then, repeat from number 6.

Contact

Andre Christi kan

Github LinkedIn

ack-nestjs-boilerplate's People

Contributors

aallithioo avatar admondtamang avatar ak2g avatar andrechristikan avatar bipinparajuli avatar dependabot[bot] avatar psheon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ack-nestjs-boilerplate's Issues

Docker compose service dependency to ackDatabase

Hello,

There is a service dependency ackDatabase for service in docker-compose file that there is not exist in the docker-compose.yml

I think the service should depend on mongo1 service. Am I right?

the demo isnt working

I just cloned the project, and changed the db config to connect it to mongo atlas. However, I see an error which is hard to track here.
As soon as i navigate to route http://localhost:4000/docs#/hello
and try the very first section i am getting error, Please refer to the screenshot below
Screenshot 2023-03-29 at 10 41 29 AM

apikey problem

When i try to test /api/hello/api-key i get this error apiKey.error.expired

Remove "format:e2e": "prettier --write e2e/**/*.ts" from package.json

"format:e2e": "prettier --write e2e/**/*.ts" which is found in package.json is not functional. So that is causing the following error while formatting the code with prettier.

$ prettier --write e2e/**/*.ts
[error] No files matching the pattern were found: "e2e/**/*.ts".
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

So please remove that. Thanks! You guys are awesome!

Import and use another services

I want to test the method usage of another service and get an error. How can I get this to work. I'm just testing

"Nest can't resolve dependencies of the UserService (UserRepository, ?, HelperDateService, HelperStringService, ConfigService). Please make sure that the argument RoleService at index [1] is available in the UserModule context."

500 Internal Server for every api endpoint

Like the title, i clone the app and start:dev and navigate to /docs. I tried healthcheck, /hello but all the same

{
"statusCode": 500,
"message": "Internal Server Error",
"_metadata": {
"languages": [
"en"
],
"timestamp": 1685074450439,
"timezone": "Asia/Saigon",
"requestId": "adab6ee8-71ba-41d9-8fd5-5e147a06c7fd",
"path": "/",
"version": "1",
"repoVersion": "5.2.3"
}
}

the console is clean, no error was shown

role creation

while creating custom role using the endpoint .../admin/role/create
returns error message of "message": "policy.error.abilityForbidden",

Migration Seed - Unexpected Token

Hi,

I was trying to run the seeding but I've encounter this issue

 ...dir\nestjs-mongodb\dist\src\common\database\abstracts\mongo\entities\database.mongo.uuid.entity.abstract.js:19
    static { _a = database_constant_1.DATABASE_DELETED_AT_FIELD_NAME, _b = database_constant_1.DATABASE_CREATED_AT_FIELD_NAME, _c = database_constant_1.DA
TABASE_UPDATED_AT_FIELD_NAME; }

I have updated the .env file with my config. but still cannot seed nor run the app.

Login/Refresh Issues

{
    "email":"[email protected]",
    "password":"aaAA@@123444",
    "rememberMe":false
}

login only works if rememberMe set to false, if set to true, nestjs log returning:

Sys log

[Nest] 17068 - 03/23/2022, 8:33:34 AM ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'replace') TypeError: Cannot read properties of undefined (reading 'replace') at AuthService.loginExpiredDate (D:\www\recipe-fork\recipefork-services\src\auth\service\auth.service.ts:132:57) at AuthService.createPayloadAccessToken (D:\www\recipe-fork\recipefork-services\src\auth\service\auth.service.ts:143:45) at AuthCommonController.login (D:\www\recipe-fork\recipefork-services\src\auth\controller\auth.common.controller.ts:123:36)

Also, in postman, refreshToken/ {{baseUrl}}/refresh endpoint functionality does not work, and postman collection is still looking for adminRefreshToken, but that is no longer coming through login payload

postman /auth/refresh returns error

I am honored to use this library. Thanks to the author for the creation. I have found a problem in use.

{{refreshToken}} has used the refreshToken value returned after login, set it to postman's global variable refreshToken

{
    "statusCode": 5103,
    "message": "Unauthorized"
}

rate-limit problem ?

I am trying to ping so many times in the login api but the rate limit is not working?

Api Key Issue

Hello,
When I want to fetch the settings information, it gives an x-api-key error. I am currently using the most recent version you posted on September 28. Sometimes when I make a request on localhost, the project terminates itself. What can I do for its solution? I have given all the necessary information below. Thank you for your project.

==========================================
"userAgent": {
"ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.47",
"browser": {
"name": "Edge",
"version": "104.0.1293.47",
"major": "104"
},
"engine": {
"name": "Blink",
"version": "104.0.5112.81"
},
"os": {
"name": "Mac OS",
"version": "10.15.7"
},
"device": {},
"cpu": {}
},

authapis record
{
"_id": "6332f995377f9750cd2c06c8",
"name": "auth api key migration",
"description": "From migration",
"key": "qwertyuiop12345zxcvbnmkjh",
"hash": "e11a023bc0ccf713cb50de9baa5140e59d3d4c52ec8952d9ca60326e040eda54",
"encryptionKey": "opbUwdiS1FBsrDUoPgZdx",
"passphrase": "cuwakimacojulawu",
"isActive": true,
"createdAt": ISODate('2022-09-27T13:24:37.808Z'),
"updatedAt": ISODate('2022-09-27T13:24:37.808Z')
}
x-api-key : qwertyuiop12345zxcvbnmkjh

curl -X 'GET'
'http://127.0.0.1:3000/api/v1/setting/list?page=1&perPage=20&sort=createdAt%40desc'
-H 'accept: application/json'
-H 'x-timestamp: 1662876305642'
-H 'x-custom-lang: en'
-H 'user-agent: Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion'
-H 'x-api-key: qwertyuiop12345zxcvbnmkjh'

API Key Error :
/Users/yavuzgunay/Projects/ack-nestjs-boilerplate-mongoose/node_modules/crypto-js/cipher-core.js:876
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
^
TypeError: Cannot read properties of undefined (reading 'salt')
at Object.decrypt (/Users/yavuzgunay/Projects/ack-nestjs-boilerplate-mongoose/node_modules/crypto-js/cipher-core.js:876:102)
at Object.decrypt (/Users/yavuzgunay/Projects/ack-nestjs-boilerplate-mongoose/node_modules/crypto-js/cipher-core.js:205:59)
at HelperEncryptionService.aes256Decrypt (/Users/yavuzgunay/Projects/ack-nestjs-boilerplate-mongoose/src/common/helper/services/helper.encryption.service.ts:45:28)
at AuthApiService.decryptApiKey (/Users/yavuzgunay/Projects/ack-nestjs-boilerplate-mongoose/src/common/auth/services/auth.api.service.ts:281:56)
at ApiKeyStrategy.validate (/Users/yavuzgunay/Projects/ack-nestjs-boilerplate-mongoose/src/common/auth/guards/api-key/auth.api-key.strategy.ts:59:43)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

====================================================
.env

APP_NAME=ACK
APP_ENV=development
APP_LANGUAGE=en

HTTP_ENABLE=true
HTTP_HOST=localhost
HTTP_PORT= 3000
HTTP_VERSIONING_ENABLE=true
HTTP_VERSION=1

DEBUGGER_HTTP_WRITE_INTO_FILE=false
DEBUGGER_SYSTEM_WRITE_INTO_FILE=false

MIDDLEWARE_TIMESTAMP_TOLERANCE=3h
MIDDLEWARE_TIMEOUT=30s

DOC_NAME=ACK APIs Spec
DOC_VERSION=1

JOB_ENABLE=false

DATABASE_HOST=mongodb://xxxxx
DATABASE_NAME=xxxxxDB
DATABASE_USER=xxxxxUser
DATABASE_PASSWORD=xxxxxx
DATABASE_DEBUG=false
DATABASE_OPTIONS=readPreference=primary&ssl=false

AUTH_JWT_SUBJECT=AckDevelopment
AUTH_JWT_ISSUER=ack
AUTH_JWT_AUDIENCE=https://example.com

AUTH_JWT_ACCESS_TOKEN_SECRET_KEY=123456
AUTH_JWT_ACCESS_TOKEN_EXPIRED=3h

AUTH_JWT_REFRESH_TOKEN_SECRET_KEY=01001231
AUTH_JWT_REFRESH_TOKEN_EXPIRED=7d
AUTH_JWT_REFRESH_TOKEN_REMEMBER_ME_EXPIRED=30d
AUTH_JWT_REFRESH_TOKEN_NOT_BEFORE_EXPIRATION=30m

SERVERLESS_AWS_API_GATEWAY=baibay
SERVERLESS_AWS_PROFILE=baibay
SERVERLESS_AWS_S3_BUCKET=baibay-development

AWS_S3_REGION=ap-southeast-3
AWS_S3_BUCKET=baibay-development

exception.getResponse() is not IErrorException

[error.http.filter.ts]

response is not always IErrorException type

so those values were undefined
{
statusCode: undefined,
message: undefined,
errors: undefined,
data: undefined,
properties: undefined
}

[Nest] 6383 - 07/17/2022, 2:23:28 PM ERROR [HealthCheckService] Health Check has failed! {"diskHealth":{"status":"down","message":"Used disk storage exceeded the set threshold"}}
(node:6383) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'split' of undefined
at I18nService.translateObject (/Users/Shahanul/WebstormProjects/ack-nestjs-boilerplate-mongoose/node_modules/nestjs-i18n/src/services/i18n.service.ts:148:22)
at I18nService.translate (/Users/Shahanul/WebstormProjects/ack-nestjs-boilerplate-mongoose/node_modules/nestjs-i18n/src/services/i18n.service.ts:72:30)
at MessageService.setMessage (/Users/Shahanul/WebstormProjects/ack-nestjs-boilerplate-mongoose/src/message/service/message.service.ts:116:26)
at MessageService.get (/Users/Shahanul/WebstormProjects/ack-nestjs-boilerplate-mongoose/src/message/service/message.service.ts:90:55)
at ErrorHttpFilter.catch (/Users/Shahanul/WebstormProjects/ack-nestjs-boilerplate-mongoose/src/utils/error/filter/error.http.filter.ts:59:73)
at ExceptionsHandler.invokeCustomFilters (/Users/Shahanul/WebstormProjects/ack-nestjs-boilerplate-mongoose/node_modules/@nestjs/core/exceptions/exceptions-handler.js:33:26)
at ExceptionsHandler.next (/Users/Shahanul/WebstormProjects/ack-nestjs-boilerplate-mongoose/node_modules/@nestjs/core/exceptions/exceptions-handler.js:13:18)
at /Users/Shahanul/WebstormProjects/ack-nestjs-boilerplate-mongoose/node_modules/@nestjs/core/router/router-proxy.js:13:35
(Use node --trace-warnings ... to show where the warning was created)
(node:6383) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 6)
(node:6383) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Integration with GraphQL

Firstly this is an awesome repo. We really appreciate the time and effort you put to this repository.

But if it is possible can you please update this repo to support GraphQL. That would be really awesome. Thanks!

Auth problems?

I freshly started this app but can't get auth mechanism to work.

Login is fine so I take the accessToken from 'admin' login action and paste it in the accessToken on swagger for GET b/api/v1/admin/role/list
image

But then I get an error
"statusCode": 5102, "message": "auth.error.permissionTokenUnauthorized", "error": "auth.error.permissionTokenUnauthorized"

When I set 'x-permission-token' header I get:
"statusCode": 5106, "message": "Permission not allowed", "error": "auth.error.permissionForbidden"

So how to make it work?

Unable to connect to the database. Retrying (1)...

Here is my .env file, when run yarn start:dev cannot connect to database

Screenshot 2024-01-02 at 23 34 42

APP_NAME=ACK
APP_ENV=development
APP_LANGUAGE=en
APP_TZ=Asia/Jakarta
APP_MAINTENANCE=false

HTTP_ENABLE=true
HTTP_HOST=localhost
HTTP_PORT= 3000
HTTP_VERSIONING_ENABLE=true
HTTP_VERSION=1

DEBUGGER_WRITE_INTO_FILE=false

JOB_ENABLE=false

DATABASE_HOST=mongodb://localhost:30001,localhost:30002,localhost:30003
DATABASE_NAME=ack
DATABASE_USER=
DATABASE_PASSWORD=
DATABASE_DEBUG=false
DATABASE_OPTIONS=replicaSet=rs0&retryWrites=true&w=majority

AUTH_JWT_SUBJECT=AckDevelopment
AUTH_JWT_ISSUER=ack
AUTH_JWT_AUDIENCE=https://example.com

AUTH_JWT_ACCESS_TOKEN_EXPIRED=1h
AUTH_JWT_ACCESS_TOKEN_SECRET_KEY=123456789012345678901234567890
AUTH_JWT_REFRESH_TOKEN_EXPIRED=182d
AUTH_JWT_REFRESH_TOKEN_SECRET_KEY=098765432112345678901234567890

AUTH_JWT_PAYLOAD_ENCRYPT=false
AUTH_JWT_PAYLOAD_ACCESS_TOKEN_ENCRYPT_KEY=qwerty12345678901234567890
AUTH_JWT_PAYLOAD_ACCESS_TOKEN_ENCRYPT_IV=12345612345678901234567890
AUTH_JWT_PAYLOAD_REFRESH_TOKEN_ENCRYPT_KEY=ytrewq12345678901234567890
AUTH_JWT_PAYLOAD_REFRESH_TOKEN_ENCRYPT_IV=65432112345678901234567890

AWS_S3_CREDENTIAL_KEY=
AWS_S3_CREDENTIAL_SECRET=
AWS_S3_REGION=ap-southeast-3
AWS_S3_BUCKET=
AWS_SES_CREDENTIAL_KEY=
AWS_SES_CREDENTIAL_SECRET=
AWS_SES_REGION=ap-southeast-3

KAFKA_CLIENT_ID=KAFKA_ACK
KAFKA_ADMIN_CLIENT_ID=KAFKA_ADMIN_ACK
KAFKA_BROKERS=localhost:9092
KAFKA_CONSUMER_ENABLE=true
KAFKA_CONSUMER_GROUP=nestjs.ack

SSO_GOOGLE_CLIENT_ID=
SSO_GOOGLE_CLIENT_SECRET=

SENTRY_DSN=

Api key Issue

when I try to access /hello/api-key
I got "Need API Key message"

found real emails in log files

hello sir,
many thanks for your great effort to build something like that,
can you explain to me why in the server log files i found real email and i tried so hard to foud where they come from
here the log file

`'::ffff:127.0.0.1' - '-' - '[2022-05-31T16:39:38.153Z]' - 'HTTP/1.1' - '[200]' - 'GET' - '/health/database' - 'Request Header :: {

{"_id":"62964577e5cf5e793d7f7dfc","firstName":"[email protected]","lastName":"bradtke","mobileNumber":"62812378789821","email":"[email protected]","isActive":true,"createdAt":"2022-05-31T16:42:31.698Z"}]

{"firstName":"Annabel","lastName":"Koss","password":"@!maryCURTIS44","email":"[email protected]","mobileNumber":"62812233040271","role":"62964578e5cf5e793d7f7e15"}'

{"firstName":"Annabel","lastName":"Koss","password":"@!maryCURTIS44","email":"[email protected]","mobileNumber":"62812378789821","role":"62946993d8a7379004cd1630"}' - 'Response Header :: -' - 'Response Body ::

`

500 Internal Server Error '/api/v1/auth/user/info'

i got error when use api /api/v1/auth/user/info. i think payload didn't have permissions in role field

{
  _id: 'e7c230b4-0740-4709-8cd4-1fe6e0072300',
  class: 'UserAuthController',
  function: 'info',
  path: '/api/v1/auth/user/info',
  data: TypeError: Cannot read properties of undefined (reading 'map')
      at Object.transformFn (E:\0.Chopbk\ack-nestjs-boilerplate\src\modules\user\serializations\user.payload.serialization.ts:57:37)
      at E:\0.Chopbk\ack-nestjs-boilerplate\node_modules\src\TransformOperationExecutor.ts:412:24
      at Array.forEach (<anonymous>)
      at TransformOperationExecutor.applyCustomTransformations (E:\0.Chopbk\ack-nestjs-boilerplate\node_modules\src\TransformOperationExecutor.ts:411:15)
      at TransformOperationExecutor.transform (E:\0.Chopbk\ack-nestjs-boilerplate\node_modules\src\TransformOperationExecutor.ts:334:33)
      at ClassTransformer.plainToInstance (E:\0.Chopbk\ack-nestjs-boilerplate\node_modules\src\ClassTransformer.ts:77:21)
      at plainToInstance (E:\0.Chopbk\ack-nestjs-boilerplate\node_modules\src\index.ts:84:27)
      at E:\0.Chopbk\ack-nestjs-boilerplate\src\common\response\interceptors\response.default.interceptor.ts:108:51
      at processTicksAndRejections (node:internal/process/task_queues:96:5),
  level: 'error',
  message: "Cannot read properties of undefined (reading 'map')",
  timestamp: '2023-06-23T09:43:16.929Z'
}

E2E And Integration Tests

@andrechristikan What do you think about including integration and E2E tests? Do you have a plan to add it in the most recent versions? I believe that both tests were integrated into the most recent versions.

Search logic in route /list.

Hi @andrechristikan,

Currently availableSort and availableSearch in route /list are not working
Is there any security issues if I changing from

if (search) {
  find['$or'] = [
    {
      firstName: {
        $regex: new RegExp(search),
        $options: 'i',
      },
      lastName: {
        $regex: new RegExp(search),
        $options: 'i',
      },
      email: {
        $regex: new RegExp(search),
        $options: 'i',
      },
      mobileNumber: search,
    },
  ];
}

to

if (search) {
  find['$or'] = availableSearch.map((searchKey) => ({
    [searchKey]: {
      $regex: new RegExp(search),
      $options: 'i',
    },
  }));
}

Clear Understanding about Api Key Encryption

Firstly @andrechristikan you really did a good work with this boilerplate, But i don't understand the APi key encryption aspect, which file are we to create all the code, for the APi key encryption, because i saw some api error that relate to apiKey. i am actually using the one generated in the migration but it not working.

Boilerplate Error

Upon forking from [4a5c348](4a5c348)

After installing dependencies and running npm run start:dev or npm run seed.

The error: <project>/src/common/database/abstracts/mongo/entities/database.mongo.uuid.entity.abstract.ts:19 static { _a = database_constant_1.DATABASE_DELETED_AT_FIELD_NAME, _b = database_constant_1.DATABASE_CREATED_AT_FIELD_NAME, _c = database_constant_1.DATABASE_UPDATED_AT_FIELD_NAME; } occurs despite no code changes.

ERROR [I18nService] Translation

calling /message/languages endpoint using Postman returns

{ "statusCode": 404,
    "message": "Cannot GET /message/languages",
    ...
    }

and the Terminal logs
ERROR [I18nService] Translation "Cannot GET /message/languages" in "en" does not exist.
the same error appears when calling similar public endpoints like /user/sign-up

Why do we have a try/catch block at the end of every api in the controller ?

Could this not be done using a catchAsync helper function? Because it has lots of code duplication and makes the code ugly. Great BP by the way. Or adding a global error handler ?

const catchAsync = (fn) => (req, res, next) => {
    Promise.resolve(fn(req, res, next)).catch((err) => {
        throw new InternalServerErrorException({
          statusCode: ENUM_ERROR_STATUS_CODE_ERROR.ERROR_UNKNOWN,
          message: 'http.serverError.internalServerError',
          _error: err.message,
        });
      )
    }

Unable to get original ObjectID from the document

Whenever I am retrieving any document, classSerialization is automatically changing all fields that contains ObjectID to a new ObjectID instead of retaining the actual value. I don't understand why, I want to retain original ObjectID of the document.

When I remove serialization, I get ObjectIds just fine. it just when I use serialization, my output gets affected.

here's my schema

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Types, Document } from 'mongoose';
@Schema({ timestamps: true, versionKey: false })
export class ArticleEntity {
   @Prop({
        required: true,
        auto: false,
    })
    _id: Types.ObjectId;
    
    @Prop({
        required: true,
        auto: false,
    })
    article_id: Types.ObjectId;

    @Prop({
        required: true,
        index: true,
    })
    title: string;
}
export const ArticleSchema = SchemaFactory.createForClass(ArticleEntity);
export type ArticleDocument = ArticleEntity & Document;

Controller Action

@Response('article.content',{classSerialization: ArticleContentSerialization})
    @Get('/:ARTICLE_ID/get')
    async getArticleContent(
        @Param('ARTICLE_ID') article_id: string
    ): Promise<IResponse> {
        const find: Record<string, any> = {
            _id: new Types.ObjectId(article_id)
        };
        const article_data : ArticleDocument = await this.articleService.findOne(find);
        return {
            content: article_data.content
        }
    }

SerializationClass

export class ArticleContentSerialization {
    
    @ApiProperty({
        example: "This is dummy Title"
    })
    title: string;
}

In DB the document is like this

 {
      "_id": ObjectId("6345926ddf03e6c3b58149c9"),
      "article_id": ObjectId("634553886b196dca90a72d7d"),
      "title": "Awesome article"
}

And when I retrieve it, I get document like this

 {
     "_id": "6376255082e77cbab9f0eb59",
     "article_id": "6376255082e77cbab9f0eb5a",
     "title": "Awesome article"
}

I couldn't find this behaviour in vanila nest js/mongoose.

Error: Nest can't resolve dependencies of the LoggerService (?). Please make sure that the argument LoggerEntityModel at index [0] is available in the LoggerModule context.

I am starting to learn nestjs, but after installing all the packages from the npm install, npm run start gives me an error saying :
_[Nest] 6445 - 24/05/2022, 12:50:27 ERROR [ExceptionHandler] Nest can't resolve dependencies of the LoggerService (?). Please make sure that the argument LoggerEntityModel at index [0] is available in the LoggerModule context.

Potential solutions:

  • If LoggerEntityModel is a provider, is it part of the current LoggerModule?
  • If LoggerEntityModel is exported from a separate @module, is that module imported within LoggerModule?
    @module({
    imports: [ /* the Module containing LoggerEntityModel */ ]
    })

Error: Nest can't resolve dependencies of the LoggerService (?). Please make sure that the argument LoggerEntityModel at index [0] is available in the LoggerModule context.

Potential solutions:

  • If LoggerEntityModel is a provider, is it part of the current LoggerModule?
  • If LoggerEntityModel is exported from a separate @module, is that module imported within LoggerModule?_

Screenshot 2022-05-24 at 12 54 01

I have no idea what goes wrong with loggerService and how to solve the issue

Pagination decorators aren't working as expected

I am using this boilerplate as starting point of my project. i have used generic pagination decorators (code borrowed from this repo) but they aren't working as expected. When i call the endpoint with query params. Query params are available till Interceptor. but after validating it against Listing Dto in router handler params. all values of Dto are undefined.

How to implement operation record

I know how to use a DTO to implement the update field diff.
I know that the controller uses decorator tag operations to record actions.
I know that interceptors are used global to commit operation records to the database.

How do you determine the request context and the operational user?

I designed the request context service class to bind a request ID,

use { scope: Scope.REQUEST }

get request: Request user

Is there a better implementation?

update-user.dto.ts

class UpdateUserDto {
     @DiffField('username')
     name: string;
}

user.controller.ts

class UserController {
    @Put(':id')
    @UpdateRecordLog(
      'update user ${entity.name}',
      'user ${entity.name} update field ${patch.name} form ${patch.origin} to ${patch.current}'
    )
    update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateUserDto) {
      return this.UserService.update(id, dto);
    }
}

user.service.ts

class UserService {
     constructor(
      private userRepository: UserRepository,
      private requestContext: RequestContext
    ) {}
    update(id: number, dto: UpdateUserDto) {
      const result =  this.userRepository.update(id, dto);
      this.recordContext.put(result);
      return result;
    }
}

request-context.ts

const map: Map<string, Record<string, unknown>> = new Map();

@Injectable({ scope: Scope.REQUEST })
export class RequestContext {
  static setRecordKeyForRequest(request: Request) {
    request[RecordContextMetadataKey] = uuid.v1();
  }

  static getRecordKeyForRequest(request: Request): string | undefined {
    return request[RecordContextMetadataKey];
  }

  static get(recordKey: string) {
    const value = map.get(recordKey);
    map.delete(recordKey);
    return value;
  }

  constructor(@Inject(REQUEST) private request: Request) {}

  put(data) {
      const recordKey = RequestContext.getRecordKeyForRequest(this.request);
      if (recordKey == null) {
       throw new Error('recordKey is not defined');
     }
     map.set(recordKey, data);
  }
}

record.interceptor.ts

@Injectable()
export class RecordInterceptor implements NestInterceptor<unknown> {
  constructor(
    @Inject(LoggerService) private readonly loggerService: LoggerService
  ) {}

  intercept(
    context: ExecutionContext,
    next: CallHandler<unknown>
  ): Observable<unknown> {
    const call$ = next.handle();

    const record_meta = Reflect.getMetadata(RECORD_META, context.getHandler());

    // Logs do not need to be reported
    if (record_meta == null) {
      return call$;
    }
    
    const { request } = ExpressContext(context);
    // bind  request ID to request context
    RequestContext.setRecordKeyForRequest(request);
    return call$.pipe(
      map((data: unknown) => {
        // record to database
        // request.user to operator
        return data;
      })
    );
  }
}

Problem with creating new Types.ObjectId from String _id

Getting Error while Starting the application

src/logger/logger.service.ts:39:38 - error TS2554: Expected 0 arguments, but got 1.

39             user: new Types.ObjectId(user),

not sure but seems like new Types.ObjectId() doesn't expect any argument . and I am wondering if there is any way around of creating ObjectId from String

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.