Skip to content

Commit

Permalink
delete user statistic codes
Browse files Browse the repository at this point in the history
  • Loading branch information
canbax committed Aug 1, 2023
1 parent f013b7e commit a3fdb72
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 167 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
coverage
.DS_Store
.DS_Store
.env
76 changes: 1 addition & 75 deletions api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import express, {
} from "express";
import { ALL_PLACES } from "../data/geoData";
import { getPlace, findPlace, getTimes } from "../src/calculator";
import { dateToString, isInRange, isValidDate } from "../src/util";
import { readFileSync, writeFile } from "fs";
import { isInRange, isValidDate } from "../src/util";

export const app: Express = express();

Expand All @@ -25,14 +24,8 @@ const allowOriginForAll: RequestHandler = (
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
totalVisits++;
next();
};
const totalVisitCountFile = __dirname + "/total-visit-count.txt";
const userVisitCountFile = __dirname + "/user-visit-count.json";
let totalVisits = readTotalVisitCount();

export const writerTimerID = setInterval(writeTotalVisitCount, 3000);

app.use(allowOriginForAll);
app.use(express.static("public"));
Expand All @@ -46,9 +39,6 @@ app.get("/api/cities", getCitiesOfRegion);
app.get("/api/coordinates", getCoordinateData);
app.get("/api/place", getPlaceData);
app.get("/api/ip", getIPAdress);
app.get("/api/totalVisitCount", getTotalVisitCount);
app.get("/api/saveUserStat", saveUserStat);
app.get("/api/getUserStat", getUserStat);

const PORT = process.env.PORT || 3000;
export const httpServer = app.listen(PORT);
Expand Down Expand Up @@ -166,67 +156,3 @@ function logIPAdress(req: Request, _: Response, next: NextFunction) {
console.log("IP address:", req.headers["x-forwarded-for"]);
next();
}

function getTotalVisitCount(_: Request, res: Response) {
res.send({ totalVisitCount: readTotalVisitCount() });
}

function getUserStat(_: Request, res: Response) {
res.send(JSON.parse(readUserVisitsFile()));
}

function readUserVisitsFile(): string {
return readFileSync(userVisitCountFile, {
encoding: "utf-8",
});
}

function saveUserStat(req: Request, res: Response) {
const country = req.query.country as string;
const region = req.query.region as string;
const city = req.query.city as string;
const dateString = dateToString(new Date());

const json = JSON.parse(readUserVisitsFile());
if (country && region && city) {
if (!json[country]) {
json[country] = {};
}
if (!json[country][region]) {
json[country][region] = {};
}
if (!json[country][region][city]) {
json[country][region][city] = {};
}
if (!json[country][region][city][dateString]) {
json[country][region][city][dateString] = 0;
}
json[country][region][city][dateString] += 1;
writeFile(userVisitCountFile, JSON.stringify(json), function (err) {
if (err) {
res.send({ error: "write file error:" + err });
} else {
res.send({ status: "success" });
}
});
} else {
res.send({ error: "INVALID parameters!" });
}
}

function readTotalVisitCount(): number {
const num = Number(
readFileSync(totalVisitCountFile, {
encoding: "utf-8",
})
);
if (!isNaN(num)) return num;
console.log("CANNOT read total visit counts!");
return 0;
}

export function writeTotalVisitCount() {
writeFile(totalVisitCountFile, totalVisits + "", function (err) {
if (err) return console.log(err);
});
}
92 changes: 1 addition & 91 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import request from "supertest";
import {
app,
httpServer,
writerTimerID,
writeTotalVisitCount,
} from "../api/index";
import { app, httpServer } from "../api/index";
import { ANKARA_PLACE_DATA } from "../data/mockData";
/* eslint-disable @typescript-eslint/no-var-requires */
const fs = require("fs");

describe("API endpoint tests", () => {
jest.mock("fs");
Expand Down Expand Up @@ -188,95 +181,13 @@ describe("API endpoint tests", () => {
expect(res.body).toEqual({ error: "NOT FOUND!" });
});

it("should be able to read total visit counts", async () => {
const url = "/api/totalVisitCount";
const res = await request(app).get(url);
expect(res.body.totalVisitCount).toBeDefined();
const n = Number(res.body.totalVisitCount);
expect(res.statusCode).toEqual(200);
expect(isNaN(n)).toEqual(false);
expect(n > -1).toEqual(true);
});

it("should log message if total visit counts is NaN", async () => {
jest
.spyOn(fs, "readFileSync")
/* eslint-disable */
.mockImplementation((_path, _callback) => {
return "a";
});
const logSpy = jest.spyOn(console, "log");
const url = "/api/totalVisitCount";

const res = await request(app).get(url);
expect(logSpy).toHaveBeenCalledWith("CANNOT read total visit counts!");
expect(res.body.totalVisitCount).toBeDefined();
const n = Number(res.body.totalVisitCount);
expect(res.statusCode).toEqual(200);
expect(isNaN(n)).toEqual(false);
expect(n > -1).toEqual(true);
});

it("should be able to write total visit counts without any error log", async () => {
const logSpy = jest.spyOn(console, "log");
writeTotalVisitCount();
expect(logSpy).toHaveBeenCalledTimes(0);
});

it("should log message if total visit counts is cannot be written", async () => {
jest
.spyOn(fs, "writeFile")
/* eslint-disable @typescript-eslint/no-explicit-any */
.mockImplementation((_path, _data, callback: any) => {
callback("err");
});
const logSpy = jest.spyOn(console, "log");
writeTotalVisitCount();
expect(logSpy).toHaveBeenCalledTimes(1);
});

it("should give error to 'place' request if coordinates are wrong", async () => {
const url = "/api/place?lat=a&lng=g";
const res = await request(app).get(url);
expect(res.body).toEqual({ error: "INVALID coordinates!" });
expect(res.statusCode).toEqual(200);
});

it("should give error to save user statistics if parameters are not given", async () => {
const url = "/api/saveUserStat";
const res = await request(app).get(url);
expect(res.body).toEqual({ error: "INVALID parameters!" });
expect(res.statusCode).toEqual(200);
});

it("should give error to save user statistics if cannot write to a file", async () => {
jest
.spyOn(fs, "writeFile")
/* eslint-disable */
.mockImplementation((_path, _data, callback: any) => {
callback("err");
});

const url = "/api/saveUserStat?country=Turkey&region=Ankara&city=Ankara";
const res = await request(app).get(url);
expect(res.body).toEqual({ error: "write file error:err" });
expect(res.statusCode).toEqual(200);
});

it("should be able to save user statistics successfully", async () => {
const url = "/api/saveUserStat?country=Turkey&region=Ankara&city=Ankara";
const res = await request(app).get(url);
expect(res.body).toEqual({ status: "success" });
expect(res.statusCode).toEqual(200);
});

it("should be able to read user statistics successfully", async () => {
const url = "/api/getUserStat";
const res = await request(app).get(url);
expect(res.body).toBeDefined();
expect(res.statusCode).toEqual(200);
});

it("should be able to find a locale from coordinates", async () => {
const url = "/api/place?lat=39.91986&lng=32.85424";
const res = await request(app).get(url);
Expand All @@ -285,7 +196,6 @@ describe("API endpoint tests", () => {
});

afterAll(() => {
clearInterval(writerTimerID);
httpServer.close();
});
});

1 comment on commit a3fdb72

@vercel
Copy link

@vercel vercel bot commented on a3fdb72 Aug 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

namaz-vakti-api – ./

namaz-vakti-api-git-main-canbax.vercel.app
namaz-vakti-api-canbax.vercel.app
namaz-vakti.vercel.app

Please sign in to comment.