Coder Social home page Coder Social logo

Comments (6)

jiayisheji avatar jiayisheji commented on May 28, 2024 2

I know,Interceptor is the best choice.
It was a pleasure talking to you. Thank you very much.
I'll show you when I write the code.

from ack-nestjs-boilerplate.

andrechristikan avatar andrechristikan commented on May 28, 2024 1

Based on my experience, if the provider scope is set to request and the request scope provider is injected to another provider. Then, other providers will be forced to request scope too.

So, if you inject the request scope provider into every provider (in the service layer), that will decrease your application performance.

ex:

  1. without request context
service1 (scope default) -> controller1 (scope default)
service1 (scope default) -> controller2 (scope default)
  1. with request context
requestContext (scope request) -> service1 (scope request) -> controller1 (scope request)
requestContext (scope request) -> service1 (scope request) -> controller2 (scope request)

Definition of request Scope from nestjs official doc

A new instance of the provider is created exclusively for each incoming request. The instance is garbage-collected after the request has completed processing.

Maybe you should try this approach

Cons RequestId will undefined in exception filter.

  1. UserService, remove the request context
class UserService {
     constructor(
      private userRepository: UserRepository,
    ) {}
    update(id: number, dto: UpdateUserDto) {
      const result =  this.userRepository.update(id, dto);
      return result;
    }
}
  1. UserController, i don't really know what happen with @UpdateRecordLog. I assume the @UpdateRecordLog is decorator group between RecordInterceptor and RECORD_META
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);
    }
}
  1. Record Interceptor, you do not need RequestContext
@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();

    // ! set request id here
    const requestId = uuid.v1();

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

    if (record_meta == null) {
      return call$;
    }
    
    return call$.pipe(
      tab(async (data: unknown) => {
        // !data is response from controller
        // !you can insert the record in this

        // for example, insert data into loggerservice
        await this.loggerService.put(requestId , data);
        return data;
      })
    );
  }
}

For the next, try to put the RequestId in middleware and then put the RequestId into RequestContext from express.

Ex:
to put look src/common/middleware/request-id.middleware.ts in this project
to get look src/common/logger/interceptors/logger.interceptor.ts in this project
also you can get in exception filter, look src/common/error/filters/error.http.filter.ts

Do not forget to read the https://docs.nestjs.com/faq/request-lifecycle. This doc will (maybe) help you

from ack-nestjs-boilerplate.

jiayisheji avatar jiayisheji commented on May 28, 2024

Thank you for your reply.

I want to make an operation log feature,record user actions, creation, modification, and deletion.

Each record needs to have an operator.

For the modification action, the modified field and the value before the modification and the value after the modification are required.

Developers can customize the format output record content.

from ack-nestjs-boilerplate.

andrechristikan avatar andrechristikan commented on May 28, 2024

Ohh, I see... 
I can only recommend that you try using the interceptor pre and interceptor post instead of injecting request context into every service provider.

Hope you got the new insight.

from ack-nestjs-boilerplate.

github-actions avatar github-actions commented on May 28, 2024

This issue is stale because it has been open for 30 days with no activity.

from ack-nestjs-boilerplate.

github-actions avatar github-actions commented on May 28, 2024

This issue was closed because it has been inactive for 14 days since being marked as stale.

from ack-nestjs-boilerplate.

Related Issues (20)

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.