美文网首页node
sequelize-typescript安装配置

sequelize-typescript安装配置

作者: AsaGuo | 来源:发表于2019-01-30 14:41 被阅读10次

    一、安装

      1. 安装TypeScript
    npm install typescript
    npm install ts-node
    
      1. 安装sequelize-typescript及相关库
    npm install sequelize
    npm install reflect-metadata
    npm install sequelize-typescript
    

    二、配置(同TypeScript配置)

    // tsconfig.json
    {
      "compilerOptions": {
        /* Basic Options */
        "target": "es6",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
        "allowJs": true,                       /* Allow javascript files to be compiled. */
        "outDir": "./dist",                        /* Redirect output structure to the directory. */
        "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    
        /* Strict Type-Checking Options */
        "strict": true,                           /* Enable all strict type-checking options. */
        "strictPropertyInitialization": false,  /* Enable strict checking of property initialization in classes. */
    
        /* Module Resolution Options */
        "esModuleInterop": true,                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    
        /* Experimental Options */
        "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
        "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
      },
      "include": [
        "src/*",
        "src/**/*"
      ],
      "exclude": [
        "node_modules"
      ]
    }
    

    三、架构

    目录结构:
    |—src
    |——ef_models
    |———tables
    |—————base_table.ts
    |—————derived_table.ts
    |———views
    |———db_context.ts
    |—app.ts

    (一)基类

    import { Table, Column, Model } from 'sequelize-typescript';
    
    @Table({
        tableName:'base_table'
    })
    export default class BaseTable extends Model<BaseTable>{
        @Column({
            primaryKey:true,
            autoIncrement:true
        })
        rid:number;
    
        /**
         * 字符串索引器
         */
        [index:string]:any;
    
        /**
         * 添加
         * @param item 新项目
         */
        static async createItem<T extends BaseTable>(item:T){
            return await this.create(item);
        }
    
        /**
         * 删除
         * @param rid 
         */
        static async deleteById<T extends BaseTable>(rid:number){
            return await this.destroy({
                where:{rid:rid}
            });
        }
    
        /**
         * 更新
         * @param item 新项目对象
         * @param rid 需要修改的项目rid
         */
        static async updateItemById<T extends BaseTable>(item:T, rid:number){
            let objItem = await this.getById(rid) as T;
            for(let key in item)
                objItem[key] = item[key];
            
            return await objItem.save();
        }
    
        /**
         * 查询所有
         */
        static async getList<T extends BaseTable>(){
            let items = await this.findAll({raw:true});
            return items as T[];
        }
    
        /**
         * 查询(通过rid)
         * @param rid 
         */
        static async getById<T extends BaseTable>(rid:number){
            let item = await this.findOne({
                raw:true,
                where:{rid:rid}
            });
    
            return item as T;
        }
    }
    

    (二)派生类

    import { Table, Column, Model } from 'sequelize-typescript';
    import BaseTable from './base_table';
    
    @Table({
        tableName:'derived_table'
    })
    export default class derived_table extends BaseTable{
        @Column
        name:string;
    
        @Column
        age:number;
    
        @Column
        create_time:Date;
    }
    

    (三)上下文

    import { Sequelize} from 'sequelize-typescript';
    import BaseTable from './tables/base_table';
    import derived_table from './tables/derived_table';
    
    // All entities
    import  from './models/access_record';
    
    const sequelize = new Sequelize({
        database:"my_database",
        username:"root",
        password:"123456",
        host:"localhost",
        port:3306,
        dialect:'mysql',
        operatorsAliases:false,
    
        pool:{
            max:5,
            min:0,
            acquire:30000,
            idle:10000
        },
    
        // 时区设置
        dialectOptions:{
            useUTC:false // for reading from database
        },
        timezone:'+8:00' // for writing to database
    })
    sequelize.addModels([__dirname + '/models']);
    
    sequelize.authenticate().then(() => {
        console.log('Connection has been established successfully.')
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err)
    });
    
    export { sequelize, BaseTable, derived_table }
    

    (四)应用

    // app.ts
    import * as db_context from './db_context'
    
    db_context
        .derived_table
        .getList<db_context.derived_table>()
        .then(results => {
            console.log('results:',results);
        });
    

    相关文章

      网友评论

        本文标题:sequelize-typescript安装配置

        本文链接:https://www.haomeiwen.com/subject/kufcsqtx.html