Skip to content

Commit

Permalink
api workflows up
Browse files Browse the repository at this point in the history
  • Loading branch information
zobkazi committed Apr 23, 2024
1 parent 4b64ca1 commit bb6f0ee
Show file tree
Hide file tree
Showing 12 changed files with 129 additions and 137 deletions.
12 changes: 5 additions & 7 deletions packages/apiGateway/package.json
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
{
"name": "api_gateway",
"version": "1.0.0",
"main": "index.js",
"main": "packages/apiGateway/src/index.ts",
"license": "MIT",
"scripts": {
"dev": "ts-node-dev -r tsconfig-paths/register ./src/index.ts",
"migrate:dev": "prisma migrate dev",
"migrate:prod": "prisma migrate deploy"
"build": "tsc & tsc-alias"
},
"dependencies": {
"@prisma/client": "^5.10.1",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"morgan": "^1.10.0",
"zod": "^3.22.4"
"express-rate-limit": "^7.2.0",
"helmet": "^7.1.0",
"morgan": "^1.10.0"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^20.11.19",
"prisma": "^5.10.1",
"ts-node-dev": "^2.0.0",
"tsc": "^2.0.4",
"tsc-alias": "^1.8.8",
Expand Down
6 changes: 3 additions & 3 deletions packages/apiGateway/src/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
"url": "http://localhost:4000",
"routes": [
{
"path": "/api/users/:id",
"path": "/users/:id",
"methods": ["get"],
"middlewares": []
},
{
"path": "/api/users",
"path": "/user",
"methods": ["post"],
"middlewares": ["auth"]
},
{
"path": "/api/users",
"path": "/users",
"methods": ["get"],
"middlewares": []
}
Expand Down
23 changes: 21 additions & 2 deletions packages/apiGateway/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import helmet from "helmet";
import rateLimit from "express-rate-limit";
import morgan from "morgan";
import error = require("./utils/error");
import { configureRoutes } from "@/utils/apiConfigRoutes";

dotenv.config();

Expand All @@ -11,8 +14,24 @@ app.use(express.json());
app.use(cors());
app.use(morgan("dev"));

app.get("/health", (_req, res) => {
res.status(200).json({ status: "UP" });
// security
app.use(helmet());

// red limit for api middleware

const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minutes
max: 10, // limit each IP to 100 requests per windowMs
handler: (_req, res, _next) => {
res.status(429).json({
success: false,
error: "Too many requests, please try again later.",
});
},
});

app.get("/health", limiter, (_req, res) => {
res.status(200).json({ status: "Api-Gateway is UP" });
});

// routes
Expand Down
20 changes: 20 additions & 0 deletions packages/apiGateway/src/middlewares.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import axios from "axios";
import { Request, Response, NextFunction } from "express";

const auth = async (req: Request, res: Response, next: NextFunction) => {
try {
if (!req.headers.authorization) {
return res.status(401).json({ message: "Unauthorized" });
}

next();
} catch (error) {
next(error);
}
};

const middleware = {
auth,
};

export default middleware;
70 changes: 70 additions & 0 deletions packages/apiGateway/src/utils/apiConfigRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { hostname } from "os";
import { Express, Request, Response } from "express";
import config from "@/config.json";
import axios from "axios";
import middlewares from "@/middlewares";

export const createHandler = (
hostname: string,
path: string,
method: string
) => {
return async (req: Request, res: Response) => {
try {
let url = `${hostname}${path}`;

console.log(url);

req.params &&
Object.keys(req.params).forEach((key) => {
url = url.replace(`:${key}`, req.params[key]);
});

const { data } = await axios({
method,
url,
data: req.body,
headers: {
origin: "http://localhost:8080",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});

res.status(200).json({
success: true,
data,
});
} catch (error) {
console.log(error);
if (error instanceof axios.AxiosError) {
res.status(error.response?.status || 500).json({
success: false,
error: error.response?.data?.message || error.message,
});
}
return res.status(500).json({
success: false,
messages: "Something went wrong",
});
}
};
};

export const getMiddlewares = (names: string[]) => {
return names.map((name) => middlewares[name]);
};

export const configureRoutes = (app: Express) => {
Object.entries(config.services).forEach(([_name, services]) => {
const hostname = services.url;
services.routes.forEach((route) => {
route.methods.forEach((method) => {
const endpoint = `/api${route.path}`;
const middleware = getMiddlewares(route.middlewares);
const handler = createHandler(hostname, route.path, method);
app[method](endpoint, ...middleware, handler);
});
});
});
};

This file was deleted.

This file was deleted.

This file was deleted.

3 changes: 0 additions & 3 deletions packages/services/auth/prisma/migrations/migration_lock.toml

This file was deleted.

This file was deleted.

3 changes: 0 additions & 3 deletions packages/services/user/prisma/migrations/migration_lock.toml

This file was deleted.

10 changes: 10 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1759,6 +1759,11 @@ exponential-backoff@^3.1.1:
resolved "https://registry.yarnpkg.com/exponential-backoff/-/exponential-backoff-3.1.1.tgz#64ac7526fe341ab18a39016cd22c787d01e00bf6"
integrity sha512-dX7e/LHVJ6W3DE1MHWi9S1EYzDESENfLrYohG2G++ovZrYOkm4Knwa0mc1cn84xJOR4KEU0WSchhLbd0UklbHw==

express-rate-limit@^7.2.0:
version "7.2.0"
resolved "https://registry.yarnpkg.com/express-rate-limit/-/express-rate-limit-7.2.0.tgz#06ce387dd5388f429cab8263c514fc07bf90a445"
integrity sha512-T7nul1t4TNyfZMJ7pKRKkdeVJWa2CqB8NA1P8BwYaoDI5QSBZARv5oMS43J7b7I5P+4asjVXjb7ONuwDKucahg==

express@^4.18.2, express@^4.19.2:
version "4.19.2"
resolved "https://registry.yarnpkg.com/express/-/express-4.19.2.tgz#e25437827a3aa7f2a827bc8171bbbb664a356465"
Expand Down Expand Up @@ -2185,6 +2190,11 @@ hasown@^2.0.0:
dependencies:
function-bind "^1.1.2"

helmet@^7.1.0:
version "7.1.0"
resolved "https://registry.yarnpkg.com/helmet/-/helmet-7.1.0.tgz#287279e00f8a3763d5dccbaf1e5ee39b8c3784ca"
integrity sha512-g+HZqgfbpXdCkme/Cd/mZkV0aV3BZZZSugecH03kl38m/Kmdx8jKjBikpDj2cr+Iynv4KpYEviojNdTJActJAg==

hosted-git-info@^2.1.4:
version "2.8.9"
resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9"
Expand Down

0 comments on commit bb6f0ee

Please sign in to comment.