Skip to content

feat: allow users to define environment shape with zod #57

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

Closed
wants to merge 1 commit into from
Closed
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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"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.5.8",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

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

1 change: 0 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ export const config = {
token: env.get('DISCORD_TOKEN').required().asString(),
clientId: env.get('DISCORD_CLIENT_ID').required().asString(),
guildId: env.get('DISCORD_GUILD_ID').required().asString(),
coolLinksChannelId: env.get('COOL_LINKS_CHANNEL_ID').required().asString(),
},
redis: {
url: env.get('REDIS_URL').required().asString(),
Expand Down
25 changes: 25 additions & 0 deletions src/core/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { z } from 'zod';

import type { BotModule } from '../types/bot';

export let allEnvSchemas = z.object({});
export const getEnv = () => process.env as z.infer<typeof allEnvSchemas>;

export const loadEnvirontmentVariables = (modules: Record<string, BotModule>): void => {
const modulesEnv = Object.values(modules)
.map((module) => 'env' in module && module.env)
.filter(<T>(env: T): env is Exclude<T, false> => Boolean(env))
.reduce((acc, currentEnv) => {
Object.keys(currentEnv).forEach((key) => {
if (Object.keys(acc).includes(key)) {
throw new Error(`Duplicate environment variable found: ${key}`);
}
});
return { ...acc, ...currentEnv };
});

Object.entries(modulesEnv).forEach(([key, schema]) => {
allEnvSchemas = allEnvSchemas.extend({ [key]: schema });
schema.parse(process.env[key]);
});
};
9 changes: 7 additions & 2 deletions src/modules/coolLinksManagement/coolLinksManagement.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { MessageType, ThreadAutoArchiveDuration } from 'discord.js';
import ogs from 'open-graph-scraper';
import { z } from 'zod';

import { config } from '../../config';
import { getEnv } from '../../core/env';
import { isASocialNetworkUrl } from '../../helpers/regex.helper';
import type { BotModule } from '../../types/bot';
import { getPageSummary } from './summarizeCoolPages';
Expand Down Expand Up @@ -33,12 +34,16 @@ const getThreadNameFromOpenGraph = async (url: string): Promise<string | null> =
const youtubeUrlRegex = new RegExp('^(https?)?(://)?(www.)?(m.)?((youtube.com)|(youtu.be))');

export const coolLinksManagement: BotModule = {
env: {
COOL_LINKS_CHANNEL_ID: z.string().nonempty(),
},
eventHandlers: {
messageCreate: async (message) => {
const env = getEnv();
if (
message.author.bot ||
message.type !== MessageType.Default ||
message.channelId !== config.discord.coolLinksChannelId
message.channelId !== env['COOL_LINKS_CHANNEL_ID']
) {
return;
}
Expand Down
4 changes: 4 additions & 0 deletions src/types/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
ClientEvents,
RESTPostAPIChatInputApplicationCommandsJSONBody,
} from 'discord.js';
import type { ZodTypeAny } from 'zod';

type slashCommandHandler = (
interaction: ChatInputCommandInteraction<'cached' | 'raw'>,
Expand All @@ -18,6 +19,9 @@ export type BotCommand = {
};

export type BotModule = {
env?: {
[key: string]: ZodTypeAny;
};
slashCommands?: Array<BotCommand>;
eventHandlers?: {
[key in keyof ClientEvents]?: EventHandler<key>;
Expand Down