This is an inheritable api controller for a nodejs express app
npm install express-base-controller --save
- include your own isAuthenticated and hasAuthorization hooks
// controllers/base.controller.server.ts
import {
Response,
NextFunction
} from 'express';
import {
BaseController,
IApiModel,
IApiRequest
} from 'express-base-controller';
import {
isAuthenticated,
hasAuthorization
} from './users.auth.controller';
abstract class MyBaseController<T extends IApiModel> extends BaseController<T> {
isAuthenticated(req: IApiRequest, res: Response, next: NextFunction) {
return isAuthenticated(req, res, next);
}
hasAuthorization(
roles: string | string[],
req: IApiRequest,
res: Response,
next: NextFunction
) {
return hasAuthorization(roles, req, res, next);
}
}
export default MyBaseController;
- Inherit MyBaseController in all your express controllers
import { IApiRequest } from 'express-base-controller';
import MyBaseController from './base.controller';
import { IUserModel } from '../types/user.model.types';
// controllers/users.controller.server.ts
class UsersController extends MyBaseController<IUserModel> {
constructor(model: IUserModel) {
super(model);
this.filters.push('roles');
}
}
const usersController = new UsersController(User);
export default usersController;
- setup your routes in the following way
import {
Router
} from 'express';
import {
signin,
signup,
signout
} from '../controllers/users.auth.controller';
import usersController from '../controllers/users.controller';
const userRouter = Router();
userRouter.post('/auth/signin', signin);
userRouter.post('/auth/signup', signup);
userRouter.post('/auth/signout', signout);
userRouter.use('/users', users.isAuthenticated.bind(users));
userRouter.route('/users')
.get(
usersController.hasAuthorization.bind(users, ['admin', 'client']),
usersController.index.bind(users),
usersController.populateMeta.bind(users),
usersController.apiResponse.bind(users)
)
.post(
usersController.hasAuthorization.bind(users, ['admin']),
usersController.create.bind(users)
);
userRouter.route('/users/self')
.get(usersController.self.bind(users))
.put(usersController.updateSelf.bind(users));
userRouter.route('/users/:userId')
.get(
usersController.hasAuthorization.bind(users, ['admin', 'client']),
usersController.read.bind(users)
)
.put(
usersController.hasAuthorization.bind(users, ['admin']),
usersController.update.bind(users)
)
.delete(usersController.hasAuthorization.bind(users, 'admin'), users.delete.bind(users));
userRouter.param('userId', users.findById.bind(users));
export default userRouter;
?select=data date&sort={"date":1}