Skip to content

Commit

Permalink
Update README.md, cron.ts, and 14 more files...
Browse files Browse the repository at this point in the history
  • Loading branch information
FinlayDaG33k committed Nov 4, 2021
1 parent 01539d4 commit a817279
Show file tree
Hide file tree
Showing 16 changed files with 1,359 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# deno-lib
Library of (arguably) useful Deno classes
Library of (arguably) useful Deno classes.
Comes with no warranties whatsoever.
172 changes: 172 additions & 0 deletions common/cron.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { Time } from './time.ts';

type JobType = () => void;

enum TIME_PART {
SECOND = 'SECOND',
MINUTE = 'MINUTE',
HOUR = 'HOUR',
DAY_OF_WEEK = 'DAY_OF_WEEK',
DAY_OF_MONTH = 'DAY_OF_MONTH',
MONTH = 'MONTH',
}

const schedules = new Map<string, Array<JobType>>();

let schedulerTimeIntervalID: ReturnType<typeof setInterval> = 0;
let shouldStopRunningScheduler = false;

export const cron = (schedule: string = '', job: JobType) => {
let jobs = schedules.has(schedule)
? [...(schedules.get(schedule) || []), job]
: [job];
schedules.set(schedule, jobs);
};

const isRange = (text: string) => /^\d\d?\-\d\d?$/.test(text);

const getRange = (min: number, max: number) => {
const numRange = [];
let lowerBound = min;
while (lowerBound <= max) {
numRange.push(lowerBound);
lowerBound += 1;
}
return numRange;
};

const { DAY_OF_MONTH, DAY_OF_WEEK, HOUR, MINUTE, MONTH, SECOND } = TIME_PART;

const getTimePart = (date: Date, type: TIME_PART): number =>
({
[SECOND]: date.getSeconds(),
[MINUTE]: date.getMinutes(),
[HOUR]: date.getHours(),
[MONTH]: date.getMonth() + 1,
[DAY_OF_WEEK]: date.getDay(),
[DAY_OF_MONTH]: date.getDate(),
}[type]);

const isMatched = (date: Date, timeFlag: string, type: TIME_PART): boolean => {
const timePart = getTimePart(date, type);

if (timeFlag === '*') {
return true;
} else if (Number(timeFlag) === timePart) {
return true;
} else if (timeFlag.includes('/')) {
const [_, executeAt = '1'] = timeFlag.split('/');
return timePart % Number(executeAt) === 0;
} else if (timeFlag.includes(',')) {
const list = timeFlag.split(',').map((num: string) => parseInt(num));
return list.includes(timePart);
} else if (isRange(timeFlag)) {
const [start, end] = timeFlag.split('-');
const list = getRange(parseInt(start), parseInt(end));
return list.includes(timePart);
}
return false;
};

export const validate = (schedule: string, date: Date = new Time().getTime) => {
// @ts-ignore
const timeObj: Record<TIME_PART, boolean> = {};

const [
dayOfWeek,
month,
dayOfMonth,
hour,
minute,
second = '01',
] = schedule.split(' ').reverse();

const cronValues = {
[SECOND]: second,
[MINUTE]: minute,
[HOUR]: hour,
[MONTH]: month,
[DAY_OF_WEEK]: dayOfWeek,
[DAY_OF_MONTH]: dayOfMonth,
};

for (const key in cronValues) {
timeObj[key as TIME_PART] = isMatched(
date,
cronValues[key as TIME_PART],
key as TIME_PART,
);
}

const didMatch = Object.values(timeObj).every(Boolean);
return {
didMatch,
entries: timeObj,
};
};

const executeJobs = () => {
const date = new Time().getTime;
schedules.forEach((jobs, schedule) => {
if (validate(schedule, date).didMatch) {
jobs.forEach((job) => {
job()
});
}
});
};

const runScheduler = () => {
schedulerTimeIntervalID = setInterval(() => {
if (shouldStopRunningScheduler) {
clearInterval(schedulerTimeIntervalID);
return;
}
executeJobs();
}, 1000);
};

export const everyMinute = (cb: JobType) => {
cron(`1 * * * * *`, cb);
};

export const every15Minute = (cb: JobType) => {
cron(`1 */15 * * * *`, cb);
};

export const hourly = (cb: JobType) => {
cron(`1 0 * * * *`, cb);
};

export const daily = (cb: JobType) => {
cron(`1 0 0 * * *`, cb);
};

export const weekly = (cb: JobType, weekDay: string | number = 1) => {
cron(`1 0 0 * * ${weekDay}`, cb);
};

export const biweekly = (cb: JobType) => {
cron(`1 0 0 */14 * *`, cb);
};

export const monthly = (cb: JobType, dayOfMonth: string | number = 1) => {
cron(`1 0 0 ${dayOfMonth} */1 *`, cb);
};

export const yearly = (cb: JobType) => {
cron(`1 0 0 1 1 *`, cb);
};

export const start = () => {
if (shouldStopRunningScheduler) {
shouldStopRunningScheduler = false;
runScheduler();
}
};

export const stop = () => {
shouldStopRunningScheduler = true;
};

runScheduler();
1 change: 1 addition & 0 deletions common/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { config as env } from "https://deno.land/x/dotenv/mod.ts";
20 changes: 20 additions & 0 deletions common/time.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { time as timets } from "https://denopkg.com/burhanahmeed/time.ts@v2.0.1/mod.ts";
import { format as formatter } from "https://cdn.deno.land/std/versions/0.77.0/raw/datetime/mod.ts";

export class Time {
private time;
public get getTime() { return this.time; }

public constructor(time: string|undefined = undefined) {
this.time = timets(time).tz(Deno.env.get('TZ')!).t;
}

public format(format: string) {
return formatter(this.time, format);
}

public tomorrow() {
this.time.setDate(this.time.getDate() + 1);
return this;
}
}
4 changes: 4 additions & 0 deletions communication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { Database } from "./communication/database.ts";
export { MasterEvent } from "./communication/master-event.ts";
export { Notifications } from "./communication/notifications.ts";
export { ServerStatuses } from "./communication/server-status.ts";
7 changes: 7 additions & 0 deletions interfaces/window.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Websocket } from "../websocket/websocket.ts";

declare global {
interface Window {
websocket: Websocket;
}
}
47 changes: 47 additions & 0 deletions logging/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Time } from "../common/time.ts";

export class Logger {
/**
* Write an info message to the console
*
* @param message The message to write
* @returns void
*/
public static info(message: string): void { console.log(`[${Logger.time()}] INFO > ${message}`); }

/**
* Write a warning message to the console
*
* @param message The message to write
* @returns void
*/
public static warning(message: string): void { console.error(`[${Logger.time()}] WARN > ${message}`); }

/**
* Write an error message to the console
*
* @param message The message to write
* @returns void
*/
public static error(message: string): void { console.error(`[${Logger.time()}] ERROR > ${message}`); }

/**
* Write a debug message to the console
* Only shows up when the "DEBUG" env is set to truthy
*
* @param message The message to write
* @returns void
*/
public static debug(message: string): void {
if(Deno.env.get('DEBUG') == "true") console.log(`[${Logger.time()}] DEBUG > ${message}`);
}

/**
* Return the current time in format.
* eg. 2020/11/28 20:50:30
*
* @private
* @returns string The formatted time
*/
private static time(): string { return new Time().format(`yyyy/MM/dd HH:mm:ss`); }
}
16 changes: 16 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export { cron } from "./common/cron.ts";
export { env } from "./common/env.ts";
export { Time } from "./common/time.ts";

export { Logger } from "./logging/logger.ts";

export { Password } from "./security/password.ts";
export { Random } from "./security/random.ts";

export { Controller } from "./webserver/controller/controller.ts";
export { Router } from "./webserver/routing/router.ts";
export { Webserver } from "./webserver/webserver.ts";
export type { RouteArgs } from "./webserver/routing/router.ts";

export { Websocket } from "./websocket/websocket.ts";
export { Events } from "./websocket/events.ts";
Loading

0 comments on commit a817279

Please sign in to comment.