Skip to content

Commit 87c870a

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

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

examples/ts/express/mysql/app.ts

+2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import express from 'express'
22
import mysql from 'mysql'
33

44
const routes = require('./routes')
5+
const custom_routes = require('./custom_routes')
56

67
const app = express()
78
app.use(express.json())
@@ -34,6 +35,7 @@ const pool = mysql.createPool({
3435
})
3536

3637
routes.register(app, pool)
38+
custom_routes.register(app, pool)
3739

3840
const port = process.env.PORT || 3000
3941
app.listen(port, () => {
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { Express, NextFunction, Request, Response } from 'express'
2+
import { Pool } from 'mysql'
3+
4+
exports.register = (app: Express, pool: Pool) => {
5+
6+
app.get('/custom/route', (req: Request, res: Response, next: NextFunction) => {
7+
res.json({ "custom": true })
8+
})
9+
10+
}

src/templates/app.ts.ejs

+16
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
1+
<%
2+
// "custom_routes.ts" => "custom_routes"
3+
function removeExtension(filename) {
4+
return filename.replace(/\.ts$/, '')
5+
}
6+
-%>
17
import express from 'express'
28
import mysql from 'mysql'
39

410
const routes = require('./routes')
11+
<% customRouteFilenames.forEach(filename => {
12+
const routerName = removeExtension(filename)
13+
-%>
14+
const <%- routerName %> = require('./<%- routerName %>')
15+
<% }) -%>
516

617
const app = express()
718
app.use(express.json())
@@ -36,6 +47,11 @@ const pool = mysql.createPool({
3647
})
3748

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

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

0 commit comments

Comments
 (0)