I have a #Get() method in a Controller. I get the response, but after the response is successfully I would like to call an async method after a delay of some milliseconds.
I'm using a Middleware, but seems like the response is pending for the time specified in the async method.
How can I do to solve the response in time, and after the delay call the custom method from the Custom Service?
Here is the used sample code:
#Controller()
export class CustomController {
#Get("custom-controller-route")
getCustomValue(#Res() response: Response) {
return response.status(200).send({
value: 1
})
}
}
The middleware code is the following:
#Injectable()
export class CustomMiddleware implements NestMiddleware {
constructor(private readonly customService: CustomService) {}
use(req: any, res: any, next: () => void) {
let send = res.send
res.send = async (customResponse: CustomResponse) => {
const { value } = customResponse
await customService.customMethod(value, 5000) // Delay of 5 seconds
res.send = send
return res.send(exchangeRateResponse)
}
next()
}
}
And the CustomService has the next code:
#Injectable()
export class CustomService {
async customMethod(value: any, delay) {
await firstValueFrom(
timer(delay).pipe(
tap(() => {
// Here is the logic that needs to be run in the delay time after the response is finished
console.log(`Custom Service - custom method called with: ${value} after: ${delay} milliseconds.`)
})
)
)
}
}
I could do it instead of returning the response in the Controller method, I only call the res.status(200).send({}) with the specific response and after that I call the specific method call with the delay.
#Controller()
export class CustomController {
#Get("custom-controller-route")
getCustomValue(#Res() response: Response) {
response.status(200).send({ value: 1 })
// Call the delayed Service method
}
}
Any other better option is welcome
Related
I have orders resolver, like this one(thats an example, not actually problem):
#Resolver(() => OrderEntity)
export class OrderResolver {
constructor(
private readonly orderService: OrderService,
private readonly usersService: UsersService,
) {}
.................
#ResolveField('users', () => [UsersEntity])
async users(#Parent() order: OrderEntity): Promise<UserEntity[]> {
return await this.usersService.findAllByOrderId(order.id);
}
#ResolveField('usersCount', () => Int)
async usersCount(#Parent() order: OrderEntity): Promise<number> {
const users = await this.usersService.findAllByOrderId(order.id);
return users.lenght; // i can't use like this: order.users.lenght, couse it's still undefined
}
}
And there are i call userService.findAllByOrderId method two times, because i can't use order.users from context in this method, as its still undefined
So how can i write one #ResolveField method for both fields: order.users and order.usersCount, or how to call usersCount method when order.users are already existing?
Thank's a lot for any answers!
I call one method 2 times, instead 1, how can i optimize it?
Do you really need to do a query to get the number of the noOfUsers ?. Cant you just call the async users function that returns UserEntity[] and then get the length of the array that is returned .length
or
If you really need to return the noOfUsers as an int then you can create a wrapper object and put the 2 fields in that e.g.
export class UserResponse {
users: Array<UserEntity>;
noOfUsers: int
}
Then you can only have 1 method that returns both fields:
#ResolveField('users', () => [UserResponse])
async users(#Parent() order: OrderEntity): Promise<UserResponse> {
const userEntities: Array<UserEntity> = await this.usersService.findAllByOrderId(order.id);
const response: UserResponse = {
users: userEntities,
noOfUsers: userEntities.length
}
return response;
}
The Nestjs module system is great, but I'm struggling to figure out how to take full advantage of it in a Serverless setting.
I like the approach of writing my domain logic in *.service.ts files, while using *.controller.ts files to take care of non-business related tasks such as validating an HTTP request body and converting to a DTO before invoking methods in a service.
I found the section on Serverless in the nestjs docs and determined that for my specific use-case, I need to use the "standalone application feature".
I created a sample nestjs app here to illustrate my problem.
The sample app has a simple add() function to add two numbers. I use class-validator for validation on the AddDto class.
// add.dto.ts
import { IsNumber } from 'class-validator'
export class AddDto {
#IsNumber()
public a: number;
#IsNumber()
public b: number;
}
And then, via some Nestjs magic, I am able to get built-in validation using the AddDto inside my controller by doing the following:
// main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Use `ValidationPipe()` for auto-validation in controllers
app.useGlobalPipes(
new ValidationPipe({ transform: true })
)
await app.listen(3000);
}
// app.controller.ts
#Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
#Post('add')
add(#Body() dto: AddDto): number {
// Request body gets auto validated and converted
// to an instance of `AddDto`, sweet!
return this.appService.add(dto.a, dto.b);
}
}
// app.service.ts
#Injectable()
export class AppService {
add(a: number, b: number): number {
return a + b
}
}
So far, so good. The problem now arises when using this in AWS with a Lambda function, namely:
I want to re-use the business logic in app.service.ts
I want to re-use built in validation that happens when making an HTTP request to the app, such as in the example above.
I want to use the standalone app feature so I don't have to spin up an entire nest server in Lambda
The docs hint on this being a problem:
Be aware that NestFactory.createApplicationContext does not wrap controller methods with enhancers (guard, interceptors, etc.). For this, you must use the NestFactory.create method.
For example, I have a lambda that receives messages from AWS EventBridge. Here's a snippet from the sample app:
// standalone-app.ts
interface IAddCommand {
a: number;
b: number;
}
export const handler = async (
event: EventBridgeEvent<'AddCommand', IAddCommand>,
context: any
) => {
const appContext = await NestFactory.createApplicationContext(AppModule);
const appService = appContext.get(AppService);
const { a, b } = event.detail;
const sum = appService.add(a, b)
// do work on `sum`, like cache the result, etc...
return sum
};
// lambda-handler.js
const { handler } = require('./dist/standalone-app')
handler({
detail: {
a: "1", // is a string, should be a number
b: "2" // is a string, should be a number
}
})
.then(console.log) // <--- prints out "12" ("1" + "2") instead of "3" (1 + 2)
I don't get "free" validation of the event's payload in event.detail like I do with #Body() dto: AddDto when making a HTTP POST request to /add. Preferentially, the code would throw a validation error in the above example. Instead, I get an answer of "12" -- a false positive.
Hopefully, this illustrates the crux of my problem. I still want to validate the payload of the event before calling appService.add(a, b), but I don't want to write custom validation logic that already exists on the controller in app.controller.ts.
Ideas? Anyone else run into this before?
It occurred to me while writing this behemoth of a question that I can simply use class-validator and class-transformer in my Lambda handler.
import { validateOrReject } from 'class-validator'
import { plainToClass } from 'class-transformer'
import { AddDto } from 'src/dto/add.dto'
export const handler = async (event: any, context: any) => {
const appContext = await NestFactory.createApplicationContext(AppModule);
const appService = appContext.get(AppService);
const data = getPayloadFromEvent(event)
// Convert raw data to a DTO
const dto: AddDto = plainToClass(AddDto, data)
// Validate it!
await validateOrReject(dto)
const sum = appService.add(dto.a, dto.b)
// do work on `sum`...
}
It's not as "free" as using app.useGlobalPipes(new ValidationPipe()), but only involves a few extra lines of code.
It worked for me with the following lambda file for nestjs.
import { configure as serverlessExpress } from '#vendia/serverless-express';
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '#nestjs/common';
let cachedServer;
export const handler = async (event, context) => {
if (!cachedServer) {
const nestApp = await NestFactory.create(AppModule);
await nestApp.useGlobalPipes(new ValidationPipe());
await nestApp.init();
cachedServer = serverlessExpress({
app: nestApp.getHttpAdapter().getInstance(),
});
}
return cachedServer(event, context);
};
I don't understand what is the use case to use Promise<APIGatewayProxyResultV2> type when processing an SNS event.
export async function main (event: SNSEvent) {
event.Records.forEach((record) => {
console.log('This is the record', record);
});
return {
statusCode: 200
}
}
export async function main (event: SNSEvent): Promise<APIGatewayProxyResultV2> {
event.Records.forEach((record) => {
console.log('This is the record', record);
});
return {
statusCode: 200
}
}
What is the benefit of using Promise<APIGatewayProxyResultV2> ?
Does it mean that I could define the event structure and not have it accepted, basically an if-else statement, but transformed in Web Logic? Can you point to an example if this is the case?
First question - do you have an API Gateway in use with your SNS?
The code you mentioned:
export async function main (event: SNSEvent): Promise<APIGatewayProxyResultV2>
just promises an APIGatewayProxyResult when returning. So it expects at least a statusCode and a body:
return {
statusCode:202,
body:"JSON"
};
I think, what you mean is: export async function main (event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2>
I assume that you're using an API Gateway that triggers a SNS Topic that triggers a lambda. With APIGatewayProxyEventV2 you just get the whole payload from the ApiGateway. You can create an interface that extends this APIGatewayProxyResultV2 to define or rather extend the event's structure. In my case, I added my own queryStringParameters.
interface ExampleApiProxyEvent extends APIGatewayProxyEventV2 {
queryStringParameters: {
par1: string;
par2: string;
par3: string;
};
}
I want to implement the global pre-loader concept in angular using httpInterceptors, its not working suppose if two http service call simultaneously called, 'finalize' will trigger only after one or more http api calls end, but its not happened, the preloader is also not shown correctly, it hide after first api call finished. Please suggest what i missed and tell me how to handle it. Is this the right place to handle the global error and preloader concept?
app.component.html
<preloader [loading]="appService.loading"></preloader>
app.component.ts:
const url1 = "https://jsonplaceholder.typicode.com/albums/1";
const url2 = "https://jsonplaceholder.typicode.com/albums/2";
forkJoin(
this.http.get(url1),
this.http.get(url2),
).subscribe(console.log);
HttpserviceInterceptor:
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { finalize, tap } from 'rxjs/operators';
import { AppCommonService } from './app.common.service';
#Injectable()
export class HttpserviceInterceptor implements HttpInterceptor {
constructor(
private appService: AppCommonService,
private notification: NotificationsWrapperService,
) {}
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.appService.showPreLoader()
return next.handle(request).pipe(
//tslint:disable-next-line: no-empty
tap(() => {
}, (error: any) => {
this.notification.error(error);
}),
finalize(() => this.appService.hidePreLoader()),
);
}
}
AppCommonService:
public showPreloader(): void {
//this.showPreloader$.next(true);
this.loading = true;
}
public hidePreLoader(): void {
//this.showPreloader$.next(false);
this.loading = false;
}
Lets suppose that you perform two requests. The first one takes one second to complete and the second one takes 5 seconds. Based on the code you provided the flow of the loader will be the following.
First request is performed and this.loading is set to true
Second request is performed and this.loading is set to true again
First requests finishes, and this.loading is set to false (wrong)
Second requests finishes, and this.loading is set to false
To make the loader appear as long as a request is active, you should try to keep the number of the requests that are currently performed by the web browser. Lets assume that you initialize a private integer named currentNumberOfRequests, and set it's value to 0.
So when a requests is performed, you should always set the {this.loading} flag to true and increase the this.currentNumberOfRequests by 1, and when a requests succeeds or fails (ideally in the finally clause), you should decrease the this.currentNumberOfRequests by 1. Now, if the this.currentNumberOfRequests is 0 you should hide the loader.
I often find myself using the following code:
export class Component implements OnDestroy {
private subscription: Subscription;
user: string;
constructor(private store: UserStore) {
this.subscription = store.select(fromUsers.getUser)
.subscribe(user => this.user = user);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
logout(): void {
this.store.dispatch({
type: LOGOUT,
payload: {
user: this.user
}
})
}
}
As you can see I need to store the user string as a member within the component to send it with my payload.
I would rather use the user string as an observable and make use of the async pipe.
How do I need to change my code to leverage the observable of the user when dispatching the action without storing it in a member variable?
You can use ngrx effects and enhance the LOGOUT command with current user.
#Effect() logoutEffect$ = this.actions$
.ofType(LOGOUT)
.withLatestFrom(this.store$)
.map(([action: Action, storeState: AppState]) => {
return storeState.getUser;
})
.map(payload => ({type: 'LOGOUT_USER', payload}))