20241103083933_user-roles.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const { ROLES } = require("../consts");
  2. const env = require("../env");
  3. /**
  4. * @param { import("knex").Knex } knex
  5. * @returns { Promise<void> }
  6. */
  7. async function up(knex) {
  8. const hasRole = await knex.schema.hasColumn("users", "role");
  9. if (!hasRole) {
  10. await knex.transaction(async function(trx) {
  11. await trx.schema.alterTable("users", table => {
  12. table
  13. .enu("role", [ROLES.USER, ROLES.ADMIN])
  14. .notNullable()
  15. .defaultTo(ROLES.USER);
  16. });
  17. const adminEmails = env.ADMIN_EMAILS.split(",").map((e) => e.trim());
  18. const adminRoleQuery = trx("users").update("role", ROLES.ADMIN);
  19. adminEmails.forEach((adminEmail, index) => {
  20. if (index === 0) {
  21. adminRoleQuery.where("email", adminEmail);
  22. } else {
  23. adminRoleQuery.orWhere("email", adminEmail);
  24. }
  25. });
  26. await adminRoleQuery;
  27. });
  28. }
  29. };
  30. /**
  31. * @param { import("knex").Knex } knex
  32. * @returns { Promise<void> }
  33. */
  34. async function down(knex) {};
  35. module.exports = {
  36. up,
  37. down,
  38. }