Sequelize не регистрирует модель в базе данных

#node.js #typescript #sequelize.js

Вопрос:

Я использую библиотеку Sequelize со своей базой данных mysql. У меня есть простой сервер, единственное, что он делает в данный момент, — это создает таблицу в базе данных.

Вот код (обратите внимание, что многие вещи там не имеют отношения к вопросу):

Сервер.ts:

 import http from 'http';
import Debug from 'debug';

import app from './app';

import ServerGlobal from './server-global';

const debug = Debug('node-angular');

const normalizePort = (val: string) => {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
        return val;
    }

    if (port >= 0) {
        return port;
    }

    return null;
};

const onError = (error: NodeJS.ErrnoException) => {
    if (error.syscall !== 'listen') {
        throw error;
    }

    const addr = server.address();
    const bind = typeof addr === 'string' ? ('pipe '   addr) : ('port '   port);

    switch (error.code) {
        case 'EACCES':
            console.error(bind   'requires elevated privileges');
            process.exit(1);
        case 'EADDRINUSE':
            console.error(bind   ' is already in use');
            process.exit(1);
        default:
            throw error;
    }
};

const onListening = () => {
    const addr = server.address();
    const bind = typeof addr === 'string' ? ('pipe '   addr) : ('port '   port);

    debug("Listening on "   bind);
};

const port = normalizePort(process.env.PORT);

app.set('port', port);

const server = http.createServer(app);

server.on('error', onError);
server.on('listening', onListening);

ServerGlobal.getInstance().db.sync().then(() => {
    ServerGlobal.getInstance().logger.info(
        'Successfully initiated connection for mysql database',
        { scope: 'server-global'},
    );

    server.listen(port);

    ServerGlobal.getInstance().logger.info(`Server is running on port ${process.env.PORT}`, {
        scope: 'server',
    });
}).catch((e) => {
    ServerGlobal.getInstance().logger.error(
        `Failed to initiated connection for mysql database with error: ${e}`,
        {
            scope: 'server-global',
            data: { error: e },
        },
    );
});
 

приложение.ts:

 import express from 'express';

import userRouter from './router/user';

const app: express.Application = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }))

app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    res.setHeader('Access-Control-Allow-Origin', process.env.HTTP_ACCESS_IP);
    res.setHeader(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, Authorization',
    );
    res.setHeader(
        'Access-Control-Allow-Methods',
        'OPTIONS, GET, POST, PATCH, DELETE, PUT',
    );
    next();
});

app.use('/user', userRouter);

export default app;
 

У меня также есть следующий файл server-global.ts, который содержит одноэлементный экземпляр некоторых глобальных переменных на сервере:

 import winston from 'winston';
import { Sequelize } from 'sequelize';

class ServerGlobal {
    private readonly _logger: winston.Logger;
    private readonly _db: Sequelize;

    private static _instance: ServerGlobal;

    private constructor() {
        this._logger = winston.createLogger({
            level: 'info',
            format: winston.format.combine(
                winston.format.timestamp(),
                winston.format.json(),
            ),
        });

        this._db = new Sequelize(
            process.env.MYSQL_SCHEMA,
            process.env.MYSQL_USERNAME,
            process.env.MYSQL_PASSWORD,
            {
                dialect: 'mysql',
                host: process.env.MYSQL_HOST,
            },
        );
    }

    /**
    * Getter for singelton instance
    * @returns ServerGlobal singelton instance
    */
    static getInstance() {
        if (this._instance) {
            return this._instance;
        }

        this._instance = new ServerGlobal();
        return this._instance;
    }

    /**
    * Getter for the logger
    * @returns logger instance 
    */
    public get logger() {
        return this._logger;
    }

    /**
    * Getter for the db
    * @returns db instance 
    */
    public get db() {
        return this._db;
    }
}

export default ServerGlobal;
 

Now I define a model named User :

 import Sequelize from 'sequelize';

import ServerGlobal from '../server-global';

import { emailRegex } from '../utils/regex';

const User = ServerGlobal.getInstance().db.define('user', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
    },
    email: {
        type: Sequelize.STRING,
        unique: true,
        allowNull: false,
        validate: {
            is: emailRegex,
        },
    },
});

export default User;
 

So, because I did ...db.sync() in the server.ts file, according to the library, it should register the user model into the database. However, when I do run the server, it does not happen as like the user model files hasn’t been executed at all.

What do I miss? (The user tables is not been created..)