Skip to content

Commit

Permalink
feat: add logs, modifier and throttling stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
sinkaroid committed Apr 18, 2023
1 parent da29c28 commit aade7ca
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/utils/limit-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import rateLimit from "express-rate-limit";
import slowDown from "express-slow-down";

const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 50,
message: "Too nasty, please slow down"
});

const slow = slowDown({
delayAfter: 50,
windowMs: 15 * 60 * 1000,
delayMs: 1000,
maxDelayMs: 20000,
});

export { limiter, slow };
8 changes: 8 additions & 0 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import pino from "pino";

export const logger = pino({
level: "info",
transport: {
target: "pino-pretty"
},
});
39 changes: 39 additions & 0 deletions src/utils/modifier.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Auto space on url
* @param str the string to be spaced
* @returns string
*/
export function spacer(str: string) {
return str.replace(/\s/g, "+");
}

/**
* Error handler
* @param success when success is false, it will return error
* @param message error message
* @returns object
*/
export function maybeError(success: boolean, message: string) {
return { success, message };
}

export function timeAgo(input: Date) {
const date = new Date(input);
const formatter: any = new Intl.RelativeTimeFormat("en");
const ranges: { [key: string]: number } = {
years: 3600 * 24 * 365,
months: 3600 * 24 * 30,
weeks: 3600 * 24 * 7,
days: 3600 * 24,
hours: 3600,
minutes: 60,
seconds: 1
};
const secondsElapsed = (date.getTime() - Date.now()) / 1000;
for (const key in ranges) {
if (ranges[key] < Math.abs(secondsElapsed)) {
const delta = secondsElapsed / ranges[key];
return formatter.format(Math.round(delta), key);
}
}
}

0 comments on commit aade7ca

Please sign in to comment.