Skip to content

Commit d96be7d

Browse files
AlexanderAlexander
Alexander
authored and
Alexander
committed
final refactor
1 parent 6ee9e0d commit d96be7d

File tree

10 files changed

+128
-111
lines changed

10 files changed

+128
-111
lines changed

my-server/.gitignore

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
node_modules
2-
logger/combined.log
3-
logger/error.log
2+
logs/

my-server/config.json renamed to my-server/configs/config.json

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
{
22
"appPort": 8000,
3-
"dbName": "credential",
43
"dbConfig": {
54
"mongoUrl": "mongodb://localhost:27017",
65
"dbName": "credential",

my-server/controllers/products.js

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
const path = require("path");
2+
const { ObjectId } = require("mongodb");
3+
const { initConfLog, initMongoDb, codes } = require("server-framework");
4+
5+
const configPath = path.join(__dirname, "configs", "config.json");
6+
7+
const getId = async (req, res) => {
8+
// /products/1, req.params has value { id: '1' }
9+
try {
10+
const { logger, config } = initConfLog(configPath);
11+
const collName = config.get("dbConfig").collName;
12+
13+
const db = await initMongoDb();
14+
15+
const dbResponse = await db
16+
.collection(collName)
17+
.findOne({ _id: new ObjectId(req.params.id) });
18+
logger.info("res", dbResponse);
19+
20+
res.json(dbResponse);
21+
} catch (e) {
22+
console.log(e);
23+
24+
throw codes.INTERNAL_SERVER_ERROR;
25+
}
26+
};
27+
28+
const getAll = (req, res) => {
29+
// /products?page=1&pageSize=10 => { page: '1', pageSize: '10' }
30+
31+
const { logger } = initConfLog(configPath);
32+
const params = JSON.stringify(req.query);
33+
logger.info(params);
34+
res.send(params);
35+
};
36+
37+
const create = async (req, res) => {
38+
const { logger, config } = initConfLog(configPath);
39+
const collName = config.get("dbConfig").collName;
40+
41+
const db = await initMongoDb();
42+
43+
const data = req.body;
44+
logger.info("data", data);
45+
try {
46+
const dbResponse = await db.collection(collName).insertOne(data);
47+
48+
logger.info(`dbResponse insertOne: ${dbResponse.insertedId.toString()}`);
49+
res.send(dbResponse.insertedId.toString());
50+
} catch (e) {
51+
console.log(e);
52+
throw codes.INTERNAL_SERVER_ERROR;
53+
}
54+
};
55+
56+
module.exports = { getId, getAll, create };

my-server/index.js

+15-73
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,29 @@
11
const fs = require("fs");
22
const path = require("path");
3-
const { ObjectId } = require("mongodb");
43

5-
// TODO: fix to npm dependency
4+
const { server, initConfLog, codes } = require("server-framework");
65

7-
const {
8-
server,
9-
initConfLog,
10-
initMongoDb,
11-
codes
12-
} = require("server-framework");
6+
const protectedMiddleware = require("./middlewares/protectedMiddleware");
7+
const productRoutes = require("./routes/products");
8+
const { defaultJsonParser } = require("./utils");
139

14-
15-
const configPath = path.join(__dirname, "config.json");
16-
17-
// path.join(__dirname, "logs", "error.log");
18-
19-
// TODO: https://blog.logrocket.com/organizing-express-js-project-structure-better-productivity/
20-
// https://github.com/geshan/expressjs-structure
21-
22-
const defaultJsonParser = (body) => {
23-
// FST_ERR_CTP_EMPTY_JSON_BODY
24-
25-
body = body ? JSON.parse(body) : {};
26-
return body;
27-
};
10+
const configPath = path.join(__dirname, "configs", "config.json");
11+
const logsFolderPath = path.join(__dirname, "logs");
2812

2913
const start = async () => {
30-
31-
const { logger, config } = initConfLog(configPath);
32-
const dbConfig = config.get("dbConfig");
14+
15+
const { logger, config } = initConfLog(configPath, logsFolderPath);
3316
const appPort = config.get("appPort");
34-
const collName = dbConfig.collName;
35-
const db = await initMongoDb();
36-
const app = server();
3717

18+
const app = server();
3819
app.addContentTypeParser("application/json", defaultJsonParser);
3920

40-
app.get("/products/:id", async (req, res) => {
41-
// /products/1, req.params has value { id: '1' }
42-
try {
43-
const dbResponse = await db
44-
.collection(collName)
45-
.findOne({ _id: new ObjectId(req.params.id) });
46-
logger.info("res", dbResponse);
21+
const router = app.Router;
4722

48-
res.json(dbResponse);
49-
} catch (e) {
50-
console.log(e);
23+
productRoutes(router);
5124

52-
throw codes.INTERNAL_SERVER_ERROR;
53-
}
54-
});
55-
56-
app.get("/products/", (req, res) => {
57-
// /products?page=1&pageSize=10 => { page: '1', pageSize: '10' }
58-
logger.info(req.query);
59-
res.send(JSON.stringify(req.query));
60-
});
61-
62-
app.post("/products/", async (req, res) => {
63-
const data = req.body;
64-
logger.info("data", data);
65-
try {
66-
const dbResponse = await db.collection(collName).insertOne(data);
67-
68-
logger.info(`dbResponse insertOne: ${dbResponse.insertedId.toString()}`);
69-
res.send(dbResponse.insertedId.toString());
70-
} catch (e) {
71-
console.log(e);
72-
throw codes.INTERNAL_SERVER_ERROR;
73-
}
74-
});
75-
76-
app.get("/photos/:file", function (req, res) {
77-
// static
25+
// static
26+
router.get("/photos/:file", function (req, res) {
7827
const file = req.params.file;
7928
const pth = path.join(__dirname, "uploads", file + ".jpeg");
8029

@@ -86,15 +35,8 @@ const start = async () => {
8635
}
8736
});
8837

89-
const protectedMiddleware = (req, res, next) => {
90-
if (req.headers["authorization"] === "a123") {
91-
next();
92-
} else {
93-
throw codes.UNAUTHORIZED;
94-
}
95-
};
96-
97-
app.get("/protected", protectedMiddleware, (req, res) => {
38+
// middleware example
39+
router.get("/protected", protectedMiddleware, (req, res) => {
9840
res.end("protected route");
9941
});
10042

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const { codes } = require("server-framework");
2+
3+
const protectedMiddleware = (req, res, next) => {
4+
if (req.headers["authorization"] === "a123") {
5+
next();
6+
} else {
7+
throw codes.UNAUTHORIZED;
8+
}
9+
};
10+
11+
module.exports = protectedMiddleware;

my-server/routes/products.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const productsController = require("../controllers/products");
2+
3+
function productRoutes(router) {
4+
router.get("/products/:id", productsController.getId);
5+
router.get("/products/", productsController.getAll);
6+
router.post("/products/", productsController.create);
7+
}
8+
9+
10+
module.exports = productRoutes;

my-server/utils/index.js

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const defaultJsonParser = (body) => {
2+
// FST_ERR_CTP_EMPTY_JSON_BODY
3+
4+
body = body ? JSON.parse(body) : {};
5+
return body;
6+
};
7+
8+
module.exports = { defaultJsonParser };

readme.md

+17
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,23 @@ npm i
2121
npm start
2222
```
2323

24+
config file format
25+
```
26+
{
27+
"appPort": 8000, // port server starts
28+
"dbConfig": {
29+
"mongoUrl": "", // mongo connection url
30+
"dbName": "credential", // db name
31+
"collName": "credentials", // collection name
32+
"validatorObj": {} // collection validation object
33+
},
34+
"logger": {
35+
"errorFile": "error.log", // file with error logs
36+
"combinedFile": "combined.log", // other logs
37+
"env": "production" // hardcoded ENV
38+
}
39+
}
40+
```
2441
examples
2542

2643
```

server-framework/ServerGlobal.js

+3-30
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,11 @@ class ServerGlobal {
1010

1111
static _instance;
1212

13-
constructor(configPathname) {
13+
constructor(configPathname, logsFolderPath) {
1414
console.log("path", configPathname);
1515
this._config = nconf.argv().env().file({ file: configPathname });
1616
const { errorFile, combinedFile, env } = this._config.get("logger");
1717

18-
const logsFolderPath = path.join(__dirname, "logs");
19-
2018
if (!fs.existsSync(logsFolderPath)) {
2119
fs.mkdirSync(logsFolderPath, { recursive: true });
2220
}
@@ -73,12 +71,12 @@ class ServerGlobal {
7371
}
7472
}
7573

76-
static getInstance(path) {
74+
static getInstance(path, logsPath) {
7775
if (this._instance) {
7876
return this._instance;
7977
}
8078

81-
this._instance = new ServerGlobal(path);
79+
this._instance = new ServerGlobal(path, logsPath);
8280
return this._instance;
8381
}
8482

@@ -91,30 +89,5 @@ class ServerGlobal {
9189
}
9290
}
9391

94-
// const initLogger = ({ errorPath, combinedPath, env }) => {
95-
// const logger = winston.createLogger({
96-
// level: "info",
97-
// format: winston.format.json(),
98-
// transports: [
99-
// new winston.transports.File({
100-
// filename: errorPath,
101-
// level: "error",
102-
// }),
103-
// new winston.transports.File({
104-
// filename: combinedPath,
105-
// }),
106-
// ],
107-
// });
108-
109-
// if (env !== "production") {
110-
// logger.add(
111-
// new winston.transports.Console({
112-
// format: winston.format.simple(),
113-
// })
114-
// );
115-
// }
116-
117-
// return logger;
118-
// };
11992

12093
module.exports = ServerGlobal;

server-framework/server.js

+7-5
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const { codes } = require("./errors");
1212

1313
const ServerGlobal = require("./ServerGlobal");
1414

15-
const initConfLog = (path) => ServerGlobal.getInstance(path);
15+
const initConfLog = (path, logsPath) => ServerGlobal.getInstance(path, logsPath);
1616
const initMongoDb = () => ServerGlobal.getInstance().initMongo()
1717

1818
function createResponse(res) {
@@ -144,10 +144,12 @@ function customServer() {
144144
};
145145

146146
return {
147-
get: method("get"),
148-
post: method("post"),
149-
put: method("put"),
150-
delete: method("delete"),
147+
Router: {
148+
get: method("get"),
149+
post: method("post"),
150+
put: method("put"),
151+
delete: method("delete"),
152+
},
151153
listen(port, cb) {
152154
server.listen(port, cb);
153155
},

0 commit comments

Comments
 (0)