Skip to content

feat: make modules isolated using creation function #81

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Sep 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ DISCORD_TOKEN=
REDIS_URL=

# CHANNELS
COOL_LINKS_CHANNEL_ID=
COOL_LINKS_MANAGEMENT_CHANNEL_ID=
COOL_LINKS_MANAGEMENT_PAGE_SUMMARIZER_BASE_URL=

# API
PAGE_SUMMARIZER_BASE_URL=
PATTERN_REPLACE_EXCLUDED_CHANNEL_ID=
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@
"dependencies": {
"@keyv/redis": "2.7.0",
"cheerio": "1.0.0-rc.12",
"constant-case": "3.0.4",
"cron": "2.4.3",
"discord.js": "14.13.0",
"env-var": "7.4.1",
"keyv": "4.5.3",
"open-graph-scraper": "6.2.2",
"param-case": "3.0.4"
"param-case": "3.0.4",
"zod": "3.22.2"
},
"devDependencies": {
"@types/node": "20.6.2",
Expand Down
38 changes: 27 additions & 11 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 0 additions & 15 deletions src/__tests__/mocks/config.mock.ts

This file was deleted.

4 changes: 0 additions & 4 deletions src/__tests__/summarize-cool-pages.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,6 @@ type SummarizeCoolPagesFixture = ReturnType<typeof createSummarizeCoolPagesFixtu
describe('Feature: summarize cool pages', () => {
let fixture: SummarizeCoolPagesFixture;
beforeEach(() => {
// config is mocked to avoid to call the third party API and to avoid to handle env-var
vi.mock('../config', async () => ({
config: (await import('./mocks/config.mock')).default,
}));
// useless atm but will be useful when we will have to reset the fixture
fixture = createSummarizeCoolPagesFixture();
});
Expand Down
14 changes: 0 additions & 14 deletions src/config.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/core/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import '@keyv/redis';

import Keyv from 'keyv';

import { config } from '../config';
import type { Frequency } from '../modules/recurringMessage/recurringMessage.helpers';
import { env } from './env';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
interface CacheGet<Entries extends Record<string, any>> {
Expand All @@ -28,7 +28,7 @@ interface CacheEntries {
}

class CacheImpl implements Cache<CacheEntries> {
private readonly backend = new Keyv(config.redis.url);
private readonly backend = new Keyv(env.redisUrl);

public get<Key extends keyof CacheEntries>(key: Key): Promise<CacheEntries[Key] | undefined>;
public get<Key extends keyof CacheEntries>(
Expand Down
34 changes: 34 additions & 0 deletions src/core/createEnvForModule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { constantCase } from 'constant-case';

import type { CreatedModule, ModuleFactory } from './createModule';

const createEnvForModule = (constantName: string) =>
Object.entries(process.env)
.filter(([key]) => key.startsWith(constantName))
.reduce<Record<string, string>>((acc, [key, value]) => {
const envKey = key.replace(`${constantName}_`, '');

if (value === undefined) {
return acc;
}

acc[envKey] = value;

return acc;
}, {});

export const createAllModules = async (
modules: Record<string, ModuleFactory>,
): Promise<CreatedModule[]> => {
const createdModules: CreatedModule[] = [];

for (const [name, factory] of Object.entries(modules)) {
const moduleConstantName = constantCase(name);
const moduleEnv = createEnvForModule(moduleConstantName);
const module = await factory({ env: moduleEnv });

createdModules.push(module);
}

return createdModules;
};
58 changes: 58 additions & 0 deletions src/core/createModule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { ClientEvents, ClientOptions } from 'discord.js';
import type { ZodTypeAny } from 'zod';
import { z } from 'zod';

import type { BotCommand, EventHandler } from '../types/bot';

type InferredZodShape<Shape extends Record<string, ZodTypeAny>> = {
[K in keyof Shape]: Shape[K]['_type'];
};

interface Context<Env extends Record<string, ZodTypeAny>> {
env: InferredZodShape<Env>;
}

type ModuleFunction<Env extends Record<string, ZodTypeAny>, ReturnType> = (
context: Context<Env>,
) => ReturnType;

type EventHandlers = {
[K in keyof ClientEvents]?: EventHandler<K>;
};

type BotModule<Env extends Record<string, ZodTypeAny>> = {
env?: Env;
intents?: ClientOptions['intents'];
slashCommands?: ModuleFunction<Env, Array<BotCommand>>;
eventHandlers?: ModuleFunction<Env, EventHandlers>;
};

interface CreatedModuleInput {
env: unknown;
}

export interface CreatedModule {
intents: ClientOptions['intents'];
slashCommands: Array<BotCommand>;
eventHandlers: EventHandlers;
}

export type ModuleFactory = (input: CreatedModuleInput) => Promise<CreatedModule>;

export const createModule = <Env extends Record<string, ZodTypeAny>>(
module: BotModule<Env>,
): ModuleFactory => {
return async (input) => {
const env = await z.object(module.env ?? ({} as Env)).parseAsync(input.env);

const context = {
env,
};

return {
intents: module.intents ?? [],
slashCommands: module.slashCommands?.(context) ?? [],
eventHandlers: module.eventHandlers?.(context) ?? {},
};
};
};
13 changes: 13 additions & 0 deletions src/core/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { z } from 'zod';

const envShape = z
.object({
DISCORD_TOKEN: z.string().nonempty(),
REDIS_URL: z.string().url(),
})
.transform((object) => ({
discordToken: object.DISCORD_TOKEN,
redisUrl: object.REDIS_URL,
}));

export const env = envShape.parse(process.env);
6 changes: 3 additions & 3 deletions src/core/getIntentsFromModules.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { BotModule } from '../types/bot';
import type { CreatedModule } from './createModule';

export const getIntentsFromModules = (modules: Record<string, BotModule>) => {
const intents = Object.values(modules).flatMap((module) => module.intents ?? []);
export const getIntentsFromModules = (modules: CreatedModule[]) => {
const intents = modules.flatMap((module) => module.intents ?? []);
return [...new Set(intents)] as const;
};
24 changes: 15 additions & 9 deletions src/core/loadModules.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { type Client } from 'discord.js';

import type { BotModule } from '../types/bot';
import { checkUniqueSlashCommandNames } from './checkUniqueSlashCommandNames';
import type { CreatedModule } from './createModule';
import { env } from './env';
import { pushCommands, routeCommands } from './loaderCommands';
import { routeHandlers } from './routeHandlers';

export const loadModules = async (
client: Client<true>,
modulesToLoad: Record<string, BotModule>,
modules: CreatedModule[],
): Promise<void> => {
const botCommands = Object.values(modulesToLoad).flatMap((module) => module.slashCommands ?? []);
await Promise.allSettled(modules.map((module) => module.eventHandlers?.ready?.(client)));

const botCommands = modules.flatMap((module) => module.slashCommands ?? []);

checkUniqueSlashCommandNames(botCommands);
routeCommands(client, botCommands);

Expand All @@ -19,11 +23,13 @@ export const loadModules = async (
const { guilds } = client;

for (const guild of guilds.cache.values()) {
await pushCommands(
botCommands.map((command) => command.schema),
clientId,
guild.id,
);
await pushCommands({
commands: botCommands.map((command) => command.schema),
clientId: clientId,
guildId: guild.id,
discordToken: env.discordToken,
});
}
routeHandlers(client, modulesToLoad);

routeHandlers(client, modules);
};
21 changes: 13 additions & 8 deletions src/core/loaderCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,23 @@ import {
Routes,
} from 'discord.js';

import { config } from '../config';
import type { BotCommand } from '../types/bot';
import { deleteExistingCommands } from './deleteExistingCommands';

const { discord } = config;
interface PushCommandsOptions {
commands: RESTPostAPIChatInputApplicationCommandsJSONBody[];
clientId: string;
guildId: string;
discordToken: string;
}

export const pushCommands = async (
commands: RESTPostAPIChatInputApplicationCommandsJSONBody[],
clientId: string,
guildId: string,
) => {
const rest = new REST({ version: '10' }).setToken(discord.token);
export const pushCommands = async ({
commands,
clientId,
guildId,
discordToken,
}: PushCommandsOptions) => {
const rest = new REST({ version: '10' }).setToken(discordToken);
await deleteExistingCommands(rest, clientId, guildId);
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: commands,
Expand Down
Loading