sequelize-typescript icon indicating copy to clipboard operation
sequelize-typescript copied to clipboard

how to hide password when get the model

Open susatyo441 opened this issue 1 year ago • 3 comments

Issue

How can I hide the password? is there any way to not select the password using typescript-sequelize?

Versions

  • sequelize: ^6.37.1
  • sequelize-typescript: 2.1.6
  • typescript: ^5.1.3

Issue type

  • [ ] bug report
  • [ x] feature request

Actual behavior

Expected behavior

Steps to reproduce

Related code

// src/models/user.model.ts

import { Table, Column, Model } from 'sequelize-typescript';
import { Exclude } from 'class-transformer';
import { IsNotEmpty } from 'class-validator';
import { IsEmail } from 'class-validator';

@Table
export class User extends Model {
  @Column
  @IsNotEmpty()
  name: string;

  @Column
  @IsEmail()
  email: string;

  @Column
  @Exclude({ toPlainOnly: true })
  password: string;

  @Column({
    type: 'ENUM',
    values: ['l', 'p'],
  })
  gender: string;
}

susatyo441 avatar Mar 08 '24 03:03 susatyo441

I override toJSON

  toJSON() {
    const json = super.toJSON();
    // Make sure that the password is not included in the response
    delete json.password;
    return json;
  }

knguyen0125 avatar Mar 27 '24 05:03 knguyen0125

You can also use scopes for this

@Table
@DefaultScope(() => {
  exclude: ['password']
})
export class User extends Model {...}

And then, for cases where you need it, you can create a different @Scope() you can find more here https://github.com/sequelize/sequelize-typescript?tab=readme-ov-file#scopes

NenadJovicic avatar Apr 03 '24 22:04 NenadJovicic

  @Column({
      get: () => undefined,
  })
  password: string;

exos avatar Jun 14 '24 10:06 exos