What is the best way to extract values from a TypeORM property decorator?

import { PrimaryColumn, Column } from 'typeorm';

export class LocationStatus {
  @PrimaryColumn({ name: 'location_id' })
  locationId: string;

  @Column({ name: 'area_code', type: 'int' })
  areaCode: number;
}

I've been struggling for hours trying to extract the values of the properties location_id and area_code using the property decorator @Column(), but so far, no success. I'm unsure if it's even feasible to retrieve a list of properties in this way.

Answer №1

After examining the source code of typeorm (found here, here, here, here), it appears that you can access various information using the global variable typeormMetadataArgsStorage (such as

window.typeormMetadataArgsStorage
or
global.typeormMetadataArgsStorage
). Dive into it, and you may discover what you're looking for with a script like this:

const global_context = ??? // depending on your environment
const property_to_look_for = `areaCode`
const name = global_context.typeormMetadataArgsStorage
  .columns
  .filter(col => col.propertyName === property_to_look_for && col.target === LocationStatus)
  .options
  .name
console.log(name)

UPDATED

For those utilizing Nest framework like myself, here's my current approach.


import { getMetadataArgsStorage, InsertResult } from 'typeorm';

export class PinLocationStatusRepository extends Repository<PinLocationStatus> {
  // List of column names in this array should not be altered.
  // For example, the value of "location_id" as "location_ko_01" remains unchanged.
  private static immutableColumnNames = ['location_id', ...]; 

  private static mutableColumnFound(name: string): boolean {
    return PinLocationStatusRepository.immutableColumnNames.every(colName => colName !== name);
  }

  savePinLocation(state: PinLocationStatus): Promise<InsertResult> {
    const columns = getMetadataArgsStorage()
     .columns.filter(({ target }) => target === PinLocationStatus)
     .map(({ options, propertyName }) => (!options.name ? propertyName : options.name))
     .reduce((columns, name) => {
       if (PinLocationStatusRepository.mutableColumnFound(name)) {
         columns.push(name);
       }
       return columns;
    }, []);

    return this.createQueryBuilder()
      .insert()
      .into(PinLocationStatus)
      .values(state)
      .orUpdate({ overwrite: columns }) // ['area_code']
      .execute();
  }
}
  1. Retrieve the column name from the @Column() decorator.
  2. Exclude certain column names where values must remain constant.
  3. Provide the columns to the overwrite property.

The output will be accurate unless "area_code" is a fixed column.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Employing lodash for object comparison and removal from an array

In my current project, I am using lodash to compare two arrays of objects and extract the differences between them. The goal is to add this difference to the original data set while maintaining the existing data intact. For instance, if there are initially ...

Utilizing ng-options within an ng-repeat to filter out previously chosen options

Facing a simple problem and seeking a solution. I am using ng-repeat to dynamically create select boxes with ng-options displaying the same values. The ng-repeat is used to iterate through model options. <div data-ng-repeat="condition in model.condit ...

Base64 versus UTF-8 charset: What sets them apart?

While working with binary files, I discovered that: If it's a text-based file, I need to use data:text/plain;charset=utf-8, and if it's a multimedia file, I should use data:image/png;base64, I attempted to use base64 encoding and encountered a ...

Instructions for creating a vibrant pathway using colorful tiles

Is there a way for me to create a path of colored tiles for a character to follow, where the character's path matches the color of the character cube itself? I currently have this code (found in another post): <html><head> <s ...

The relocation of the route from app.js to route.js has caused a malfunction in the app

After restructuring my code, I encountered an issue with a route that was working fine before. Initially, the code was in my app.js file and it worked as intended. However, after moving it to its own route at routes/random, I started receiving a "http://lo ...

Working with a function in the stylesheet of TypeScript in React Native allows for dynamic styling

When attempting to use variables in my StyleSheet file, I encounter a type error even though the UI works fine. Any suggestions on how to resolve this issue? type buttonStyle = (height: number, width: string, color: string) => ViewStyle; export type St ...

Encountering a surprising token error while running a node.js application with a classic example

I downloaded node.js from its official website and followed the instructions provided here. I attempted to run the example code snippet from the "JavaScript - The Good Parts" textbook: var myObject = { value: 0; increment: function (inc) { this.value ...

Can you provide instructions on how to use JavaScript to click and hold a button for a specific duration?

Is it possible to use jQuery to create a button that, when guest button number 1 is clicked, will automatically click and hold down button number 2 for about 3 seconds? I have tried using the mousedown() and click(), but they only register a click, not a ...

Manipulating objects with Jade Mixin

My current challenge involves programmatically displaying objects within a jade template by passing an array of objects to the view. The aim is to present these objects in a grid view with up to 3 items per row. However, I encountered an issue where nested ...

Re-activate external script following a language update in Next.js

In my Next.js 13 app, I have implemented a live chat support button that is dynamically added based on the language selection. The code for rendering the button looks like this: import Script from 'next/script'; ... <div id={`onlinehelp-button ...

Methods for comparing the current date and time to a specific time stored in a database

A database table contains the following values: "295fc51f6b02d01d54a808938df736ed" : { "author" : "James Iva", "authorID" : "JBvLC3tCYCgFeIpKjGtSwBJ2scu1", "geometry" : { "latitude" : 29.4241219, "longitude" : -98.49362819999999 ...

What are the best tools to develop a browser-based 2D top-down soccer simulation?

I'm looking to create a 2D top-down soccer simulation game for web browsers using modern technologies and without the need for additional plugins like Flash or Silverlight, making it compatible with mobile devices as well. The game will be AI-controll ...

Increase the identifier of my input text when a table row is duplicated through Javascript

I have a table with only one row that contains various elements like textboxes and buttons. I want to clone the table row using the append() function when a button is clicked. However, I am facing an issue - how can I increment the id of the textboxes and ...

Exploring the concepts of express post and delete responses that are unclear

It appears that I am facing an issue where trying to access an attribute of an element from a JSON file returns null. Additionally, I am still encountering npm audit problems. What are your thoughts on this situation? Below is the code snippet that has be ...

The comparison between dynamically adding elements through Javascript and hiding them using CSS

I am contemplating the advantages and disadvantages of adding elements to a page and setting display:none versus creating a function that dynamically generates the elements and appends them where needed. In my current situation, I am implementing a reply ...

What is the best way to display a number or integer using axios?

Need help retrieving the integer from the response obtained through an axios get request Here is what I see in the console log: https://i.stack.imgur.com/ztmf0.png setDappList([response.data.stats]); <div>{setDappList.total}</div> Unfortuna ...

The error occurred at line 12 in the app.js file, where it is unable to access properties of an undefined object, specifically the 'className' property. This occurred within an anonymous function in an HTMLDivElement

I am facing an issue with my website where I have buttons on the right side. I want to use JavaScript to change the style of the button when it is clicked. When the page loads, the home button should have a background-color: green. However, when another bu ...

Tips for adjusting the size of a three.js object without changing its position

I'm working on animating a sphere made up of dots, and I'm facing a challenge. I want each dot to remain on the surface of the sphere while it resizes. Currently, I am attempting to scale the mesh or geometry of a specific point on the surface, b ...

Which is Better for Mobile Web Apps: Multiple Pages or AJAX?

I am currently planning a new project focused on mobile web apps. The project will involve creating a mobile web app with multiple screens, a search system, and various other features. One decision I need to make is choosing the primary framework for this ...

Cover the entire screen with numerous DIV elements

Situation: I am currently tackling a web design project that involves filling the entire screen with 60px x 60px DIVs. These DIVs act as tiles on a virtual wall, each changing color randomly when hovered over. Issue: The challenge arises when the monitor ...