The "routes" app collects express routers from project apps and builds them into one web app to serve.
When the "routes" service is loaded, it creates a root express app with a
socket.io instance and configured to
use pug templates. It then looks in each
installed app for router.js
to add subrouters to the root router and looks
for socket.js
to add functionality for sockets.
More on how to write these files is further below.
The default configuration for the "routes" app looks like this:
module.exports = {
// external link to site (for e-mails, etc)
linkUrl: process.env.LINK_URL || "http://localhost:8080",
// map of router-enabled apps to mount urls
urls: {
main: '/',
assets: '/assets',
public: '/public'
}
};
The linkUrl
property should be useable for external links to your project.
The urls
property should be a map of app names to mount points where the
express routers for those apps will be mounted.
The config file for the "routes" app can be copied to config/routes.js
for editing via the following command:
node . publish --config routes
You can add an express router to your web application by writing a router.js
file in your app directory. You have two options. You can either export an
express router as router
or export a function getRouter
which returns an
express router. You can only do one or the other - if you provide both, only
the value of router
will be used and getRouter
will not be called.
The getRouter
function will be called at the last minute (right before the
web server starts), so all installed apps will be mounted to the App
instance
before that time.
Here is an example of a simple router.js
file (shown using asyncHandler
,
a good module for supporting async express handlers):
// apps/my_custom_app/router.js
const express = require('express');
const asyncHandler = require('express-async-handler');
const App = require('@carolina/core');
function getRouter() {
const router = express.Router;
router.use(App.$middleware.middleware(':standard'));
router.get('/', asyncHandler(async (req, res) => {
// you could do async stuff here
return res.send("Hello");
}));
return router;
}
module.exports = { getRouter };
If you want to add configuration or events to the main socket.io instance,
you should the file socket.js
in your app directory and export a method
called socketConfig
. It will receive the socket.io instance.
Example:
function socketConfig(io) {
io.on('connection', (socket) => {
// add events to the socket
});
};
module.exports = { socketConfig };