conditional columns

is there a better way of doing this? if the userType column equals to 'artist', the nickname column should be notNull(), but in case of 'customer' it should be null also, the firstName, lastName and the city columns should be filled out before isSetupComplete column can be set to true below is what i came up with open to tips and suggestions, thanks in advance!
export const users = pgTable('users', {
id: uuid().notNull().primaryKey().defaultRandom(),
email: text().notNull().unique(),
password: text().notNull(),
code: text().notNull(),
isVerified: boolean().notNull().default(false),
type: pgEnum('user_type', ['customer', 'artist'])(),
firstName: text(),
lastName: text(),
city: text(),
nickname: text(),
isSetupComplete: boolean().generatedAlwaysAs(
(): SQL => sql`CASE
WHEN ${users.isVerified} = true
AND ${users.firstName} IS NOT NULL
AND ${users.lastName} IS NOT NULL
AND ${users.city} IS NOT NULL
AND ${users.type} IS NOT NULL
AND (
${users.type} = 'customer'
OR (${users.type} = 'artist' AND ${users.nickname} IS NOT NULL)
)
THEN true
ELSE false
END`,
),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
});
export const users = pgTable('users', {
id: uuid().notNull().primaryKey().defaultRandom(),
email: text().notNull().unique(),
password: text().notNull(),
code: text().notNull(),
isVerified: boolean().notNull().default(false),
type: pgEnum('user_type', ['customer', 'artist'])(),
firstName: text(),
lastName: text(),
city: text(),
nickname: text(),
isSetupComplete: boolean().generatedAlwaysAs(
(): SQL => sql`CASE
WHEN ${users.isVerified} = true
AND ${users.firstName} IS NOT NULL
AND ${users.lastName} IS NOT NULL
AND ${users.city} IS NOT NULL
AND ${users.type} IS NOT NULL
AND (
${users.type} = 'customer'
OR (${users.type} = 'artist' AND ${users.nickname} IS NOT NULL)
)
THEN true
ELSE false
END`,
),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
});
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?