Skip to content

Commit b8f57c0

Browse files
committed
feat: generate endpoints in a separate file (routes.js)
Fix #6
1 parent a83c669 commit b8f57c0

File tree

5 files changed

+161
-136
lines changed

5 files changed

+161
-136
lines changed

examples/js/app.js

Lines changed: 2 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const bodyParser = require('body-parser')
22
const express = require('express')
33
const mysql = require('mysql')
4+
const routes = require('./routes')
45

56
const app = express()
67
app.use(bodyParser.json())
@@ -25,107 +26,7 @@ const pool = mysql.createPool({
2526
}
2627
})
2728

28-
29-
app.get('/v1/categories/count', (req, res) => {
30-
pool.query(
31-
'SELECT COUNT(*) AS counter FROM categories',
32-
(err, rows, fields) => {
33-
if (err) {
34-
throw err
35-
}
36-
if (rows.length === 0) {
37-
res.type('application/json').status(404).end()
38-
return
39-
}
40-
res.json(rows[0])
41-
}
42-
)
43-
})
44-
45-
app.get('/v1/collections/:collectionId/categories/count', (req, res) => {
46-
pool.query(
47-
'SELECT COUNT(DISTINCT s.category_id) AS counter FROM collections_series cs JOIN series s ON s.id = cs.series_id WHERE cs.collection_id = :collectionId',
48-
{ "collectionId": req.params.collectionId },
49-
(err, rows, fields) => {
50-
if (err) {
51-
throw err
52-
}
53-
if (rows.length === 0) {
54-
res.type('application/json').status(404).end()
55-
return
56-
}
57-
res.json(rows[0])
58-
}
59-
)
60-
})
61-
62-
app.get('/v1/categories', (req, res) => {
63-
pool.query(
64-
'SELECT id , name , name_ru , slug FROM categories',
65-
(err, rows, fields) => {
66-
if (err) {
67-
throw err
68-
}
69-
res.json(rows)
70-
}
71-
)
72-
})
73-
74-
app.post('/v1/categories', (req, res) => {
75-
pool.query(
76-
'INSERT INTO categories ( name , name_ru , slug , created_at , created_by , updated_at , updated_by ) VALUES ( :name , :nameRu , :slug , NOW() , :userId , NOW() , :userId )',
77-
{ "name": req.body.name, "nameRu": req.body.nameRu, "slug": req.body.slug, "userId": req.body.userId },
78-
(err, rows, fields) => {
79-
if (err) {
80-
throw err
81-
}
82-
res.sendStatus(204)
83-
}
84-
)
85-
})
86-
87-
app.get('/v1/categories/:categoryId', (req, res) => {
88-
pool.query(
89-
'SELECT id , name , name_ru , slug FROM categories WHERE id = :categoryId',
90-
{ "categoryId": req.params.categoryId },
91-
(err, rows, fields) => {
92-
if (err) {
93-
throw err
94-
}
95-
if (rows.length === 0) {
96-
res.type('application/json').status(404).end()
97-
return
98-
}
99-
res.json(rows[0])
100-
}
101-
)
102-
})
103-
104-
app.put('/v1/categories/:categoryId', (req, res) => {
105-
pool.query(
106-
'UPDATE categories SET name = :name , name_ru = :nameRu , slug = :slug , updated_at = NOW() , updated_by = :userId WHERE id = :categoryId',
107-
{ "name": req.body.name, "nameRu": req.body.nameRu, "slug": req.body.slug, "userId": req.body.userId, "categoryId": req.body.categoryId },
108-
(err, rows, fields) => {
109-
if (err) {
110-
throw err
111-
}
112-
res.sendStatus(204)
113-
}
114-
)
115-
})
116-
117-
app.delete('/v1/categories/:categoryId', (req, res) => {
118-
pool.query(
119-
'DELETE FROM categories WHERE id = :categoryId',
120-
{ "categoryId": req.params.categoryId },
121-
(err, rows, fields) => {
122-
if (err) {
123-
throw err
124-
}
125-
res.sendStatus(204)
126-
}
127-
)
128-
})
29+
routes.register(app, pool)
12930

13031
const port = process.env.PORT || 3000;
13132
app.listen(port, () => {

examples/js/routes.js

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
const register = (app, pool) => {
2+
3+
4+
app.get('/v1/categories/count', (req, res) => {
5+
pool.query(
6+
'SELECT COUNT(*) AS counter FROM categories',
7+
(err, rows, fields) => {
8+
if (err) {
9+
throw err
10+
}
11+
if (rows.length === 0) {
12+
res.type('application/json').status(404).end()
13+
return
14+
}
15+
res.json(rows[0])
16+
}
17+
)
18+
})
19+
20+
app.get('/v1/collections/:collectionId/categories/count', (req, res) => {
21+
pool.query(
22+
'SELECT COUNT(DISTINCT s.category_id) AS counter FROM collections_series cs JOIN series s ON s.id = cs.series_id WHERE cs.collection_id = :collectionId',
23+
{ "collectionId": req.params.collectionId },
24+
(err, rows, fields) => {
25+
if (err) {
26+
throw err
27+
}
28+
if (rows.length === 0) {
29+
res.type('application/json').status(404).end()
30+
return
31+
}
32+
res.json(rows[0])
33+
}
34+
)
35+
})
36+
37+
app.get('/v1/categories', (req, res) => {
38+
pool.query(
39+
'SELECT id , name , name_ru , slug FROM categories',
40+
(err, rows, fields) => {
41+
if (err) {
42+
throw err
43+
}
44+
res.json(rows)
45+
}
46+
)
47+
})
48+
49+
app.post('/v1/categories', (req, res) => {
50+
pool.query(
51+
'INSERT INTO categories ( name , name_ru , slug , created_at , created_by , updated_at , updated_by ) VALUES ( :name , :nameRu , :slug , NOW() , :userId , NOW() , :userId )',
52+
{ "name": req.body.name, "nameRu": req.body.nameRu, "slug": req.body.slug, "userId": req.body.userId },
53+
(err, rows, fields) => {
54+
if (err) {
55+
throw err
56+
}
57+
res.sendStatus(204)
58+
}
59+
)
60+
})
61+
62+
app.get('/v1/categories/:categoryId', (req, res) => {
63+
pool.query(
64+
'SELECT id , name , name_ru , slug FROM categories WHERE id = :categoryId',
65+
{ "categoryId": req.params.categoryId },
66+
(err, rows, fields) => {
67+
if (err) {
68+
throw err
69+
}
70+
if (rows.length === 0) {
71+
res.type('application/json').status(404).end()
72+
return
73+
}
74+
res.json(rows[0])
75+
}
76+
)
77+
})
78+
79+
app.put('/v1/categories/:categoryId', (req, res) => {
80+
pool.query(
81+
'UPDATE categories SET name = :name , name_ru = :nameRu , slug = :slug , updated_at = NOW() , updated_by = :userId WHERE id = :categoryId',
82+
{ "name": req.body.name, "nameRu": req.body.nameRu, "slug": req.body.slug, "userId": req.body.userId, "categoryId": req.body.categoryId },
83+
(err, rows, fields) => {
84+
if (err) {
85+
throw err
86+
}
87+
res.sendStatus(204)
88+
}
89+
)
90+
})
91+
92+
app.delete('/v1/categories/:categoryId', (req, res) => {
93+
pool.query(
94+
'DELETE FROM categories WHERE id = :categoryId',
95+
{ "categoryId": req.params.categoryId },
96+
(err, rows, fields) => {
97+
if (err) {
98+
throw err
99+
}
100+
res.sendStatus(204)
101+
}
102+
)
103+
})
104+
105+
106+
}
107+
108+
exports.register = register;

src/cli.js

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ const fs = require('fs');
66
const path = require('path');
77

88
const endpointsFile = 'endpoints.yaml';
9-
const resultFile = 'app.js';
9+
const appFile = 'app.js';
10+
const routesFile = 'routes.js';
1011

1112
const loadConfig = (endpointsFile) => {
1213
console.log('Read', endpointsFile);
@@ -21,6 +22,13 @@ const loadConfig = (endpointsFile) => {
2122
}
2223
};
2324

25+
const createApp = async (destDir, fileName) => {
26+
console.log('Generate', fileName);
27+
const resultFile = path.join(destDir, fileName);
28+
29+
fs.copyFileSync(__dirname + '/templates/app.js', resultFile)
30+
};
31+
2432
// "SELECT *\n FROM foo" => "SELECT * FROM foo"
2533
const flattenQuery = (query) => query.replace(/\n[ ]*/g, ' ');
2634

@@ -46,7 +54,7 @@ const createEndpoints = async (destDir, fileName, config) => {
4654
}
4755

4856
const resultedCode = await ejs.renderFile(
49-
__dirname + '/templates/app.js.ejs',
57+
__dirname + '/templates/routes.js.ejs',
5058
{
5159
"endpoints": config,
5260

@@ -103,8 +111,8 @@ if (!fs.existsSync(destDir)) {
103111
fs.mkdirSync(destDir, {recursive: true});
104112
}
105113

106-
createEndpoints(destDir, resultFile, config);
107-
114+
createApp(destDir, appFile, config);
115+
createEndpoints(destDir, routesFile, config);
108116
createPackageJson(destDir, 'package.json');
109117

110118
console.info(`The application has been generated!

src/templates/app.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const bodyParser = require('body-parser')
2+
const express = require('express')
3+
const mysql = require('mysql')
4+
const routes = require('./routes')
5+
6+
const app = express()
7+
app.use(bodyParser.json())
8+
9+
const pool = mysql.createPool({
10+
connectionLimit: 2,
11+
host: process.env.DB_HOST || 'localhost',
12+
user: process.env.DB_USER,
13+
password: process.env.DB_PASSWORD,
14+
database: process.env.DB_NAME,
15+
// Support of named placeholders (https://github.com/mysqljs/mysql#custom-format)
16+
queryFormat: function(query, values) {
17+
if (!values) {
18+
return query;
19+
}
20+
return query.replace(/\:(\w+)/g, function(txt, key) {
21+
if (values.hasOwnProperty(key)) {
22+
return this.escape(values[key]);
23+
}
24+
return txt;
25+
}.bind(this));
26+
}
27+
})
28+
29+
routes.register(app, pool)
30+
31+
const port = process.env.PORT || 3000;
32+
app.listen(port, () => {
33+
console.log(`Listen on ${port}`)
34+
})

src/templates/app.js.ejs renamed to src/templates/routes.js.ejs

Lines changed: 5 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,4 @@
1-
const bodyParser = require('body-parser')
2-
const express = require('express')
3-
const mysql = require('mysql')
4-
5-
const app = express()
6-
app.use(bodyParser.json())
7-
8-
const pool = mysql.createPool({
9-
connectionLimit: 2,
10-
host: process.env.DB_HOST || 'localhost',
11-
user: process.env.DB_USER,
12-
password: process.env.DB_PASSWORD,
13-
database: process.env.DB_NAME,
14-
// Support of named placeholders (https://github.com/mysqljs/mysql#custom-format)
15-
queryFormat: function(query, values) {
16-
if (!values) {
17-
return query;
18-
}
19-
return query.replace(/\:(\w+)/g, function(txt, key) {
20-
if (values.hasOwnProperty(key)) {
21-
return this.escape(values[key]);
22-
}
23-
return txt;
24-
}.bind(this));
25-
}
26-
})
1+
const register = (app, pool) => {
272

283
<%
294
endpoints.forEach(function(endpoint) {
@@ -103,9 +78,8 @@ app.delete('<%- endpoint.path %>', (req, res) => {
10378
<%
10479
}
10580
});
106-
-%>
81+
%>
10782

108-
const port = process.env.PORT || 3000;
109-
app.listen(port, () => {
110-
console.log(`Listen on ${port}`)
111-
})
83+
}
84+
85+
exports.register = register;

0 commit comments

Comments
 (0)