Skip to content

Commit

Permalink
Changed api build
Browse files Browse the repository at this point in the history
  • Loading branch information
Tangerie committed Sep 17, 2022
1 parent 72c2801 commit a55025a
Show file tree
Hide file tree
Showing 11 changed files with 96 additions and 27 deletions.
6 changes: 6 additions & 0 deletions api/@types/express/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare namespace Express {
export interface Request {
tracking : string;
redis : ReturnType<typeof import("redis").createClient>
}
}
2 changes: 2 additions & 0 deletions api/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ RUN npm ci

COPY . .

RUN npm run build

EXPOSE 8080

ENTRYPOINT ["npm", "start"]
4 changes: 3 additions & 1 deletion api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
"name": "portfolio-api",
"version": "0.0.1",
"description": "",
"main": "dist/index.js",
"scripts": {
"start": "node -r ts-node/register src/index.ts",
"start": "node .",
"build": "tsc",
"dev": "nodemon src/index.ts",
"clean": "rimraf dist"
},
Expand Down
12 changes: 10 additions & 2 deletions api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
import express from "express";

import dotenv from 'dotenv';
import analytics from "./routes/analytics";
import analytics, { AnalyticsMiddleware } from "./routes/analytics";

import cookieMiddleware from "cookie-parser";
import { DatabaseMiddleware } from "./modules/database";

dotenv.config();

const app = express();

app.use(cookieMiddleware(process.env.COOKIE_SECRET || "cookie_secret"))
app.use(express.json({

}));

app.use(cookieMiddleware(process.env.COOKIE_SECRET || "cookie_secret"));

app.use(DatabaseMiddleware);

app.use(AnalyticsMiddleware);

const port = process.env.PORT || 8080;

Expand Down
14 changes: 13 additions & 1 deletion api/src/modules/database/database.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RedisClientType } from "@redis/client";
import { Request, Response, NextFunction } from "express";
import { createClient } from "redis";

export async function CreateDatabase() {
Expand All @@ -10,3 +10,15 @@ export async function CreateDatabase() {

return client;
}

export async function DatabaseMiddleware(req : Request, res : Response, next : NextFunction) {
const client = await CreateDatabase();

req.redis = client;

req.on("finish", () => {
client.quit();
});

next();
}
7 changes: 6 additions & 1 deletion api/src/routes/analytics/analytics.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Router } from "express";
import { getTrackingData } from "./util";
import { getTrackingData, logRequest } from "./util";

export const router = Router();

Expand All @@ -10,3 +10,8 @@ router.get("/", async (req, res) => {

res.json(userData);
});

router.post("/log", async (req, res) => {
await logRequest(req, res, req.body);
res.json({});
});
3 changes: 2 additions & 1 deletion api/src/routes/analytics/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { router as default } from "./analytics";
export { router as default } from "./analytics";
export { AnalyticsMiddleware } from "./middleware";
32 changes: 32 additions & 0 deletions api/src/routes/analytics/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { randomBytes } from "crypto";
import { NextFunction, Request, Response } from "express";
import { CreateDatabase } from "../../modules/database";
import { TrackingInstance } from "./types";

export async function AnalyticsMiddleware(req : Request, res : Response, next : NextFunction) {
req.tracking = await getCookie(req, res);
next();
}

async function createTrackingInstance(req : Request, cookie : string) {
const data : TrackingInstance = {
id: cookie,
visits: []
}

await req.redis.json.set(`tracking:${cookie}`, ".", data as any);
}

async function getCookie(req : Request, res : Response) {
let cookie = req.signedCookies["tracker"];
if(!cookie) {
cookie = randomBytes(20).toString("hex");
res.cookie("tracker", cookie, {
signed: true
});

await createTrackingInstance(req, cookie);
}

return cookie as string;
}
10 changes: 10 additions & 0 deletions api/src/routes/analytics/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export interface TrackingInstance {
id : string;
visits : TrackingVisit[];
}

export interface TrackingVisit {
ts : number;
route : string;
data : any;
}
25 changes: 6 additions & 19 deletions api/src/routes/analytics/util.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,15 @@
import { randomBytes } from "crypto";
import { Request, Response } from "express";
import { CreateDatabase } from "../../modules/database";
import { TrackingInstance, TrackingVisit } from "./types";

export async function getTrackingData(req : Request, res : Response) {
const db = await CreateDatabase();

const cookie = getCookie(req, res);



const data = await db.json.get(`tracker:${cookie}`);

const data = await req.redis.json.get(`tracking:${req.tracking}`);

return data;
}

function getCookie(req : Request, res : Response) {
let cookie = req.signedCookies["tracker"];
if(!cookie) {
cookie = randomBytes(20).toString("hex");
res.cookie("tracker", cookie, {
signed: true
})
}
export async function logRequest(req : Request, res : Response, visit : TrackingVisit) {
visit.ts = Date.now();
await req.redis.json.arrAppend(`tracking:${req.tracking}`, ".visits", visit as any);
}

return cookie as string;
}
8 changes: 6 additions & 2 deletions api/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
"typeRoots": [
"@types",
"./node_modules/@types"
], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
Expand Down Expand Up @@ -93,6 +96,7 @@
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": [
"src/**/*"
"src/**/*",
"@types/**/*"
]
}

0 comments on commit a55025a

Please sign in to comment.