NestJS - How to add a dynamic routing to the controller? - node.js

I have the following problem. Let's say I have an array of routes & paths to static resources, e.g.
const routes = [{ url: '/', path: 'assets/www' }]
What I would like to do is to create a set of dynamic routes to serve static resources. In express application I would do smth like:
const router = express.Router();
routes.forEach(route => {
router.use(route.url, express.static(path.join(__dirname, route.path)))
})
But is it possible to create such a logic inside a NestJS controller?
#Controller()
export class ItemsController {
constructor() {}
#Get()
findAll() {}
#Get(':id')
findOne() {}
....
}
As far as I can see all HTTP request handlers should be predefined using the corresponding decorators.

I would opt for an approach where you create your controllers fully dynamic. This is not natively supported in Nest, but you can actually create dynamic controllers and dynamic services using a mixin approach (what is actually quite common), also see this answer at GitHub:
import { Post, Get, Controller } from '#nestjs/common';
interface Options {
basePath: string
entityName: string // you could even pass down DTO classes here, for maximum flexibility.
providerName: string
}
// this service is generated dynamically as well
// preferably use a custom providerName.
interface DynamicService {
foo: () => void
bar: () => void
}
export const createDynamicController = (controllerOptions: Options) => {
#Controller(controllerOptions.basePath)
class MyController {
constructor(
#Inject(options.providerName) myProvider: DynamicProvider
){}
#Get(options.entityName)
findOne(){
return this.myProvider.foo()
}
#Post(options.entityName)
create(){
return this.myProvider.foo()
}
}
return MyController
}
Using that approach you can create all controllers in theory dynamically, but it asks a bit more about understanding of the NestJS dependency tree.
You can now create the controller like:
{
controllers: [createDynamicController({
basePath: 'foo',
entityName: 'barz',
providerName: 'custom-provider-name'
})
]
}

What you could do is have a dynamic controller -> with say Parameters identifiers -> the as if it were like an event handler id... (not really just using that as an way to think of the process.)
Then in your the connected service -> you can have the 5 crud operations however in your service you inject the static resources -> and use that Identifier to route the call.
query dto
export class QueryDto {
readonly params?: any[];
readonly body: any;
}
controller
#Post(':serviceId')
async create(#Param('serviceId') serviceId: string, #Body() queryDto: QueryDto) {
return await this.rootService.create(serviceId, queryDto);
}
inside your root service
// childService = used to route the request dynamically ->
// body = your body or if you dont need a body this is where any parameters would go. which is why it's any (for if it was a get)
// params last => incase your doing a put or something where you need a body and parameters -> but it also allows it to be optional.
async create(childService: string, data: any, params: any[]): Promise<any> {
if (!id) {
return await this[childService].create(data.body, ...data.params).exec()
}
just an idea, but if everything static then this should do it for you. just use the root service as a passthrough. from the single controller -> to the various services.

Related

MIssing TERMINUS_ERROR_LOGGER argument/dependency - NestJS HealthCheck controller

I'm trying to implement a simple HealtCheck controller in my NestJS api by following the offical example Healthchecks (Terminus): https://docs.nestjs.com/recipes/terminus#setting-up-a-healthcheck but I'm getting this error:
Nest can't resolve dependencies of the HealthCheckService (HealthCheckExecutor, ?). Please make sure that the argument TERMINUS_ERROR_LOGGER at index [1] is available in the HealthCheckModule context.
Since TERMINUS_ERROR_LOGGER seems like some kind of a enum, I'm not able to import it or add it as a provider inside my HealthModule and I haven't found any documentation/blog/post related to this.
Here's my HealthCHeck controller code:
import { Controller, Get } from '#nestjs/common';
import { HealthCheckService, HttpHealthIndicator, HealthCheck, TypeOrmHealthIndicator } from '#nestjs/terminus';
#Controller('health-check')
export class HealthCheckController {
constructor(
private readonly health: HealthCheckService,
private db: TypeOrmHealthIndicator,
) { }
#Get()
#HealthCheck()
readiness() {
return this.health.check([
async () => this.db.pingCheck('postgres', { timeout: 300 }),
]);
}
}
I just want to create a HealtCheck controller to check if the api is connected to my db and implement future health checks.

How to use correctly NextJs API

i've just started using Next js with mongodb and i have a question about how should i organize the API route files.
I have a simple application that add, update and delete documents of a mongodb collection. For each operation i created a .ts file inside the api folder. Like this
And for example my new_task.ts file looks like this
export default async function AddTask (req:NextApiRequest, res:NextApiResponse) {
const task:Task = req.body
const client = await clientPromise;
const db = client.db("diary");
const myCollection: Collection = db.collection('tasks');
try {
await myCollection.insertOne(task)
res.send('Success')
} catch (error) {
res.status(400).json({error})
console.log(error)
}
}
Everything is working ok but i think it's kinda messy the file organization. Is there a way to put every operation inside just one file? Or to do so i would have to build a custom server with express?
Thanks
In one route function, you can check the request object req to see if the HTTP request method is GET POST PUT PATCH or DELETE. Depending on which method, you can call a different function.
Here is an example from the NextJS docs.
import type { NextApiRequest, NextApiResponse } from 'next'
export default function userHandler(req: NextApiRequest, res: NextApiResponse) {
const {
query: { id, name },
method,
} = req
switch (method) {
case 'GET':
// Get data from your database
res.status(200).json({ id, name: `User ${id}` })
break
case 'PUT':
// Update or create data in your database
res.status(200).json({ id, name: name || `User ${id}` })
break
default:
res.setHeader('Allow', ['GET', 'PUT'])
res.status(405).end(`Method ${method} Not Allowed`)
}
}
Another thing you can do to make your code more re-useable and easier to maintain is to write reusable function definitions in a lib folder and then import them into your api route files when you want to use them.
Have you tried creating a file in the lib folder and writing function definitions there for MongoDB and then importing those function definitions into your api route file?
Then call the appropriate function depending upon the request method.
In ./lib/mongodb, write a function definition and import any Mongo-related imports you need.
export async function updateUserInfo(parameters) {
// . . . your code needs to return something, probably an array or object from MongoDB
}
In your api route file, import that function definition.
import { updateUserInfo } from "../../lib/mongodb"
Inside your route function, call updateUserInfo and pass whatever arguments you need based on the parameters you put in the definition. Handle its return value using await.
import type { NextApiRequest, NextApiResponse } from 'next'
import { updateUserInfo } from "../../lib/mongodb"
export default function userHandler(req: NextApiRequest, res: NextApiResponse) {
const {
query: { id, name },
method,
} = req
switch (method) {
case 'GET':
// Get data from your database
res.status(200).json({ id, name: `User ${id}` })
break
case 'PUT':
// Update or create data in your database
const updateResult = await updateUserInfo( . . .)
// FIX THE OBJECT IN .JSON BELOW TO SUIT YOUR CODE
res.status(200).json({ id, name: name || `User ${id}` })
break
default:
res.setHeader('Allow', ['GET', 'PUT'])
res.status(405).end(`Method ${method} Not Allowed`)
}
}
You can reuse updateUserInfo anywhere you have arguments for the required parameters.
Also, consider when you are calling the API route. At build time or after. At build, you call from static functions and after you call from client-side.
So by using the lib file for function definitions, you can reuse them in server functions and static functions.
The structure of the files inside the api folder is your api architecture. So it's organization depends upon your application's needs. You can use static and dynamic routes, as you maybe already know.
Consider API best practices when designing your architecture.

Is there a way to get request context within a decorator in Nest JS

I am trying to build a decorator to "log" request info
export const Tracking = () => {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const method = descriptor.value;
descriptor.value = async function(...args: any[]) {
console.log(/** Request info */)
console.log(/** Headers, Body, Method, URL...*/)
return method.call(this, ...args);
}
}
}
and try to use it on a controller method like this.
export class Controller {
#Get('/path')
#Tracking()
public async getData(#Headers('user') user: User) {
return this.service.getData(user.id);
}
}
If this is impossible, is there a way to apply interceptor to some method of controller?
Or is there a thread(like)-level context for request?
Thanks!!
Decorators don't have access to the request information because of what a decorator is. It's a higher order function that is called to set metadata for the class, class member, class method, or class method parameter. This metadata can be read at runtime, but it is called and set essentially as soon the file is imported. Due to this, there's no way to call a decorator on each request, even Nest's #Body() and #Req() are called at the time of import and read at the time of the request (actually earlier but that's besides the point).
What you're looking for here sounds more like an interceptor, like Micael Levi and hoangdv have already mentioned. The Nest docs show a basic logging example, and there are packages out there like #ogma/nestjs-module (disclaimer: I'm the author) that handle this request logging/tracking for you including the addition of correlation IDs.

Is it ok to use controller and graphql resolver together in nestJs?

For my next project I would like to use Graphql inside the FrontEnd. Furthermore this project should also offer a Rest-Api.
Now I have discovered this extremely great framework "nestjs", where it is theoretically possible to combine a Graphql endpoint and a rest endpoint.
Unfortunately I can't find anything in the documentation if this can lead to problems. Is the following code usable without problems?
Artikel controller:
#Controller('article')
#Resolver('Article')
export class ArticleController {
constructor(private articleService: ArticleService){}
#Get()
#Query(returns => CArticle)
async Article() {
const dbElement=await this.articleService.getById("xy");
return dbElement;
}
}
Article module:
#Module({
controllers:[ArticleController],
providers:[ArticleService,ArticleController]
})
export class ArticleModule {}
As this would work in this specific example, it may not work well in other use cases you may reach.
In my experience with using both Rest and gRPC - there are eventually different things that the controllers need to take care of.
I would highly recommend having dedicated controllers/resolvers for each API - with these taking care of API entry (i.e. authenticating, taking care of context) and having the Business Logic in a separate Provider.
So your example would look like so:
Article.controller.ts:
#Controller('article')
export class ArticleController {
constructor(private articleService: ArticleService){}
#Get()
async Article() {
return this.articleService.getById("xy");
}
}
Article.resolver.ts:
#Resolver('Article')
export class ArticleResolver {
constructor(private articleService: ArticleService){}
#Query(returns => CArticle)
async Article() {
return this.articleService.getById("xy");
}
}
Article.module.ts:
#Module({
controllers:[ArticleController, ArticleResolver],
providers:[ArticleService]
})
export class ArticleModule {}
As I understand nestjs now, there should be no problems, as the decorators do not change the code but only create new code.

How can I cast input JSON object to model class in Node.JS with TypeScript?

I am writing my Node.js server using TypeScript and express framework.
This is how my controller and route looks like:
export class AuthController {
public async signUpNewUser(request: Request, response: Response) {
...
}
}
How can I receive a model class instead Request type like in ASP.NET ?
Something like:
public async signUpNewUser(input: SignUpModel, response: Response) {
Is this a good idea at all? I am not sure this is a common approach in the Node.JS
I just want to make sure I get the same model each time and write a code related to this model and not on dynamic JSON object.
My suggestion is to convert to strong type model at the beginning of the route, but I am not sure this is a good way.
Does somebody have a solution for such cases?
How can I receive a model class instead Request type like in ASP.NET
This was a perpetual pain to me in my projects (and at work), eventually we decided to build a custom router with its own default error handling and auth-header checks. The trick with this pattern is to keep it lightweight, because this is still express and middleware is where things should go - this wrapper just provides a way for us to cast the express request into a properly shaped type based on the middleware we actually use.
This is pared down example, the idea is that you can specify the shape of the req & res by passing an interface (or an inlined type shape) and have typescript enforce the return shape.
Wrapper class example:
import * as express from 'express';
export type ExpressMethods = "get" | "post" | "put" | "delete" | "patch";
export type JsonRouteInput<RequestBody, RouteParams, QueryParams> = {
body: RequestBody;
params: RouteParams;
query: QueryParams;
};
export type JsonRouteHandler<
RequestBody,
RouteParams,
QueryParams,
ResponseBody
> = (
request: JsonRouteInput<RequestBody, RouteParams, QueryParams>
) => Promise<ResponseBody> | ResponseBody;
export class JsonRouter {
router = express.Router();
private addHandler<M extends ExpressMethods>(
method: M,
...middleware: express.RequestHandler[]
) {
this.router.use(...middleware);
}
get route(): {
[K in ExpressMethods]: <
RequestBody,
ResponseBody,
RouteParams = never,
QueryParams = never
>(
path: string,
handler: JsonRouteHandler<
RequestBody,
RouteParams,
QueryParams,
ResponseBody
>
) => JsonRouter
} {
const addables = {} as any;
(["get", "post", "put", "delete", "patch"] as ExpressMethods[]).forEach(
<RequestBody, ResponseBody, RouteParams = never, QueryParams = never>(
method
) => {
addables[method] = (
path: string,
handler: JsonRouteHandler<
RequestBody,
RouteParams,
QueryParams,
ResponseBody
>
) => {
this.router[method](path, async (req, res) => {
try {
const responseBody: ResponseBody = await handler({
body: req.body,
params: req.params,
query: req.query
});
res.json(responseBody);
} catch (err) {
// do your standard error handling or whatever
res.status(500).end("ow");
}
});
return this;
};
}
);
return addables;
}
}
And then using it
const jsonRouter = new JsonRouter().route.get<{ request: number }, { response: number }>(
"/hello-world",
req => {
return { response: req.body.request + 1 }; // type-checked result
}
);
This can definitely be taken one step further - I have some prototypes that allow us to semi-fluently build the shape of the request/response body. The goal with this strategy long term lets us generate a typescript rest client for the frontend, generate input-validation that matches the type we're using to annotate, and also enforce that the response is the right type - example router using this strategy to build the type dynamically
EDIT: To plug this example into an express server
const app = express();
// custom middleware goes here
app.use('/', jsonRouter.router);
app.listen(8000)
So you seem to have a couple different questions in there. The core question is "how do I cast a JSON object to a specific type", but then you also ask if it's a good idea or not and if it's a common practice.
The answer to your first question is pretty simple, you can cast it in your route (or wherever) like so:
router.get('/whatever', (req, res) => {
const signup: SignupModel = JSON.parse(req.model) as SignupModel;
// Do whatever you want with the signup model
});
Now, your other questions are way more opinion-based. If I'm being honest, I would say "don't use Typescript". :) Joking aside, I don't know how to answer your opinion-based question (nor is it a good fit for this site)

Resources