Tips for including a sequelize getter in a model instance?

I'm currently struggling to add a getter to the name field of the Company model object in my project. Despite trying various approaches, I haven't had any success so far. Unfortunately, I also couldn't find a suitable example to guide me through this issue. The Sequelize version I am using is 5.21. My main confusion lies in whether the getter should be inside a decorator or another part of the code. To keep things clear and concise, here's a trimmed snippet of the relevant code. Any assistance on this matter would be highly appreciated.

    export default class Company extends Model<Company> {
      @PrimaryKey
      @Default(DataType.UUIDV4)
      @Column(DataType.UUID)
      id: string;
    
      @Default(DataType.NOW)
      @Column
      created_at: Date;
    
      @Default(0)
      @Column
      deleted_at: Date;
    
      @AllowNull(false)
      @Column(DataType.STRING(25))
      name: string;
    
      @Default(true)
      @Column
      active: boolean;
    
      
    }

Answer №1

If you want to manipulate a column using the VIRTUAL type, you can achieve that by implementing a getter and setter in your model:

@Table({ modelName: 'application' })
export class Application extends Model<Application> {

  @Column(DataType.VIRTUAL(DataType.STRING))
  get clientSecret(): string {
    return this.getDataValue('clientSecret')
  }

  set clientSecret(value: string) {
    this.setDataValue('clientSecret', value)
  }
}

For more information, refer to this comment in an issue

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

Exploring how enums can be utilized to store categories in Angular applications

My application has enums for category names on both the back- and front-end: export enum CategoryEnum { All = 'All', Category1 = 'Category1', Category2 = 'Category2', Category3 = 'Category3', Cate ...

What will be the output of this typescript function?

Whenever I hover over the keyword 'function', this cryptic description pops up: "(local function)(this: any, next: (err?: mongoose.CallbackError | undefined) => void): Promise<void>" I'm confused about whether it return ...

Transform the process.env into <any> type using TypeScript

Need help with handling logging statements: log.info('docker.r2g run routine is waiting for exit signal from the user. The container id is:', chalk.bold(process.env.r2g_container_id)); log.info('to inspect the container, use:', chalk.b ...

Sending information from service.ts to component

I'm encountering a roadblock with this issue, hopefully I can find some assistance here. Essentially, I am attempting to make a simple get http request in http.service and then pass the json object to the filter.service. From there, I aim to transfer ...

Angular HTTP requests are failing to function properly, although they are successful when made through Postman

I am attempting to send an HTTP GET request using the specified URL: private materialsAPI='https://localhost:5001/api/material'; setPrice(id: any, price: any): Observable<any> { const url = `${this.materialsURL}/${id}/price/${price}`; ...

An issue has occurred while utilizing Angular

I'm diving into the world of Angular and encountering some errors as I try to execute this code. An unexpected token is causing trouble. A constructor, method, accessor, or property was expected. The left side of a comma operator seems to be unused ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

Removing a portion of an item with the power of RxJS

I possess the subsequent entity: const myObject = { items:[ { name: 'John', age: 35, children: [ { child: 'Eric', age: 10, sex: 'M' }, { ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

Preventing an Angular component from continuing to execute after clicking away from it

At the moment, I have a sidebar with clickable individual components that trigger API calls to fetch data. However, I've noticed that even when I click off a component to another one, the old component continues to refresh the API data unnecessarily. ...

What could be the reason for React not memoizing this callback?

I am encountering an issue with my Next.js project where the _app.tsx file contains the following code: const Root = ({ Component, pageProps }) => { ... const handleHistoryChange = useCallback((url) => { console.log({ url }); }, []); u ...

I'm looking for a solution to reorganize my current state in order to display the image URL

My React component, which also utilizes TypeScript, is responsible for returning a photo to its parent component: import React, { useEffect, useState } from "react"; import axios from "axios"; export const Photo = () => { const [i ...

ng2-table ways to customize the appearance of a particular row

Hey there, I'm currently new to Angular 2 and working with ng2-table. I've successfully added a table like the one shown here to my website. Now, I'm trying to figure out how to add color to specific rows within the table. Following the ste ...

A conditional type used with an array to return either an Error object or a generic type when the array is destructured

Within my Typescript project, I've implemented a Result type to be returned from functions, containing either an error or some data. This can take the form of [Error, null], or [null, Data]. Here's an example: type Result<Data> = [ Error | ...

Navigating through a mergeMap observable with an undefined value

In my Angular 6 app, I have a class that attaches API tokens to every http request using the getIdToken() method. If the token retrieval is successful, everything works fine. However, if it fails, my app will stop functioning. I need help with handling th ...

"Efficiently Distributing HTTP Requests Among Simultaneous Observers using RxJS

Currently, I am working on a feature in my Angular application that requires handling multiple concurrent fetches for the same data with only one HTTP request being made. This request should be shared among all the subscribers who are requesting the data s ...

The initial rendering of components is not displayed by Vue Storybook

The functionality of the storybook is effective, but initially, it fails to "render" the component. By examining the screenshot, we can deduce that the component-template is being utilized in some way, as otherwise, the basic layout of the component would ...

Searching within an Angular component's DOM using JQuery is restricted

Want to incorporate JQuery for DOM manipulation within Angular components, but only want it to target the specific markup within each component. Trying to implement Shadow DOM with this component: import { Component, OnInit, ViewEncapsulation } from &apo ...

How can I prevent unnecessary rerenders when choosing an array in React Redux?

Is there a method to extract a derived array from a Redux store without triggering unnecessary renders? Within my Redux store, I have an array of objects. state = {items: [{id: 1, keys...}, {id: 2, keys...}, {id: 3, keys...}, ...]} I have created a selec ...