Skip to content

Commit

Permalink
feat(ts): include user defined routes from *_routes.ts files
Browse files Browse the repository at this point in the history
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
  • Loading branch information
php-coder committed Apr 17, 2024
1 parent e4c4814 commit 87c870a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
2 changes: 2 additions & 0 deletions examples/ts/express/mysql/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import express from 'express'
import mysql from 'mysql'

const routes = require('./routes')
const custom_routes = require('./custom_routes')

const app = express()
app.use(express.json())
Expand Down Expand Up @@ -34,6 +35,7 @@ const pool = mysql.createPool({
})

routes.register(app, pool)
custom_routes.register(app, pool)

const port = process.env.PORT || 3000
app.listen(port, () => {
Expand Down
10 changes: 10 additions & 0 deletions examples/ts/express/mysql/custom_routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Express, NextFunction, Request, Response } from 'express'
import { Pool } from 'mysql'

exports.register = (app: Express, pool: Pool) => {

app.get('/custom/route', (req: Request, res: Response, next: NextFunction) => {
res.json({ "custom": true })
})

}
16 changes: 16 additions & 0 deletions src/templates/app.ts.ejs
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
<%
// "custom_routes.ts" => "custom_routes"
function removeExtension(filename) {
return filename.replace(/\.ts$/, '')
}
-%>
import express from 'express'
import mysql from 'mysql'

const routes = require('./routes')
<% customRouteFilenames.forEach(filename => {
const routerName = removeExtension(filename)
-%>
const <%- routerName %> = require('./<%- routerName %>')
<% }) -%>

const app = express()
app.use(express.json())
Expand Down Expand Up @@ -36,6 +47,11 @@ const pool = mysql.createPool({
})

routes.register(app, pool)
<% customRouteFilenames.forEach(filename => {
const routerName = removeExtension(filename)
-%>
<%- routerName %>.register(app, pool)
<% }) -%>

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

0 comments on commit 87c870a

Please sign in to comment.