Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda