iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 16
0
Modern Web

Nest.js framework 30天初探系列 第 16

Nestjs framework 30天初探:Day16 SQL (Sequelize) PART 1

  • 分享至 

  • xImage
  •  

Sequelize是神好用的模組,可以透過它建立ORM架構的Restful API,用過Sequelize的大大們應該對它不陌生,還沒接觸過的大大們,可能先用一般的node app玩一下Sequelize再來看本篇會比較好,接下來我會使用Sequelize來操作SQL Server的資料。

1.0 sql script如下。

USE [IronManNest]
GO

/****** Object:  Table [dbo].[Users]    Script Date: 2017/12/19 下午 11:52:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Users](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NULL,
	[Age] [int] NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

1.1 建立新專案,NestCLI雖然是很方便的工具,不過似乎透過NestCLI建立的專案,其模組有的不是nestjs最新版,所以我們還是透過git去copy一份吧。
cmd 指令

git clone https://github.com/nestjs/typescript-starter.git project
cd project
npm install
  1. 安裝本次會用到的模組。
npm install --save sequelize sequelize-typescript @types/sequelize tedious body-parser @types/body-parser rxjs reflect-metadata @types/express 
npm install --save-dev typescript
npm install

3.1 請把預設的modules資料夾刪掉,專案架構要調整一下。
新架構如下,請先新增好下列資料夾、檔案。
https://ithelp.ithome.com.tw/upload/images/20171219/20107195rBt3A4sucV.png
3.2 server.ts程式碼如下。
src/server.ts

import { NestFactory } from '@nestjs/core';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import { ApplicationModule } from './app/app.module';
import { INestApplication } from '@nestjs/common';

//創建express 實例
const instance = express();
//middleware
instance.use(bodyParser.json());
instance.use(bodyParser.urlencoded({ extended: false }));
//NestFactory.create()接受一個模組引數,和一個可選的express實例引數,並返回Promise。
const app: Promise<INestApplication> = NestFactory.create(ApplicationModule, instance);

app
  //Promise傳入nest的實例引數。
  .then(nestInstance =>
    //nest實例具有listen方法,傳入port引數,和一個可選的callback function。
    nestInstance.listen(3000, () => {
      console.log('Application based on Express is listening on port 3000');
    })
  )
  .catch((err) => {
    console.error('Application configured to listen on port 3000 failed to start', err);
  });
  1. 先建立好Model,這算是最源頭也最重要的部分,ORM的概念就是一個Object對應一張表。
'use strict';

import { Table, Column, Model, DataType } from 'sequelize-typescript';
import { IDefineOptions } from 'sequelize-typescript/lib/interfaces/IDefineOptions';

const tableOptions: IDefineOptions = { timestamp: false, tableName: 'Users' } as IDefineOptions;

@Table(tableOptions)
export class Users extends Model<Users>{

    @Column({ type: DataType.INTEGER, autoIncrement: true, primaryKey: true, unique: true, field: 'ID' })
    public ID: number;

    @Column({ type: DataType.STRING(50), allowNull: true, comment: '姓名', field: 'Name'})
    public Name: string;

    @Column({ type: DataType.INTEGER, allowNull: true, comment: '年紀',field:'Age' })
    public Age: number;
}
  1. 接著完成IUsers.service.ts、IUser.ts、index.ts。
    src/app/Users/interfaces/IUsers.ts
'use strict';

export interface IUsers {
    readonly ID: number;
    readonly Name: string;
    readonly Age: number;
}

定義好Users介面

src/app/Users/interfaces/IUsers.service.ts

'use strict';

import { Users } from '../users.entity';
import { IUsers } from './IUsers';

export interface IUsersService {
    findAll(): Promise<Array<Users>>;
    findById(ID: number): Promise<Users | null>;
    findOne(options: Object): Promise<Users | null>;
    create(users: IUsers): Promise<Users>;
    update(ID: number, newValue: IUsers): Promise<Users | null>;
    delete(ID: number): Promise<number>;
}

定義好操作Users資料表的功能介面。Promise<Users | null>,若無值就回傳null。

src/app/Users/interfaces/index.ts

'use strict';

export * from './IUsers';
export * from './IUsers.service';
  1. 接著完成database.provider.ts、database.module.ts
    src/app/database.provider.ts
'use strict';

import { Sequelize } from 'sequelize-typescript';
import { Users } from './Users/users.entity';

export const databaseProviders = [
    {
        provide: 'SequelizeInstance',
        useFactory: async () => {
            const sequelize = new Sequelize({
                dialect: 'mssql',
                host: 'localhost',
                port: 1433,
                username: 'sa',
                password: 'Aa123456',
                database: 'IronManNest'
            });
            sequelize.addModels([Users]);
            await sequelize.sync();
            return sequelize;
        }
    }
]

src/app/database.module.ts

'use strict';

import { Module } from '@nestjs/common';
import { databaseProviders } from './database.provider';

@Module({
    components: [...databaseProviders],
    exports: [...databaseProviders]
})

export class DatabaseModule { }

程式碼都在github


上一篇
Nestjs framework 30天初探:Day15 MicroServices_RabbitMQ
下一篇
Nestjs framework 30天初探:Day17 SQL (Sequelize) PART 2
系列文
Nest.js framework 30天初探30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言