Sobes.tech
Junior — Middle

How do you apply metadata in your work?

sobes.tech AI

Answer from AI

Metadata in Node.js is often used to store additional information about data or objects, which helps in processing or logging. For example, when working with HTTP requests, metadata can be used to store information about the user session, request time, or access rights.

In projects using TypeScript and decorators, metadata is used to describe class properties, which facilitates validation, serialization, or integration with frameworks (for example, NestJS uses metadata for dependency injection).

Example of using metadata with the Reflect API:

import 'reflect-metadata';

function Log(target: any, propertyKey: string) {
  Reflect.defineMetadata('log', true, target, propertyKey);
}

class Example {
  @Log
  method() {
    console.log('Method called');
  }
}

const example = new Example();
const hasLog = Reflect.getMetadata('log', example, 'method');
console.log(hasLog); // true

Thus, metadata helps add additional context to code without changing its logic.