typescript + express + mongoose 实例

typescript + express + mongoose 实例

最近在学习 typescript ,所以用 typescript 来写了个 MVC 实例。

typescript + mongoose

Order.js

'use strict';
import mongoose = require('mongoose');
const Schema = mongoose.Schema;

interface IOrder extends mongoose.Document {
amount: string;
oType: string;
pType: string;
status: string;
createdAt: Date;
}

const _schema = new Schema({
amount: {type: Number},
oType: {type: Number},
pType: {type: Number},
status: {type: Number},
bankcard: {type: String},
parent_id: {type: String},
createdAt: {type: Date, default: Date.now}
}, {collection: 'order', id: true});

_schema.path('amount').required(true, 'Order amount cannot be blank');
_schema.path('status').required(true, 'Order status cannot be blank');

_schema.pre('remove', function (next) {
next();
});

const _model = mongoose.model < IOrder >('Order', _schema);

class Order {
/**
* static
* @param id
* @returns {Promise<Order>}
*/

static findById(id:string):Promise < Order > {
console.log('findById2', ' 执行 ');
return new Promise<Order>((resolve, reject) => {
_model.findById(id, (err, order) => {
err ? reject(err) : resolve(new Order(order))
})
});
}
/**
* static
* @param id
* @returns {Promise<Order>}
*/

static findById2(id:string):Promise < Order > {
return new Promise<Order>((resolve, reject) => {
_model.findById(id)
.exec()
.onResolve((err, order) => {
err ? reject(err) : resolve(new Order(order))
});
});
}
/**
*
*/

private _document:IOrder;
/**
* 构造器
* @param document
*/

constructor(document:IOrder) {
this._document = document;
}
get amount():string {
return this._document.amount;
}
}

export default Order

还是需要定义好 Order 表的 schema 以及 Order 的 Interface IOrder,这样通过 mongoose 查询到的实例都是实现了 IOrder 接口的。

typescript 与 express

使用装饰器(注解)
OrderController.js

import e = require('express');
import Order from '../models/Order'
import {router} from "../decorators/Web";


const timeOut = function (time) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(`respond with asynv await ${time} ms`)
}, time)
});
};

class OrderController {
@router({
method: 'get',
path: '/order/awaitTest'
})
async awaitTest(req:e.Request, res) {
console.log('OrderController', 'awaitTest');
let result = await timeOut(10);
res.send(result);
}

@router({
method: 'get',
path: '/order/findOneWithClass'
})
async findOneWithClass(req:e.Request, res:e.Response) {
let result = await Order.findById2('54ce6d7779337f164b36504a')
res.status(200).json(result);
res.status(200).json(result);
}

}

export default OrderController

装饰器是 es7 的新特性,typescript 已经实现了该功能。具体请看源码实现或者文档。

源码