Skip to content

Commit

Permalink
Add semicolons to project
Browse files Browse the repository at this point in the history
  • Loading branch information
QuantGeekDev committed Jan 4, 2024
1 parent 251b3fa commit 98af5f8
Show file tree
Hide file tree
Showing 17 changed files with 148 additions and 148 deletions.
36 changes: 18 additions & 18 deletions src/config/app.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
import { loadEnv } from '../helpers/load-env.js'
import { validateEnv } from '../helpers/validate-env.js'
import { startBot } from './bot.js'
import { connectToDb } from './database.js'
import debugCreator from 'debug'
import { loadEnv } from '../helpers/load-env.js';
import { validateEnv } from '../helpers/validate-env.js';
import { startBot } from './bot.js';
import { connectToDb } from './database.js';
import debugCreator from 'debug';

const debug = debugCreator('app:')
const debug = debugCreator('app:');

export async function startApp() {
debug('Starting app...')
debug('Starting app...');
try {
loadEnv()
validateEnv(['TELEGRAM_TOKEN', 'DB_CONNECTION_STRING'])
loadEnv();
validateEnv(['TELEGRAM_TOKEN', 'DB_CONNECTION_STRING']);
} catch (error) {
console.error('Error occurred while loading environment:', error)
process.exit(1)
console.error('Error occurred while loading environment:', error);
process.exit(1);
}

let database
let database;
try {
database = await connectToDb()
database = await connectToDb();
} catch (error) {
console.error('Error occurred while connecting to the database:', error)
process.exit(2)
console.error('Error occurred while connecting to the database:', error);
process.exit(2);
}

try {
await startBot(database)
await startBot(database);
} catch (error) {
console.error('Error occurred while starting the bot:', error)
process.exit(3)
console.error('Error occurred while starting the bot:', error);
process.exit(3);
}
}
66 changes: 33 additions & 33 deletions src/config/bot.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
import type { I18n } from '@grammyjs/i18n/dist/source/i18n.js'
import { Bot as TelegramBot, session } from 'grammy'
import type { I18n } from '@grammyjs/i18n/dist/source/i18n.js';
import { Bot as TelegramBot, session } from 'grammy';

import { resolvePath } from '../helpers/resolve-path.js'
import { createReplyWithTextFunc } from '../services/context.js'
import type { CustomContext } from '../types/context.js'
import type { Chat, Database } from '../types/database.js'
import { initLocaleEngine } from './locale-engine.js'
import { startController } from '../controllers/start.js'
import { stopController } from '../controllers/stop.js'
import type { Bot } from '../types/telegram.js'
import { buildName, getOrCreatePlayer } from '../services/user.js'
import { getOrCreateChat } from '../services/chat.js'
import { resolvePath } from '../helpers/resolve-path.js';
import { createReplyWithTextFunc } from '../services/context.js';
import type { CustomContext } from '../types/context.js';
import type { Chat, Database } from '../types/database.js';
import { initLocaleEngine } from './locale-engine.js';
import { startController } from '../controllers/start.js';
import { stopController } from '../controllers/stop.js';
import type { Bot } from '../types/telegram.js';
import { buildName, getOrCreatePlayer } from '../services/user.js';
import { getOrCreateChat } from '../services/chat.js';

function extendContext(bot: Bot, database: Database) {
bot.use(async (ctx, next) => {
if (!ctx.chat || !ctx.from) {
return
return;
}

ctx.text = createReplyWithTextFunc(ctx)
ctx.db = database
ctx.text = createReplyWithTextFunc(ctx);
ctx.db = database;

let chat: Chat | null = null
let chat: Chat | null = null;
if (ctx.chat.type !== 'private') {
chat = await getOrCreateChat({
db: database,
chatId: ctx.chat.id,
title: ctx.chat.title
})
});
}

ctx.entities = {
Expand All @@ -37,33 +37,33 @@ function extendContext(bot: Bot, database: Database) {
name: buildName(ctx.from.first_name, ctx.from.last_name)
}),
chat
}
};

await next()
})
await next();
});
}

function setupMiddlewares(bot: Bot, localeEngine: I18n) {
bot.use(session())
bot.use(localeEngine.middleware())
bot.catch(console.error)
bot.use(session());
bot.use(localeEngine.middleware());
bot.catch(console.error);
}

function setupControllers(bot: Bot) {
bot.use(startController)
bot.use(stopController)
bot.use(startController);
bot.use(stopController);
}

export async function startBot(database: Database) {
const localesPath = resolvePath(import.meta.url, '../locales')
const i18n = initLocaleEngine(localesPath)
const bot = new TelegramBot<CustomContext>(process.env.TELEGRAM_TOKEN)
extendContext(bot, database)
setupMiddlewares(bot, i18n)
setupControllers(bot)
const localesPath = resolvePath(import.meta.url, '../locales');
const i18n = initLocaleEngine(localesPath);
const bot = new TelegramBot<CustomContext>(process.env.TELEGRAM_TOKEN);
extendContext(bot, database);
setupMiddlewares(bot, i18n);
setupControllers(bot);

// NOTE: Resolves only when bot is stopped
// so give it a second to start instead of `await`
bot.start()
return new Promise(resolve => setTimeout(resolve, 1_000))
bot.start();
return new Promise(resolve => setTimeout(resolve, 1_000));
}
18 changes: 9 additions & 9 deletions src/config/database.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { MongoClient } from 'mongodb'
import type { Chat, Database, User } from '../types/database.js'
import { MongoClient } from 'mongodb';
import type { Chat, Database, User } from '../types/database.js';

export async function connectToDb() {
const client = new MongoClient(process.env.DB_CONNECTION_STRING)
await client.connect()
const mongoDb = client.db()
const user = mongoDb.collection<User>('user')
const chat = mongoDb.collection<Chat>('chat')
const database: Database = { user, chat }
return database
const client = new MongoClient(process.env.DB_CONNECTION_STRING);
await client.connect();
const mongoDb = client.db();
const user = mongoDb.collection<User>('user');
const chat = mongoDb.collection<Chat>('chat');
const database: Database = { user, chat };
return database;
}
6 changes: 3 additions & 3 deletions src/config/locale-engine.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { I18n } from '@grammyjs/i18n'
import { I18n } from '@grammyjs/i18n';

export function initLocaleEngine(path: string, defaultLanguage = 'en') {
const i18n = new I18n({
directory: path,
defaultLanguage: defaultLanguage,
defaultLanguageOnMissing: true,
useSession: true
})
return i18n
});
return i18n;
}
10 changes: 5 additions & 5 deletions src/controllers/start.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Composer } from 'grammy'
import type { CustomContext } from '../types/context.js'
import { Composer } from 'grammy';
import type { CustomContext } from '../types/context.js';

export const startController = new Composer<CustomContext>()
export const startController = new Composer<CustomContext>();
startController.command('start', async ctx => {
await ctx.text('start', {
name: ctx.entities.user.name,
chatName: ctx.entities.chat?.title ?? 'PM'
})
})
});
});
10 changes: 5 additions & 5 deletions src/controllers/stop.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Composer } from 'grammy'
import type { CustomContext } from '../types/context.js'
import { Composer } from 'grammy';
import type { CustomContext } from '../types/context.js';

export const stopController = new Composer<CustomContext>()
export const stopController = new Composer<CustomContext>();
stopController.command('stop', async ctx => {
await ctx.text('stop', {
name: ctx.entities.user.name,
chatName: ctx.entities.chat?.title ?? 'PM'
})
})
});
});
4 changes: 2 additions & 2 deletions src/environment.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export declare global {
namespace NodeJS {
interface ProcessEnv {
TELEGRAM_TOKEN: string
DB_CONNECTION_STRING: string
TELEGRAM_TOKEN: string;
DB_CONNECTION_STRING: string;
}
}
}
10 changes: 5 additions & 5 deletions src/helpers/load-env.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import dotenv from 'dotenv'
import { resolvePath } from './resolve-path.js'
import dotenv from 'dotenv';
import { resolvePath } from './resolve-path.js';

export function loadEnv(configPath = '../../.env') {
const fullPath = resolvePath(import.meta.url, configPath)
const fullPath = resolvePath(import.meta.url, configPath);
dotenv.config({
path: fullPath,
})
path: fullPath
});
}
10 changes: 5 additions & 5 deletions src/helpers/resolve-path.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import pathModule from 'path'
import { fileURLToPath } from 'url'
import pathModule from 'path';
import { fileURLToPath } from 'url';

export function resolvePath(localPath: string, targetPath: string) {
const __filename = fileURLToPath(localPath)
const __dirname = pathModule.dirname(__filename)
return pathModule.join(__dirname, targetPath)
const __filename = fileURLToPath(localPath);
const __dirname = pathModule.dirname(__filename);
return pathModule.join(__dirname, targetPath);
}
2 changes: 1 addition & 1 deletion src/helpers/validate-env.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export function validateEnv(requiredEnvs: string[]) {
for (const env of requiredEnvs) {
if (process.env[env] === undefined) {
throw new Error(`ERROR: Required variable "${env}" is not specified`)
throw new Error(`ERROR: Required variable "${env}" is not specified`);
}
}
}
12 changes: 6 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { startApp } from './config/app.js'
import debugCreator from 'debug'
import { startApp } from './config/app.js';
import debugCreator from 'debug';

const debug = debugCreator('index:')
const debug = debugCreator('index:');

debug('Starting App')
startApp()
debug('App started')
debug('Starting App');
startApp();
debug('App started');
26 changes: 13 additions & 13 deletions src/services/chat.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
import type { Chat, Database } from '../types/database.js'
import type { Chat, Database } from '../types/database.js';

async function createChat(args: {
db: Database
chatId: number
title: string
db: Database;
chatId: number;
title: string;
}): Promise<Chat> {
const chatObject = {
chatId: args.chatId,
title: args.title
} as Chat
} as Chat;

await args.db.chat.insertOne(chatObject)
await args.db.chat.insertOne(chatObject);

return chatObject
return chatObject;
}

export async function getOrCreateChat(args: {
db: Database
chatId: number
title: string
db: Database;
chatId: number;
title: string;
}): Promise<Chat> {
const chat = await args.db.chat.findOneAndUpdate(
{ chatId: args.chatId },
{ $set: { title: args.title } },
{ returnDocument: 'after' }
)
);

if (chat.ok && chat.value) {
return chat.value
return chat.value;
}

return createChat(args)
return createChat(args);
}
12 changes: 6 additions & 6 deletions src/services/context.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { CustomContext, CustomContextMethods } from '../types/context.js'
import type { CustomContext, CustomContextMethods } from '../types/context.js';

export function createReplyWithTextFunc(
ctx: CustomContext
): CustomContextMethods['text'] {
return (resourceKey, templateData, extra = {}) => {
extra.parse_mode = 'HTML'
extra.disable_web_page_preview = true
const text = ctx.i18n.t(resourceKey, templateData)
return ctx.reply(text, extra)
}
extra.parse_mode = 'HTML';
extra.disable_web_page_preview = true;
const text = ctx.i18n.t(resourceKey, templateData);
return ctx.reply(text, extra);
};
}
Loading

0 comments on commit 98af5f8

Please sign in to comment.