Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!