Issue
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?
Solution
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.
Answered By - alp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.