Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
Sequelize scope on create

I am quite new to sequelize and trying to use it with sequelize-typescript.

I have a user model like this:

@Scopes(() => ({
    authenticated: {
        attributes: {
            exclude: ["password", "email" /* more .. */]
        }
    }
}))
export default class User extends Model<IUser, UserOnCreate> implements IUser {
    @PrimaryKey
    @AutoIncrement
    @Column(DataType.INTEGER)
    declare id: number

    @Unique
    @Column(DataType.STRING(20))
    declare username: string

    @Column(DataType.STRING(64))
    get password(): string { return this.getDataValue("password") }
    set password(p: string) { /* some hashing algorithms */ }

    // more columns...
}

Also have a type for authenticated user,

type AuthenticatedUser = Omit<IUser, | "password" | "email" /* more */>

And, I am creating a new user with the following code:

await new User(credentials, { raw: true }).save()

So is there a easier way to apply authenticated scope on create?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

After some searchings and browsing of the docs, couldn't find anything.

So, define an array for unwanted keys:

export const authenticableExclude = ["id", "updatedAt", "createdAt", "email"] 

And define a @AfterCreate hook and set these keys as undefined

@AfterCreate
static async editLikeScope(i: User) {
    Object.keys(i.get()).forEach((k) => { 
        if (authenticatedExclude.includes(k)) i.set(k as (keyof IUser), undefined)
    })
}

That's it.
PS: The main idea is, @AfterCreate hooks aren't update your model instance, as long as you are not call the .save() method. Herewith, attributes can be change and update without affecting the created model.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda