mirror of
https://github.com/HabitRPG/habitica.git
synced 2025-12-19 15:48:04 +01:00
add example controller and lib to setup routes
This commit is contained in:
15
website/src/controllers/api-v3/example.js
Normal file
15
website/src/controllers/api-v3/example.js
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
// An example file to show how a controller should be structured
|
||||||
|
let api = {};
|
||||||
|
|
||||||
|
api.exampleRoute = {
|
||||||
|
method: 'GET',
|
||||||
|
url: '/example/:param',
|
||||||
|
middlewares: [],
|
||||||
|
handler (req, res) {
|
||||||
|
res.status(200).send({
|
||||||
|
status: 'ok'
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default api;
|
||||||
23
website/src/libs/api-v3/setupRoutes.js
Normal file
23
website/src/libs/api-v3/setupRoutes.js
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import express from 'express';
|
||||||
|
import _ from 'lodash';
|
||||||
|
const CONTROLLERS_PATH = path.join(__dirname, '/../../controllers/api-v3/');
|
||||||
|
let router = express.Router();
|
||||||
|
|
||||||
|
fs
|
||||||
|
.readdirSync(CONTROLLERS_PATH)
|
||||||
|
.filter(fileName => fileName.match(/\.js$/))
|
||||||
|
.filter(fileName => fs.statSync(CONTROLLERS_PATH + fileName).isFile())
|
||||||
|
.forEach((fileName) => {
|
||||||
|
let controller = require(CONTROLLERS_PATH + fileName);
|
||||||
|
|
||||||
|
_.each(controller, (action) => {
|
||||||
|
let {method, url, middlewares, handler} = action;
|
||||||
|
|
||||||
|
method = method.toLowerCase();
|
||||||
|
router[method](url, ...middlewares, handler);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
import analytics from './analytics';
|
import analytics from './analytics';
|
||||||
import errorHandler from './errorHandler';
|
import errorHandler from './errorHandler';
|
||||||
import bodyParser from 'body-parser';
|
import bodyParser from 'body-parser';
|
||||||
|
import routes from '../../libs/api-v3/setupRoutes';
|
||||||
|
|
||||||
export default function attachMiddlewares (app) {
|
export default function attachMiddlewares (app) {
|
||||||
// Parse query parameters and json bodies
|
// Parse query parameters and json bodies
|
||||||
@@ -14,6 +15,7 @@ export default function attachMiddlewares (app) {
|
|||||||
|
|
||||||
app.use(analytics);
|
app.use(analytics);
|
||||||
|
|
||||||
|
app.use(routes);
|
||||||
// Error handler middleware, define as the last one
|
// Error handler middleware, define as the last one
|
||||||
app.use(errorHandler);
|
app.use(errorHandler);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user