Skip to content

Commit 2c785b1

Browse files
authored
Merge pull request #3 from Kettailor/codex/deploy-docker-and-run-my-code-4drsgx
Align services with environment configuration
2 parents e6fee46 + c3141a7 commit 2c785b1

File tree

12 files changed

+77
-51
lines changed

12 files changed

+77
-51
lines changed

api-gateway/index.js

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,45 @@ const httpProxy = require("http-proxy");
44
const proxy = httpProxy.createProxyServer();
55
const app = express();
66

7+
const AUTH_SERVICE_HOST = process.env.AUTH_SERVICE_HOST || "auth";
8+
const AUTH_SERVICE_PORT = process.env.AUTH_SERVICE_PORT || "3000";
9+
const PRODUCT_SERVICE_HOST = process.env.PRODUCT_SERVICE_HOST || "product";
10+
const PRODUCT_SERVICE_PORT = process.env.PRODUCT_SERVICE_PORT || "3001";
11+
const ORDER_SERVICE_HOST = process.env.ORDER_SERVICE_HOST || "order";
12+
const ORDER_SERVICE_PORT = process.env.ORDER_SERVICE_PORT || "3002";
13+
14+
const AUTH_SERVICE_URL =
15+
process.env.AUTH_SERVICE_URL || `http://${AUTH_SERVICE_HOST}:${AUTH_SERVICE_PORT}`;
16+
const PRODUCT_SERVICE_URL =
17+
process.env.PRODUCT_SERVICE_URL ||
18+
`http://${PRODUCT_SERVICE_HOST}:${PRODUCT_SERVICE_PORT}`;
19+
const ORDER_SERVICE_URL =
20+
process.env.ORDER_SERVICE_URL || `http://${ORDER_SERVICE_HOST}:${ORDER_SERVICE_PORT}`;
21+
22+
proxy.on("error", (err, req, res) => {
23+
console.error("Proxy error:", err.message);
24+
if (!res.headersSent) {
25+
res.status(502).json({ message: "Service unavailable" });
26+
}
27+
});
28+
729
// Route requests to the auth service
830
app.use("/auth", (req, res) => {
9-
proxy.web(req, res, { target: "http://auth:3000" });
31+
proxy.web(req, res, { target: AUTH_SERVICE_URL });
1032
});
1133

1234
// Route requests to the product service
1335
app.use("/products", (req, res) => {
14-
proxy.web(req, res, { target: "http://product:3001" });
36+
proxy.web(req, res, { target: PRODUCT_SERVICE_URL });
1537
});
1638

1739
// Route requests to the order service
1840
app.use("/orders", (req, res) => {
19-
proxy.web(req, res, { target: "http://order:3002" });
41+
proxy.web(req, res, { target: ORDER_SERVICE_URL });
2042
});
2143

2244
// Start the server
23-
const port = process.env.PORT || 3003;
45+
const port = Number(process.env.PORT) || 3003;
2446
app.listen(port, () => {
2547
console.log(`API Gateway listening on port ${port}`);
2648
});

auth/src/app.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,16 @@ class App {
3434
setRoutes() {
3535
this.app.post("/login", (req, res) => this.authController.login(req, res));
3636
this.app.post("/register", (req, res) => this.authController.register(req, res));
37-
this.app.get("/dashboard", authMiddleware, (req, res) => res.json({ message: "Welcome to dashboard" }));
37+
this.app.get("/dashboard", authMiddleware, (req, res) =>
38+
res.json({ message: "Welcome to dashboard" })
39+
);
3840
}
3941

4042
start() {
41-
this.server = this.app.listen(3000, () => console.log("Server started on port 3000"));
43+
const port = config.port;
44+
this.server = this.app.listen(port, () =>
45+
console.log(`Server started on port ${port}`)
46+
);
4247
}
4348

4449
async stop() {

auth/src/config/index.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
require("dotenv").config();
22

3+
const DEFAULT_PORT = 3000;
4+
const DEFAULT_MONGODB_URI = "mongodb://localhost:27017/auth";
5+
const DEFAULT_JWT_SECRET = "secret";
6+
37
module.exports = {
4-
mongoURI: process.env.MONGODB_AUTH_URI,
5-
jwtSecret: process.env.JWT_SECRET || "secret",
8+
port: Number(process.env.PORT) || DEFAULT_PORT,
9+
mongoURI: process.env.MONGODB_AUTH_URI || DEFAULT_MONGODB_URI,
10+
jwtSecret: process.env.JWT_SECRET || DEFAULT_JWT_SECRET,
611
};

order/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ require("dotenv").config();
22
const App = require("./src/app");
33

44
const app = new App();
5-
app.start();
5+
app.start();

order/src/app.js

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ class App {
2626

2727
async setupOrderConsumer() {
2828
console.log("Connecting to RabbitMQ...");
29-
29+
30+
const delay = config.rabbitMQConnectDelayMs;
3031
setTimeout(async () => {
3132
try {
3233
const connection = await amqp.connect(config.rabbitMQURI);
@@ -38,22 +39,18 @@ class App {
3839
// Consume messages from the order queue on buy
3940
console.log("Consuming ORDER service");
4041
const { products, username, orderId } = JSON.parse(data.content);
41-
42+
4243
const newOrder = new Order({
4344
products,
4445
user: username,
4546
totalPrice: products.reduce((acc, product) => acc + product.price, 0),
4647
});
47-
48-
// Save order to DB
48+
4949
await newOrder.save();
50-
51-
// Send ACK to ORDER service
50+
5251
channel.ack(data);
5352
console.log("Order saved to DB and ACK sent to ORDER queue");
54-
55-
// Send fulfilled order to PRODUCTS service
56-
// Include orderId in the message
53+
5754
const { user, products: savedProducts, totalPrice } = newOrder.toJSON();
5855
channel.sendToQueue(
5956
config.productQueue,
@@ -65,11 +62,9 @@ class App {
6562
} catch (err) {
6663
console.error("Failed to connect to RabbitMQ:", err.message);
6764
}
68-
}, 10000); // add a delay to wait for RabbitMQ to start in docker-compose
65+
}, delay);
6966
}
7067

71-
72-
7368
start() {
7469
this.server = this.app.listen(config.port, () =>
7570
console.log(`Server started on port ${config.port}`)

order/src/config.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,3 @@ module.exports = {
77
productQueue: process.env.RABBITMQ_PRODUCT_QUEUE || "products",
88
port: process.env.PORT || 3002,
99
};
10-

order/src/utils/isAuthenticated.js

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,21 @@
1-
const jwt = require('jsonwebtoken');
2-
require('dotenv').config();
1+
const jwt = require("jsonwebtoken");
2+
const config = require("../config");
33

44
function isAuthenticated(req, res, next) {
5-
// Check for the presence of an authorization header
65
const authHeader = req.headers.authorization;
76
if (!authHeader) {
8-
return res.status(401).json({ message: 'Unauthorized' });
7+
return res.status(401).json({ message: "Unauthorized" });
98
}
109

11-
// Extract the token from the header
12-
const token = authHeader.split(' ')[1];
10+
const token = authHeader.split(" ")[1];
1311

1412
try {
15-
// Verify the token using the JWT library and the secret key
16-
const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
13+
const decodedToken = jwt.verify(token, config.jwtSecret);
1714
req.user = decodedToken;
1815
next();
1916
} catch (err) {
2017
console.error(err);
21-
return res.status(401).json({ message: 'Unauthorized' });
18+
return res.status(401).json({ message: "Unauthorized" });
2219
}
2320
}
2421

product/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ require("dotenv").config();
22
const App = require("./src/app");
33

44
const app = new App();
5-
app.start();
5+
app.start();

product/src/config.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
require("dotenv").config();
22

3+
const DEFAULT_PORT = 3001;
4+
const DEFAULT_MONGO_URI = "mongodb://localhost:27017/products";
5+
const DEFAULT_RABBIT_URI = "amqp://localhost";
6+
const DEFAULT_ORDER_QUEUE = "orders";
7+
const DEFAULT_PRODUCT_QUEUE = "products";
8+
const DEFAULT_JWT_SECRET = "secret";
9+
const DEFAULT_RABBIT_CONNECT_DELAY_MS = 20000;
10+
311
module.exports = {
412
port: process.env.PORT || 3001,
513
mongoURI: process.env.MONGODB_PRODUCT_URI || "mongodb://localhost/products",

product/src/utils/isAuthenticated.js

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
11
const jwt = require("jsonwebtoken");
2-
require("dotenv").config();
2+
const config = require("../config");
33

44
function isAuthenticated(req, res, next) {
5-
// Check for the presence of an authorization header
65
const authHeader = req.headers.authorization;
76
if (!authHeader) {
87
return res.status(401).json({ message: "Unauthorized" });
98
}
109

11-
// Extract the token from the header
1210
const token = authHeader.split(" ")[1];
1311

1412
try {
15-
// Verify the token using the JWT library and the secret key
16-
const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
13+
const decodedToken = jwt.verify(token, config.jwtSecret);
1714
req.user = decodedToken;
1815
next();
1916
} catch (err) {

0 commit comments

Comments
 (0)