上一篇大概說明模擬數據的認知,
這篇就快速帶過安裝跟執行json-server,
以及相關的model建置。
npm install -g json-server
內容請參照下方#範例網。
json-server
:json-server db.json
如果是mac電腦,若出現一直
notfound db.json
的話,
要記得設定路徑。
因使用強型別typescript,
所以建置model時就會設定好變數型別,
有利於開發時在傳接值降低出錯率。
-src
|-app
|-app.component.css
|-app.component.html
|-app.component.ts
|-app.module.ts
|-model
|-base.ts
|-data
|-admin.ts
|-customer.ts
|-product.ts
|-order.ts
|-user.ts
|-index.ts
--
export interface IAdmin {
id?: number;
name: string;
account: string;
password: string;
status: number;
holds?: IHold[];//關聯"holds"
token: string;
insertBy: number;
inserted: number;
updateBy: number;
updated: number;
}
export interface IPower {
id: number;
name: string;
check?: boolean;
}
export interface IHold {
id?: number;
adminId: number;//關聯"admins"
powerId: number;
power?: IPower;//關聯"powers"
}
--
export interface ICustomer {
id?: number;
name: string;
levelId: number;
account: string;
password: string;
status: number;
updateBy: number;
updated: number;
insertBy: number;
inserted: number;
level?: ILevel;//關聯"levels"
}
export interface ILevel {
id?: number;
name: string;
}
--
export interface IProduct {
id: number;
typeId: number;
name: string;
price: number;
status: number;
file: string;
type?: IType;//關聯"types"
updateBy: number;
updated: number;
insertBy: number;
inserted: number;
}
export interface IType {
id: number;
name: string;
}
--
import { IProduct } from "./product";
import { ICustomer } from "./customer";
export interface IOrder {
id: number;
customerId: number;
cars?: IOrderCar[];//關聯"cars"
status: number;
customer?: ICustomer;//關聯"customers"
updateBy: number;
updated: number ;
insertBy: number;
inserted: number;
}
export interface IOrderCar {
id: number;
orderId: number;
productId: number;
amount: number;
product?: IProduct;//關聯"products"
}
--
這個在 json-server 的db.json
裡並沒有相對應,
理論上後台登入都是管理者身份,所以user應該是Admin Model
。
但是實務上會遇到,
很多需要紀錄此登入者的相關行為,
所以多半會另外設定一個User Model
。
流程會在一開始登入後,
就會把此admin
的資料先複製到user
去。
import { IHold } from "./admin";
export interface IUser {
id: number;
name: string;
account: string;
password: string;
status: number;
token: string;
holds: IHold[];//關聯"holds"
}
--
最後為了方便匯入model各個檔案,
會在src/app/model/底下建置index.ts
檔。
export * from "./user";
export * from "./admin";
export * from "./customer";
export * from "./product";
export * from "./order";
需匯入時
import { IAdmin,ICustomer,IProduct,IOrder,IUser } from "../model/";
那還有個問題,有的時候會呼叫所有model型別,
總不可能呼叫一個model型別寫一個function,
所以最後用type
聯合類型。
import { ICustomer, ILevel } from "./customer";
import { IProduct, IType } from "./product";
import { IUser } from "./user";
import { IAdmin, IPower, IHold } from "./admin";
import { IOrder, IOrderCar } from "./order";
export * from "./user";
export * from "./admin";
export * from "./customer";
export * from "./product";
export * from "./order";
export type IModel =
| IUser
| IAdmin
| IPower
| IHold
| ICustomer
| ILevel
| IProduct
| IType
| IOrder
| IOrderCar;
https://stackblitz.com/edit/ngcms-service