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
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資料夾刪掉,專案架構要調整一下。
新架構如下,請先新增好下列資料夾、檔案。
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);
});
'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;
}
'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';
'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