Skip to content

Commit

Permalink
Merge pull request #89 from danbilokha/feature/dbilokha/code-quality
Browse files Browse the repository at this point in the history
code quality
  • Loading branch information
danbilokha committed Apr 21, 2020
2 parents 10caa38 + 4b79cce commit d3abb1b
Show file tree
Hide file tree
Showing 50 changed files with 693 additions and 374 deletions.
1 change: 1 addition & 0 deletions server/src/bots/telegram/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
## Usage

We use <a href='https://github.com/yagop/node-telegram-bot-api'>Node Telegram bot api</a> for Telegram.
Here you can find <a href='https://github.com/yagop/node-telegram-bot-api/blob/release/doc/api.md'>API</a>.
12 changes: 7 additions & 5 deletions server/src/bots/telegram/botResponse/countryResponse.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { adaptCountryToSystemRepresentation } from '../../../services/domain/covid19';
import {
getCountryIKActionMessage,
getCountryMessage,
Expand All @@ -16,7 +15,10 @@ import { catchAsyncError } from '../../../utils/catchError';
import { logger } from '../../../utils/logger';
import { Country } from '../../../models/country.models';
import { CountrySituationInfo } from '../../../models/covid19.models';
import { getRequestedCountry } from '../../../services/domain/countries';
import {
getCountryNameFormat,
getRequestedCountry,
} from '../../../services/domain/countries';
import { LogCategory } from '../../../models/constants';

export const showCountryByNameStrategyResponse: CallBackQueryHandlerWithCommandArgument = async (
Expand All @@ -33,7 +35,7 @@ export const showCountryByNameStrategyResponse: CallBackQueryHandlerWithCommandA
bot,
message,
chatId,
adaptCountryToSystemRepresentation(commandParameter)
getCountryNameFormat(commandParameter)
);
};

Expand All @@ -52,7 +54,7 @@ export const showCountryByFlag: CallBackQueryHandlerWithCommandArgument = async
// MessageRegistry.registerMessageHandler this._bot.onText(
// Regexp works not as we expect it to work
// Theoretically should be fixed with https://github.com/danbilokha/covid19liveupdates/issues/49
!adaptCountryToSystemRepresentation(name(countryFlag))
!getCountryNameFormat(name(countryFlag))
) {
return bot.sendMessage(chatId, getUserInputWithoutCountryNameMessage());
}
Expand All @@ -61,7 +63,7 @@ export const showCountryByFlag: CallBackQueryHandlerWithCommandArgument = async
bot,
message,
chatId,
adaptCountryToSystemRepresentation(name(countryFlag))
getCountryNameFormat(name(countryFlag))
);
};

Expand Down
6 changes: 4 additions & 2 deletions server/src/bots/telegram/botResponse/noResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ export const noResponse = async (
chatId: number
): Promise<TelegramBot.Message> => {
// TODO: log with another severity type
logger.log(
logger.error(
'error',
`We have no response for user ${chatId} for ${message.text} ... plak.. plak..`,
new Error(
`We have no response for a user ${chatId} for ${message.text}.`
),
LogCategory.NoSuitableResponseToUser,
chatId
);
Expand Down
10 changes: 4 additions & 6 deletions server/src/bots/telegram/botResponse/startResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ import { getHelpProposalInlineKeyboard } from '../services/keyboard';
import { greetUser } from '../../../messages/userMessage';
import { CallBackQueryHandlerWithCommandArgument } from '../models';
import * as TelegramBot from 'node-telegram-bot-api';
import {
getTelegramUser,
addTelegramUser,
} from '../../telegram/services/storage';
import { logger } from '../../../utils/logger';
import { LogCategory } from '../../../models/constants';
import { catchAsyncError } from '../../../utils/catchError';
import { addTelegramUser, getTelegramUser } from '../services/storage';

export const startResponse: CallBackQueryHandlerWithCommandArgument = async (
bot: TelegramBot,
Expand Down Expand Up @@ -43,7 +40,7 @@ export const startResponse: CallBackQueryHandlerWithCommandArgument = async (
const [err, result] = await catchAsyncError(addTelegramUser(newUser));
if (err) {
logger.error(
`An error ocured while trying to add new user ${chatId}`,
`An error occurred while trying to add new user ${chatId}`,
err,
LogCategory.Command,
chatId
Expand All @@ -56,6 +53,7 @@ export const startResponse: CallBackQueryHandlerWithCommandArgument = async (
chatId
);
}
return messageSentPromise;
}

return messageSentPromise;
};
3 changes: 2 additions & 1 deletion server/src/bots/telegram/botResponse/trendResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export const trendsByCountryResponse: CallBackQueryHandlerWithCommandArgument =
if (err) {
logger.error(
`Error ocured while trying to get requested country ${requestedCountry}`,
err);
err
);

return bot.sendMessage(chatId, err.message);
}
Expand Down
3 changes: 1 addition & 2 deletions server/src/bots/telegram/botResponse/unsubscribeResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { noSubscriptionsResponseMessage } from '../../../messages/feature/subscr
import { getTelegramActiveUserSubscriptions } from '../services/storage';
import * as TelegramBot from 'node-telegram-bot-api';
import { CallBackQueryHandlerWithCommandArgument } from '../models';
import { adaptCountryToSystemRepresentation } from '../../../services/domain/covid19';

export const buildUnsubscribeInlineResponse = async (
bot: TelegramBot,
Expand Down Expand Up @@ -60,7 +59,7 @@ export const unsubscribeStrategyResponse: CallBackQueryHandlerWithCommandArgumen

return bot.sendMessage(
chatId,
unsubscribeResultMessage(adaptCountryToSystemRepresentation(result)),
unsubscribeResultMessage(result),
getFullMenuKeyboard(chatId)
);
};
2 changes: 1 addition & 1 deletion server/src/bots/telegram/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import {
subscriptionManagerResponse,
} from './botResponse/subscribeResponse';
import { SubscriptionType } from '../../models/subscription.models';
import { MessageHandlerRegistry } from './services/messageHandlerRegistry';
import { MessageHandlerRegistry } from './services/registry/messageHandlerRegistry';
import { subscriptionNotifierHandler } from './services/subscriptionNotifierManager';
import { unsubscribeStrategyResponse } from './botResponse/unsubscribeResponse';
import { trendsByCountryResponse } from './botResponse/trendResponse';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { getParameterAfterCommandFromMessage } from './getParameterAfterCommandFromMessage';
import {
Continents,
CustomSubscriptions,
UserMessages,
UserRegExps,
} from '../../../../models/constants';

const singleParameterAfterCommandMock = [
...Object.keys(UserMessages).filter(
(key) => !isNaN(Number(UserMessages[key]))
),
...Object.keys(Continents).filter((key) => !isNaN(Number(Continents[key]))),
...Object.keys(CustomSubscriptions).filter(
(key) => !isNaN(Number(CustomSubscriptions[key]))
),
// Add countries by flag checkout
];

const singleParameterAfterCommandBulkMock = [
...Object.keys(UserRegExps).map((v) => [UserRegExps[v]]),
...Object.keys(Continents).map((v) => [Continents[v]]),
];

describe('getParameterAfterCommandFromMessage', () => {
it('should return undefined if unsupported command', () => {
const expectation = getParameterAfterCommandFromMessage(
singleParameterAfterCommandMock,
'/CommandDoesnotExist'
);

expect(expectation).toBeUndefined();
});

it('should return undefined if no arguments', () => {
const expectation = getParameterAfterCommandFromMessage(
singleParameterAfterCommandMock,
'/country'
);

expect(expectation).toBeUndefined();
});

it('should return Ukraine', () => {
const expectation = getParameterAfterCommandFromMessage(
singleParameterAfterCommandMock,
'/country Ukraine'
);

expect(expectation).toBe('Ukraine');
});

test.each(singleParameterAfterCommandBulkMock)(
'.singleParameterAfterCommandBulkMock(%s)',
(command) => {
const expectation = getParameterAfterCommandFromMessage(
singleParameterAfterCommandMock,
`${command} PARAMETER`
);

expect(expectation).toBe('PARAMETER');
}
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Check out how it works here
* https://codepen.io/belokha/pen/xxwOdWg?editors=0012
*/
export function getParameterAfterCommandFromMessage(
singleParameterAfterCommands: Array<string>,
userFullInput: string | undefined
): string | undefined {
const makeMagicOverUserFullInput: string = singleParameterAfterCommands.find(
(parameter) => parameter === userFullInput
)
? userFullInput + ' ' // Problem is that userInput is the same as RegExp it returns null, but when it has
: // at least one whitespace it is not null
// https://codepen.io/belokha/pen/xxwOdWg?editors=0012, Example 5.
userFullInput;

const execResult = new RegExp(
`(?<command>${singleParameterAfterCommands.join(
'|\\'
)})\\s(?<firstargument>.*)`
).exec(makeMagicOverUserFullInput);
if (!execResult) {
return undefined;
}

/* tslint:disable:no-string-literal */
if (execResult.groups['command'] && !execResult.groups['firstargument']) {
return undefined;
}

return execResult.groups['firstargument'];
/* tslint:enable:no-string-literal */
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { MessageHandlerRegistry } from './messageHandlerRegistry';

describe('MessageHandlerRegistry', () => {
let messageHandlerRegistry: MessageHandlerRegistry;
const botMock: any = {
sendMessage: jest.fn().mockReturnValue(Promise.resolve('message')),
on: jest.fn(),
};
beforeAll(() => {
messageHandlerRegistry = new MessageHandlerRegistry(botMock);
});

it('should be created', () => {
expect(!!messageHandlerRegistry).toBeTruthy();
});
});

0 comments on commit d3abb1b

Please sign in to comment.