feat: add provide and update template
This commit is contained in:
parent
829ca19b4a
commit
177c001bb8
@ -1,23 +1,54 @@
|
||||
import {
|
||||
controller, httpGet, httpPost
|
||||
controller, response, requestBody, httpGet, httpPost, queryParam
|
||||
} from 'inversify-express-utils';
|
||||
import { inject } from 'inversify';
|
||||
import { DBClient } from 'cc-server-db'
|
||||
import 'cc-server-db-mongo'
|
||||
|
||||
//process.env.FAAS_MONGO_URL = 'mongodb://192.168.0.2:27017';
|
||||
process.env.FAAS_MONGO_DB = "faas";
|
||||
|
||||
const TABLE = 'users'
|
||||
|
||||
interface ExampleModel {
|
||||
_id: string;
|
||||
username: string;
|
||||
password: string;
|
||||
age: number;
|
||||
email: string;
|
||||
}
|
||||
|
||||
type Model = ExampleModel
|
||||
|
||||
@controller('/')
|
||||
export class UserController {
|
||||
constructor(
|
||||
@inject(DBClient) private client: DBClient
|
||||
) { }
|
||||
export class Controller {
|
||||
@inject(DBClient)
|
||||
private client: DBClient
|
||||
|
||||
@httpGet('/')
|
||||
public async getUsers(): Promise<any[]> {
|
||||
return this.client.find('users', {});
|
||||
public async list(): Promise<Model[]> {
|
||||
return this.client.find(TABLE, {});
|
||||
}
|
||||
|
||||
@httpGet('/:id')
|
||||
public async get(
|
||||
@queryParam('id') id: string
|
||||
): Promise<Model> {
|
||||
return this.client.findOneById(TABLE, id);
|
||||
}
|
||||
|
||||
@httpPost('/')
|
||||
public async newUser(): Promise<any> {
|
||||
return {}
|
||||
public async create(
|
||||
@requestBody() model: Model
|
||||
): Promise<Model> {
|
||||
return this.client.insertOne(TABLE, model);
|
||||
}
|
||||
|
||||
@httpPost('/:id')
|
||||
public async update(
|
||||
@queryParam('id') id: string,
|
||||
@requestBody() model: Model
|
||||
): Promise<boolean> {
|
||||
return this.client.updateById(TABLE, id, model);
|
||||
}
|
||||
}
|
||||
|
@ -4,7 +4,7 @@ import { provide } from 'cc-server-ioc'
|
||||
import { DBClient } from 'cc-server-db'
|
||||
|
||||
@provide(DBClient)
|
||||
export class MongoDBClient<T = any> {
|
||||
export class MongoDBClient<T = any> implements DBClient {
|
||||
public db: Db;
|
||||
|
||||
constructor() {
|
||||
@ -13,6 +13,10 @@ export class MongoDBClient<T = any> {
|
||||
});
|
||||
}
|
||||
|
||||
public getProvide(): Db {
|
||||
return this.db;
|
||||
}
|
||||
|
||||
public async find(collection: string, filter: object): Promise<T[]> {
|
||||
return await this.db.collection(collection).find(filter).toArray();
|
||||
}
|
@ -1 +1,2 @@
|
||||
export * from './client'
|
||||
export * from 'mongodb';
|
@ -1,5 +1,6 @@
|
||||
export const DBClient = Symbol.for('DBClient')
|
||||
export interface DBClient<T = any> {
|
||||
getProvide(): any;
|
||||
find(collection: string, filter: object): Promise<T[]>;
|
||||
findOne(collection: string, filter: Object): Promise<T>;
|
||||
findOneById(collection: string, objectId: string): Promise<T>;
|
||||
|
Loading…
Reference in New Issue
Block a user