Skip to content

Commit

Permalink
style(eslint-config): enforce consistent brace style and control stat…
Browse files Browse the repository at this point in the history
…ements (#2992)

- Add ESLint rules for curly braces, brace style, and newline positioning
- Optimize object curly brace newline consistency

(your code spacing is more inconsistent than a taco truck's salsa recipe)
  • Loading branch information
shanegrouber authored Jan 29, 2025
1 parent 53266d4 commit 11ad58f
Show file tree
Hide file tree
Showing 35 changed files with 137 additions and 56 deletions.
4 changes: 4 additions & 0 deletions packages/eslint-config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ module.exports = {
classPropertiesAllowed: false,
},
],
curly: ['error', 'all'], // Enforce curly braces for all control statements
'brace-style': ['error', '1tbs', { allowSingleLine: false }], // Enforce one true brace style and disallow single-line blocks
'nonblock-statement-body-position': ['error', 'below'], // Enforce body on new line
'object-curly-newline': ['error', { multiline: true, consistent: true }], // Enforce consistent line breaks inside braces
'newline-before-return': 'error',
'padding-line-between-statements': [
'error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,17 @@ module.exports = {

return {
MethodDefinition: node => {
if (!isRepository || node.key.name === 'constructor') return;
if (!isRepository || node.key.name === 'constructor') {
return;
}

const isUnscoped = UNSCOPED_METHOD_NAMES.some(name =>
node.key.name.toLowerCase().includes(name),
);

if (isUnscoped) return;
if (isUnscoped) {
return;
}

const isProjectIdsIncluded = node.value.params.some(
param => param.type === 'Identifier' && param.name.toLowerCase().includes('projectid'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,9 @@ export class AlertControllerExternal {
} = alert as TAlertTransactionResponse;

const counterpartyDetails = (counterparty: TAlertTransactionResponse['counterparty']) => {
if (!counterparty) return;
if (!counterparty) {
return;
}

return counterparty?.business
? {
Expand Down
1 change: 0 additions & 1 deletion services/workflows-service/src/alert/alert.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import { DedupeWindow, TDedupeStrategy, TExecutionDetails } from './types';
import { computeHash } from '@ballerine/common';
import { convertTimeUnitToMilliseconds } from '@/data-analytics/utils';
import { DataInvestigationService } from '@/data-analytics/data-investigation.service';
import { equals } from 'class-validator';

const DEFAULT_DEDUPE_STRATEGIES = {
cooldownTimeframeInMinutes: 60 * 24,
Expand Down
4 changes: 3 additions & 1 deletion services/workflows-service/src/alert/dtos/get-alerts.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ export const FindAlertsSchema = z.object({
.transform(value => {
const [column = '', direction = ''] = value.split(':');

if (!column || !direction) throw new Error('Invalid orderBy');
if (!column || !direction) {
throw new Error('Invalid orderBy');
}

return {
[column]: direction,
Expand Down
4 changes: 3 additions & 1 deletion services/workflows-service/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ export class AuthService {
const user = await this.userService.getByEmailUnscoped(email);

if (user && (await this.passwordService.compare(password, user.password))) {
if (user?.status !== UserStatus.Active) throw new UnauthorizedException('Unauthorized');
if (user?.status !== UserStatus.Active) {
throw new UnauthorizedException('Unauthorized');
}

const { id, firstName, lastName, roles } = user;
const roleList = roles as string[];
Expand Down
4 changes: 3 additions & 1 deletion services/workflows-service/src/auth/session-serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ export class SessionSerializer extends PassportSerializer {

return done(null, authenticatedEntity);
} catch (err) {
if (!isRecordNotFoundError(err)) throw err;
if (!isRecordNotFoundError(err)) {
throw err;
}

return done(null, null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ export class CaseManagementService {
const dataSchema =
workflowDefinition.definition?.states[inputState]?.meta?.inputSchema?.dataSchema;

if (!dataSchema?.schema) return;
if (!dataSchema?.schema) {
return;
}

const validate = ajv.compile(dataSchema.schema);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ export class CollectionFlowController {
[tokenScope.projectId],
);

if (!activeWorkflow) throw new common.InternalServerErrorException('Workflow not found.');
if (!activeWorkflow) {
throw new common.InternalServerErrorException('Workflow not found.');
}

try {
const adapter = this.adapterManager.getAdapter(activeWorkflow.workflowDefinitionId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ export class WorkflowAdapterManager {
getAdapter(type: string) {
const adapter = this.adapters[type];

if (!adapter) throw new UnsupportedFlowTypeException();
if (!adapter) {
throw new UnsupportedFlowTypeException();
}

return adapter;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ export class InvalidArgumentParser extends IParser {
parse(): IParserResult {
const { message } = this;

if (!message) return {};
if (!message) {
return {};
}

return this.execPattern(this.pattern, (result, match) => {
const [_, paramName, errorReason] = match;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ export abstract class IParser {

let match: RegExpExecArray | null = null;

if (!message) return {};
if (!message) {
return {};
}

while ((match = pattern.exec(message))) {
parseResult = resolver(parseResult, match);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ export class UnknownArgumentParser extends IParser {
pattern = new RegExp(/Unknown arg `(.+?)` in (.+?) for type (.+?)\./, 'gi');

parse(): IParserResult {
if (!this.message) return {};
if (!this.message) {
return {};
}

return this.execPattern(this.pattern, (result, match) => {
const [_, fieldName, failedOnPath, type] = match;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
export const getFileExtension = (fileName: string) => {
const parts = fileName?.split('.');

if (!parts?.length) return;
if (!parts?.length) {
return;
}

const extension = parts?.[parts?.length - 1];
// For Handling URLs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ export class UserSessionAuditMiddleware implements NestMiddleware {
lastUpdate: Date | null,
updateIntervalInMs: number = this.UPDATE_INTERVAL,
) {
if (!lastUpdate) return true;
if (!lastUpdate) {
return true;
}

const now = Date.now();
const pastDate = Number(new Date(lastUpdate));
Expand Down
4 changes: 3 additions & 1 deletion services/workflows-service/src/common/utils/bytes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// formatBytes(1024) // 1 KiB
// formatBytes('1024') // 1 KiB
export const formatBytes = (bytes: any, decimals = 2) => {
if (!+bytes) return '0 Bytes';
if (!+bytes) {
return '0 Bytes';
}

const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ export const logDocumentWithoutId = ({
}) => {
workflowRuntimeData?.context?.documents?.forEach(
(document: DefaultContextSchema['documents'][number]) => {
if (document?.id) return;
if (document?.id) {
return;
}

logger.error('Document without an ID was found', {
line,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ export class CustomerControllerExternal {
async getByCurrentProjectId(
@CurrentProject() currentProjectId: TProjectId,
): Promise<TCustomerWithFeatures | null> {
if (!currentProjectId) throw new NotFoundException('Customer not found');
if (!currentProjectId) {
throw new NotFoundException('Customer not found');
}

return this.service.getByProjectId(currentProjectId, {
select: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ export class CustomerControllerInternal {
async find(@ProjectIds() projectIds: TProjectIds): Promise<TCustomerWithFeatures | null> {
const projectId = projectIds?.[0];

if (!projectId) throw new NotFoundException('Customer not found');
if (!projectId) {
throw new NotFoundException('Customer not found');
}

return this.service.getByProjectId(projectId, {
select: {
Expand Down
12 changes: 9 additions & 3 deletions services/workflows-service/src/customer/customer.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,19 @@ export class CustomerRepository {
}

async validateApiKey(apiKey?: string) {
if (apiKey === undefined) return;
if (apiKey === undefined) {
return;
}

if (apiKey.length < 4) throw new Error('Invalid API key');
if (apiKey.length < 4) {
throw new Error('Invalid API key');
}

const customerApiAlreadyExists = await this.findByApiKey(apiKey);

if (customerApiAlreadyExists) throw new Error('API key already exists');
if (customerApiAlreadyExists) {
throw new Error('API key already exists');
}
}

async findMany<T extends Prisma.CustomerFindManyArgs>(
Expand Down
8 changes: 6 additions & 2 deletions services/workflows-service/src/events/get-webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@ export const mergeSubscriptions = (
customerSubscriptions: TCustomerSubscription['subscriptions'],
workflowSubscriptions: TCustomerSubscription['subscriptions'],
): TCustomerSubscription['subscriptions'] => {
if (!workflowSubscriptions?.length) return customerSubscriptions ?? [];
if (!workflowSubscriptions?.length) {
return customerSubscriptions ?? [];
}

if (!customerSubscriptions?.length) return workflowSubscriptions ?? [];
if (!customerSubscriptions?.length) {
return workflowSubscriptions ?? [];
}

const workflowEvents = workflowSubscriptions.flatMap(sub => sub.events);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import { isRecordNotFoundError } from '@/prisma/prisma.util';
import { ProjectScopeService } from '@/project/project-scope.service';
import type { InputJsonValue, TProjectId, TProjectIds } from '@/types';
import { CurrentProject } from '@/common/decorators/current-project.decorator';
import { UseCustomerAuthGuard } from '@/common/decorators/use-customer-auth-guard.decorator';

@swagger.ApiBearerAuth()
@swagger.ApiTags('Filters')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,9 @@ export class MetricsRepository {
buildAggregateDailyCasesResolvedQuery(params.fromDate, params.userId, projectIds),
);

if (!results.length) return [];
if (!results.length) {
return [];
}

return results.map(result =>
plainToClass(CasesResolvedInDay, {
Expand Down
4 changes: 3 additions & 1 deletion services/workflows-service/src/storage/storage.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ export class StorageService {
}

private __getAbsoluteFilePAth(filePath: string) {
if (!path.isAbsolute(filePath)) return filePath;
if (!path.isAbsolute(filePath)) {
return filePath;
}

const rootDir = path.parse(os.homedir()).root;

Expand Down
8 changes: 6 additions & 2 deletions services/workflows-service/src/test/db-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ process.env.LOG_LEVEL = 'error';
const DATABASE_NAME = 'test';

module.exports = async () => {
if (process.env.SKIP_DB_SETUP_TEARDOWN) return;
if (process.env.SKIP_DB_SETUP_TEARDOWN) {
return;
}

const container = await new PostgreSqlContainer('sibedge/postgres-plv8:15.3-3.1.7')
.withDatabase(DATABASE_NAME)
Expand All @@ -32,7 +34,9 @@ module.exports = async () => {
};

const runPrismaMigrations = () => {
if (process.env.SKIP_DB_SETUP_TEARDOWN) return;
if (process.env.SKIP_DB_SETUP_TEARDOWN) {
return;
}

try {
execSync('npx prisma migrate dev --preview-feature', { stdio: 'inherit' });
Expand Down
4 changes: 3 additions & 1 deletion services/workflows-service/src/test/db-teardown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { TestGlobal } from '@/test/test-global';
export const teardown = async () => {
const globalThisTest = globalThis as TestGlobal;

if (!globalThisTest.__DB_CONTAINER__) return;
if (!globalThisTest.__DB_CONTAINER__) {
return;
}

await globalThisTest.__DB_CONTAINER__.stop({ removeVolumes: true });
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,10 @@ import {
} from '@prisma/client';
import { createProject } from '@/test/helpers/create-project';
import { TransactionModule } from '@/transaction/transaction.module';
import { TransactionControllerExternal } from '@/transaction/transaction.controller.external';
import { TransactionCreateDto } from '@/transaction/dtos/transaction-create.dto';
import { generateBusiness, generateEndUser } from '../../scripts/generate-end-user';
import { BulkStatus } from '@/alert/types';
import { ProjectScopeService } from '@/project/project-scope.service';
import { AlertRepository } from '@/alert/alert.repository';
import { AlertDefinitionRepository } from '@/alert-definition/alert-definition.repository';
import { DataAnalyticsService } from '@/data-analytics/data-analytics.service';
import { ConfigService } from '@nestjs/config';
import { AlertService } from '@/alert/alert.service';
import { MerchantMonitoringClient } from '@/business-report/merchant-monitoring-client';
import { DataAnalyticsModule } from '@/data-analytics/data-analytics.module';
import { AlertModule } from '@/alert/alert.module';

const getBusinessCounterpartyData = (business?: Business) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { GetTransactionsDto } from './dtos/get-transactions.dto';
import { DateTimeFilter } from '@/common/query-filters/date-time-filter';
import { toPrismaOrderByGeneric } from '@/workflow/utils/toPrismaOrderBy';
import deepmerge from 'deepmerge';
import { PageDto } from '@/common/dto';

const DEFAULT_TRANSACTION_ORDER = {
transactionDate: Prisma.SortOrder.desc,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,9 @@ export class UiDefinitionService {
getTranslationServiceResources(
uiDefinition: UiDefinition & { locales?: unknown },
): ITranslationServiceResource[] | undefined {
if (!uiDefinition.locales) return undefined;
if (!uiDefinition.locales) {
return undefined;
}

return Object.entries(uiDefinition.locales).map(([language, resource]) => ({
language,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,9 @@ export const getCountriesList = (): ICountry[] =>
}));

export const getCountryStates = (countryCode: string) => {
if (!countryCode) return [];
if (!countryCode) {
return [];
}

return states.filter(
state => state.countryCode.toLocaleLowerCase() === countryCode.toLocaleLowerCase(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ export class WorkflowDefinitionRepository {
if (workflowDefinition?.isPublic) {
throw new Error('Cannot delete public workflow definition templates');
}

return await this.prisma.workflowDefinition.delete(
this.scopeService.scopeDelete(
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,9 @@ export class HookCallbackHandlerService {
currentProjectId,
]);

if (!business) throw new BadRequestException('Business not found.');
if (!business) {
throw new BadRequestException('Business not found.');
}

// const currentReportId = reportId as string;
//
Expand Down Expand Up @@ -313,7 +315,9 @@ export class HookCallbackHandlerService {
documentPage => documentPage.uri === base64PDFString,
);

if (!pdfReportDocument?.ballerineFileId) return;
if (!pdfReportDocument?.ballerineFileId) {
return;
}

pdfReportBallerineFileId = pdfReportDocument.ballerineFileId;
});
Expand Down
Loading

0 comments on commit 11ad58f

Please sign in to comment.