Skip to content

Commit e4c4814

Browse files
committed
feat(js): include user defined routes from *_routes.js files
In order to include custom routes: - create a file <name>_routes.js - export a function "register" that accepts 2 arguments (express router and MySQL connection pool) Part of #27
1 parent 71f12f3 commit e4c4814

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

examples/js/express/mysql/app.js

+3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const express = require('express')
22
const mysql = require('mysql')
33
const routes = require('./routes')
4+
const custom_routes = require('./custom_routes')
45

56
const app = express()
67
app.use(express.json())
@@ -34,6 +35,8 @@ const pool = mysql.createPool({
3435

3536
routes.register(app, pool)
3637

38+
custom_routes.register(app, pool)
39+
3740
const port = process.env.PORT || 3000
3841
app.listen(port, () => {
3942
console.log(`Listen on ${port}`)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
exports.register = (app, pool) => {
2+
3+
app.get('/custom/route', (req, res, next) => {
4+
res.json({ "custom": true })
5+
})
6+
7+
}

src/templates/app.js.ejs

+16
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,17 @@
1+
<%
2+
// "custom_routes.js" => "custom_routes"
3+
function removeExtension(filename) {
4+
return filename.replace(/\.js$/, '')
5+
}
6+
-%>
17
const express = require('express')
28
const mysql = require('mysql')
39
const routes = require('./routes')
10+
<% customRouteFilenames.forEach(filename => {
11+
const routerName = removeExtension(filename)
12+
-%>
13+
const <%- routerName %> = require('./<%- routerName %>')
14+
<% }) -%>
415

516
const app = express()
617
app.use(express.json())
@@ -35,6 +46,11 @@ const pool = mysql.createPool({
3546
})
3647

3748
routes.register(app, pool)
49+
<% customRouteFilenames.forEach(filename => {
50+
const routerName = removeExtension(filename)
51+
%>
52+
<%- routerName %>.register(app, pool)
53+
<% }) -%>
3854

3955
const port = process.env.PORT || 3000
4056
app.listen(port, () => {

0 commit comments

Comments
 (0)