Created
November 4, 2019 13:41
-
-
Save zmnv/42f762c42a55288ea9099553e1d54f0b to your computer and use it in GitHub Desktop.
Generate controller classes by model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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