Skip to content

Commit

Permalink
Reorganize a bunch of stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
FinlayDaG33k committed Aug 3, 2023
1 parent dc8306e commit 2a3d3ad
Show file tree
Hide file tree
Showing 25 changed files with 131 additions and 90 deletions.
36 changes: 20 additions & 16 deletions common/cache.ts → core/cache.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { T as TimeString } from "../util/time-string.ts";
import { T as TimeString } from "../utility/time-string.ts";

interface CacheItem {
[key: string]: {
data: unknown;
expires: Date;
expires: Date|null;
}
}

Expand All @@ -12,65 +12,69 @@ export class Cache {

/**
* Add an item to the cache.
*
*
* @param key
* @param value
* @param expiry
* @param expiry Can be set to null for never expiring items
*/
public static set(key: string, value: unknown, expiry = '+1 minute'): void {
public static set(key: string, value: unknown, expiry: string|null = '+1 minute'): void {
let expiresAt = null;
if(expiry) expiresAt = new Date(new Date().getTime() + TimeString`${expiry}`)

Cache._items[key] = {
data: value,
expires: new Date(new Date().getTime() + TimeString`${expiry}`),
expires: expiresAt,
};
}

/**
* Get an item from the cache
*
*
* @param key
*/
public static get(key: string): unknown|null {
// Return null if the item doesn't exist
if(!Cache.exists(key)) return null;

// Return null if the item expired
if(Cache.expired(key)) return null;

// Return the item's data
return Cache._items[key].data;
}

/**
* Check whether an item exists in the cache
*
*
* @param key
*/
public static exists(key: string): boolean {
return key in Cache._items;
}

/**
* Check whether an item has expired
*
*
* @param key
*/
public static expired(key: string): boolean {
// If the item doesn't exist, return true
if(!Cache.exists(key)) return true;

// Check if the expiry date is before our current date
return Cache._items[key].expires < new Date();
if(!Cache._items[key].expires) return false;
return Cache._items[key].expires! < new Date();
}

/**
* Remove an item from the cache
*
*
* @param key
*/
public static remove(key: string): void {
// Return if the item doesn't exist
if(!Cache.exists(key)) return;

// Delete our item
delete Cache._items[key];
}
Expand Down
File renamed without changes.
10 changes: 5 additions & 5 deletions discord/dispatchers/event.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Logger } from "../../logging/logger.ts";
import { folderExists } from "../../util/folder-exists.ts";
import { isTs } from "../../util/is-ts.ts";
import { Inflector } from "../../util/inflector.ts";
import { Folder } from "../../filesystem/folder.ts";
import { File } from "../../filesystem/file.ts";
import { Inflector } from "../../utility/inflector.ts";

interface EventConfig {
name: string;
Expand Down Expand Up @@ -91,7 +91,7 @@ export class EventDispatcher {
Logger.debug(`Loading events from "${dir}"...`);

// Make sure the interactions directory exists
if(!folderExists(dir)) {
if(!await new Folder(dir).exists()) {
Logger.warning(`"${dir}" does not exist, no events to load.`);
return;
}
Expand All @@ -102,7 +102,7 @@ export class EventDispatcher {
// Load all interactions
const promiseQueue: Promise<void>[] = [];
for await(const file of files) {
if(!isTs(file.name)) {
if(new File(`${dir}/${file.name}`).ext() === 'ts') {
Logger.debug(`File "${file.name}" is not a TS file, skipping...`);
continue;
}
Expand Down
22 changes: 11 additions & 11 deletions discord/dispatchers/interaction.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {ApplicationCommandOption, ApplicationCommandTypes} from "https://deno.land/x/[email protected]/mod.ts";
import { Discord } from "../discord.ts";
import { Logger } from "../../logging/logger.ts";
import { isTs } from "../../util/is-ts.ts";
import { folderExists } from "../../util/folder-exists.ts";
import { Inflector } from "../../util/inflector.ts";
import { File } from "../../filesystem/file.ts";
import { Folder } from "../../filesystem/folder.ts";
import { Inflector } from "../../utility/inflector.ts";

export interface InteractionConfig {
name: string;
Expand All @@ -14,6 +14,7 @@ export interface InteractionConfig {
}

export class InteractionDispatcher {
private static _interactionsDir = `${Deno.cwd()}/src/interactions`;
private static list: InteractionConfig[] = [];
private static handlers: any = {};

Expand Down Expand Up @@ -57,7 +58,7 @@ export class InteractionDispatcher {
public static async add(interaction: InteractionConfig): Promise<void> {
try {
// Import the interaction handler
InteractionDispatcher.handlers[interaction.handler] = await import(`file://${Deno.cwd()}/src/interactions/${interaction.handler}.ts`)
InteractionDispatcher.handlers[interaction.handler] = await import(`file://${InteractionDispatcher._interactionsDir}/${interaction.handler}.ts`)
} catch(e) {
Logger.error(`Could not register interaction handler for "${interaction}": ${e.message}`);
return;
Expand Down Expand Up @@ -98,29 +99,28 @@ export class InteractionDispatcher {
*/
public static async load(): Promise<void> {
// Create our directory string
const dir = `${Deno.cwd()}/src/interactions`;
Logger.debug(`Loading interactions from "${dir}"...`);
Logger.debug(`Loading interactions from "${InteractionDispatcher._interactionsDir}"...`);

// Make sure the interactions directory exists
if(!folderExists(dir)) {
Logger.warning(`"${dir}" does not exist, no interactions to load`);
if(!await new Folder(InteractionDispatcher._interactionsDir).exists()) {
Logger.warning(`"${InteractionDispatcher._interactionsDir}" does not exist, no interactions to load`);
return;
}

// Get a list of all files
const files = await Deno.readDir(dir);
const files = await Deno.readDir(InteractionDispatcher._interactionsDir);

// Load all interactions
const promiseQueue: Promise<void>[] = [];
for await(const file of files) {
if(!isTs(file.name)) {
if(new File(`${InteractionDispatcher._interactionsDir}/${file.name}`).ext() === 'ts') {
Logger.debug(`File "${file.name}" is not a TS file, skipping...`);
continue;
}

// Import each file as a module
Logger.debug(`Loading "${file.name}"...`);
const module = await import(`file:///${dir}/${file.name}`);
const module = await import(`file:///${InteractionDispatcher._interactionsDir}/${file.name}`);

// Make sure module has a "config" exposed
if(!('config' in module)) {
Expand Down
30 changes: 30 additions & 0 deletions filesystem/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export class File {
public constructor(
private readonly path: string
) {
}

public async create(): Promise<void> {
await Deno.create(this.path);
}

public async exists(): Promise<boolean> {
try {
const target = await Deno.stat(this.path);
return target.isFile;
} catch(e) {
if(e instanceof Deno.errors.NotFound) return false;
throw e;
}
}

public async delete(): Promise<void> {
await Deno.remove(this.path);
}

public ext(): string {
const pos = this.path.lastIndexOf(".");
if(pos < 1) return '';
return this.path.slice(pos + 1);
}
}
16 changes: 16 additions & 0 deletions filesystem/folder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export class Folder {
public constructor(
private readonly path: string
) {
}

public async exists(): Promise<boolean> {
try {
const target = await Deno.stat(this.path);
return target.isDirectory;
} catch(e) {
if(e instanceof Deno.errors.NotFound) return false;
throw e;
}
}
}
4 changes: 2 additions & 2 deletions logging/logger.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Time } from "../common/time.ts";
import { Configure } from "../common/configure.ts";
import { Time } from "../utility/time.ts";
import { Configure } from "../core/configure.ts";
import { cyan, yellow, red, magenta, bold } from "https://deno.land/[email protected]/fmt/colors.ts";

export class Logger {
Expand Down
2 changes: 1 addition & 1 deletion tests/common/configure.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
import { Configure } from "../../common/configure.ts";
import { Configure } from "../../core/configure.ts";

Deno.test("Configure Test", async (t) => {
// Add a test variable and test against it
Expand Down
2 changes: 1 addition & 1 deletion tests/util/inflector.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Inflector } from "../../util/inflector.ts";
import { Inflector } from "../../utility/inflector.ts";
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";

Deno.test("Inflector Test", async (t) => {
Expand Down
9 changes: 0 additions & 9 deletions util/folder-exists.ts

This file was deleted.

5 changes: 0 additions & 5 deletions util/is-ts.ts

This file was deleted.

10 changes: 0 additions & 10 deletions util/tokenizer.ts

This file was deleted.

16 changes: 3 additions & 13 deletions util/check-source.ts → utility/check-source.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Logger } from "../logging/logger.ts";
import { File } from "../filesystem/file.ts";

export interface ExclusionConfig {
directories?: string[];
Expand All @@ -18,7 +19,7 @@ export class CheckSource {
// Get list of files
await this.getFiles(this.path);

// Checkk all files found
// Check all files found
Logger.info(`Checking "${this.files.length}" files...`);
await this.checkFiles();

Expand Down Expand Up @@ -53,7 +54,7 @@ export class CheckSource {
Logger.debug(`Skipping excluded file "${path}/${entry.name}"...`);
continue;
}
if(!this.isTs(entry.name)) {
if(new File(`${path}/${entry.name}`).ext() !== 'ts') {
Logger.debug(`Skipping non-ts file...`);
continue;
}
Expand Down Expand Up @@ -86,15 +87,4 @@ export class CheckSource {
}
}
}

/**
* Checks whether the file is a ".ts" file
*
* @returns boolean
*/
private isTs(name: string): boolean {
const pos = name.lastIndexOf(".");
if(pos < 1) return false;
return name.slice(pos + 1) === 'ts';
}
}
File renamed without changes.
10 changes: 5 additions & 5 deletions util/inflector.ts → utility/inflector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class Inflector {

/**
* Return input string with first character lowercased.
*
*
* @param input
*/
public static lcfirst(input: string): string {
Expand All @@ -23,7 +23,7 @@ export class Inflector {

/**
* Turn a string into PascalCase.
*
*
* @param input
*/
public static pascalize(input: string, delimiter: string = '_'): string {
Expand All @@ -35,20 +35,20 @@ export class Inflector {
/**
* Return the input lower_case_delimited_string as "A Human Readable String".
* (Underscores are replaced by spaces and capitalized following words.)
*
*
* @param input
* @param delimiter
*/
public static humanize(input: string, delimiter: string = '_'): string {
// Split our string into tokens
const tokens: string[] = input
.split(delimiter);

// Uppercase each of the tokens
for(let i = 0; i < tokens.length; i++) {
tokens[i] = Inflector.ucfirst(tokens[i]);
}

// Join tokens into a string and return
return tokens.join(' ');
}
Expand Down
2 changes: 1 addition & 1 deletion util/raise.ts → utility/raise.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* Utility function that literally just throws an error
*
*
* @param err
*/
export function raise(err: string): never {
Expand Down
Loading

0 comments on commit 2a3d3ad

Please sign in to comment.