Skip to content

Instantly share code, notes, and snippets.

@zmnv
Created November 4, 2019 13:41
Show Gist options
  • Save zmnv/42f762c42a55288ea9099553e1d54f0b to your computer and use it in GitHub Desktop.
Save zmnv/42f762c42a55288ea9099553e1d54f0b to your computer and use it in GitHub Desktop.
Generate controller classes by model
import { Request, Response, NextFunction } from 'express';
export type ExpressMethodType = (req: Request, res: Response, next?: NextFunction) => void;
export interface CrudControllerInterface {
addNew?: ExpressMethodType;
get?: ExpressMethodType;
getById?: ExpressMethodType;
update?: ExpressMethodType;
delete?: ExpressMethodType;
}
import * as mongoose from 'mongoose';
import { CrudControllerInterface, ExpressMethodType } from "./crudController";
import { LogMessageSchema } from './models/logMessage.model';
export const Logs = mongoose.model('Log', LogMessageSchema);
/**
* Using in router:
* const controller = createLogsController(Logs);
*/
export function createLogsController(model) {
return new LogsController(model);
}
export class LogsController implements CrudControllerInterface {
modelClass: mongoose.Model<mongoose.Document, {}>;
addNew: ExpressTypeType;
get: ExpressTypeType;
getById: ExpressTypeType;
constructor(className) {
this.modelClass = className;
console.log(this.modelClass);
this.addNew = (req, res) => {
let newEvent = new this.modelClass(req.body);
newEvent.save((err, data) => {
if(err){
res.send(err);
}
res.json(data);
});
}
this.get = (req, res) => {
this.modelClass.find({}, (err, data) => {
if(err){
res.send(err);
}
res.json(data);
});
}
this.getById = (req, res) => {
const session_id = req.params.sessionId;
this.modelClass.find({ session_id }, (err, data) => {
if(err){
res.send(err);
}
res.json(data);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment