Skip to content

Instantly share code, notes, and snippets.

@Romakita
Last active April 4, 2020 09:37
Show Gist options
  • Save Romakita/0936933b93738e40391ad02c905b950d to your computer and use it in GitHub Desktop.
Save Romakita/0936933b93738e40391ad02c905b950d to your computer and use it in GitHub Desktop.
Crud Mongoose Controller
import {Type, nameOf} from "@tsed/core";
const {paramCase} = require("change-case");
export interface ICrudControllerOptions {
path?: string;
model: Type<any>
}
export function CrudController(options: ICrudControllerOptions) {
return (target: Type<any>) =>{
registerController({
provide: target,
path: "/" + paramCase(nameOf(target)),
controllerType: "crudController", // add metadata type to find crud controller from Cur
...options
});
// Inject automatically mongoosee model on the model property
Inject(options.model)(target.prototype, "model");
}
}
import {Module, Constant, ProviderType, InjectorService, Platform, ControllerProvider, AfterInit} from "@tsed/common";
@Module()
export class CrudLoaderModule implement AfterInit {
@Inject()
private injector: InjectorService;
@Inject()
private platform: Platform;
$afterInit() {
this.injector
.getProviders(ProviderType.CONTROLLER)
.filter((provider) => provider.controllerType === "crudController")
.forEach((provider: ControllerProvider) => {
// you can change also the provider.path = "/sub-model-path"
this.addController("/global-path", provider.token)
});
}
addController(endpoint: string, token: Type<any>) {
this.settings.mount[endpoint] = (this.settings.mount[endpoint] || []).concat(provider);
}
}
import {Inject, Controller} from "@tsed/common";
import {MongooseModel} from "@tsed/mongoose";
export class CrudMongoose<T> {
protected model: MongooseModel<T>;
@Get("/:id")
async get(@PathParams("id") id: string): Promise<T> {
const instance = await this.model.findById(id).exec(); // change the requet
return instance
}
@Post("/") 
async post(@BodyParams() @Required() payload: T): Promise<T> {
//etc...
}
// etc...
}
import {Inject, Controller} from "@tsed/common";
import {MongooseModel} from "@tsed/mongoose";
import {MyModel} from "../models/MyModel";
import {CrudMongoose} from "../utils/CrudMongoose";
import {CrudController} from "../decorators/CrudController";
@CrudController({
model: MyModel
})
export classs MyCrudController extends CrudMongoose<MyModel> {
// implement custom
}
import {
Required
} from "@tsed/common";
import {Model, ObjectID, Unique} from "@tsed/mongoose";
@Model()
export class MyModel {
@ObjectID("id")
_id: string;
@Unique()
@Required()
name: string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment