import Migration from "../../db/Migration"; import ModelFactory from "../../db/ModelFactory"; import User from "../models/User"; import UserNameComponent from "../models/UserNameComponent"; import MagicLink from "../models/MagicLink"; import MagicLinkUserNameComponent from "../models/MagicLinkUserNameComponent"; import {nanoid} from "nanoid"; export default class AddNameToUsersMigration extends Migration { public async install(): Promise { await this.query(`ALTER TABLE users ADD COLUMN name VARCHAR(64) NOT NULL`); await this.query(`ALTER TABLE magic_links ADD COLUMN username VARCHAR(64) DEFAULT NULL`); // Give every user a random name const users = await User.select().get(this.getCurrentConnection()); const callbacks: (() => Promise)[] = []; await Promise.all(users.map(user => { user.name = nanoid(); return user.save(this.getCurrentConnection(), c => callbacks.push(c)); })); await Promise.all(callbacks); await this.query(`ALTER TABLE users ADD CONSTRAINT UNIQUE (name)`); } public async rollback(): Promise { await this.query('ALTER TABLE users DROP COLUMN name'); await this.query('ALTER TABLE magic_links DROP COLUMN username'); } public registerModels(): void { ModelFactory.get(User).addComponent(UserNameComponent); ModelFactory.get(MagicLink).addComponent(MagicLinkUserNameComponent); } }