|
| 1 | +const express = require('express'); |
| 2 | + |
| 3 | +const controllers = require('../controllers'); |
| 4 | + |
| 5 | +const router = express.Router(); |
| 6 | +const { |
| 7 | + auth, |
| 8 | + home, |
| 9 | + publication, |
| 10 | +} = controllers; |
| 11 | + |
| 12 | +/** |
| 13 | + * Handles controller execution and responds to user (API version). |
| 14 | + * This way controllers are not attached to the API. |
| 15 | + * Web socket has a similar handler implementation. |
| 16 | + * @param promise Controller Promise. |
| 17 | + * @param params (req) => [params, ...]. |
| 18 | + */ |
| 19 | +const controllerHandler = (promise, params) => async (req, res, next) => { |
| 20 | + const boundParams = params ? params(req, res, next) : []; |
| 21 | + try { |
| 22 | + const result = await promise(...boundParams); |
| 23 | + return res.json(result || { message: 'OK' }); |
| 24 | + } catch (error) { |
| 25 | + return res.status(500) && next(error); |
| 26 | + } |
| 27 | +}; |
| 28 | +const c = controllerHandler; |
| 29 | + |
| 30 | +/** |
| 31 | + * Auth. |
| 32 | + */ |
| 33 | +router.post('/signin', c(auth.signin, (req, res, next) => [req, res, next])); |
| 34 | +router.post('/signup', c(auth.signup, (req, res, next) => [req, res, next])); |
| 35 | + |
| 36 | +/** |
| 37 | + * Home. |
| 38 | + */ |
| 39 | +router.get('/', c(home.hello)); |
| 40 | +router.get('/greet/:name', c(home.getGreeting, req => [req.params.name])); |
| 41 | +router.post('/greet/', c(home.postGreeting, req => [req.body.name])); |
| 42 | + |
| 43 | +/** |
| 44 | + * Publications. |
| 45 | + */ |
| 46 | +router.get('/publications', c(publication.getPublications)); |
| 47 | +router.post('/publications', c(publication.postPublication, req => [req.user, req.body.content])); |
| 48 | + |
| 49 | +/** |
| 50 | + * Error-handler. |
| 51 | + */ |
| 52 | +router.use((err, req, res, _next) => { |
| 53 | + // Expected errors always throw ServerError. |
| 54 | + // Unexpected errors will either throw unexpected stuff or crash the application. |
| 55 | + if (Object.prototype.isPrototypeOf.call(ServerError.prototype, err)) { |
| 56 | + return res.status(err.status || 500).json({ error: err.message }); |
| 57 | + } |
| 58 | + |
| 59 | + log.error('~~~ Unexpected error exception start ~~~'); |
| 60 | + log.error(req); |
| 61 | + log.error(err); |
| 62 | + log.error('~~~ Unexpected error exception end ~~~'); |
| 63 | + |
| 64 | + |
| 65 | + return res.status(500).json({ error: '⁽ƈ ͡ (ुŏ̥̥̥̥םŏ̥̥̥̥) ु' }); |
| 66 | +}); |
| 67 | + |
| 68 | +module.exports = router; |
0 commit comments