Skip to content

Commit

Permalink
[Fix] Jest Test e2e (#402)
Browse files Browse the repository at this point in the history
* chore(deps): bump jest from ^27.1.1 to ^29.7.0

* fix: updated gitignore file

* fix: typeorm nested relations query syntax

* chore(deps): bump prettier from ^2.4.0 to ^3.2.5

* fix:  run prettier for formatting

* fix: run prettier for formatting

* fix: typeorm nested relations query syntax

* fix: get data source connection for e2e testing

* fix: run prettier for formatting

* fix: run prettier for formatting

* fix: increased jest testTimeout

* fix: removed maxWorker for jest

* update yarn.lock

* chore: update yarn.lock

* fix: coderabbitai suggestion

* fix: coderabbitai suggestion

* chore: update yarn.lock

* fix: removed console

* style: fix code style issues using Prettier

* fix: updated connection datasource
  • Loading branch information
rahul-rocket authored Oct 18, 2024
1 parent 22a2254 commit 96a2ec4
Show file tree
Hide file tree
Showing 49 changed files with 574 additions and 200 deletions.
2 changes: 1 addition & 1 deletion api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"crypto": "^1.0.1",
"crypto": "^1.0.1",
"csv": "^5.5.3",
"csv-stringify": "^6.0.5",
"ejs": "^3.1.10",
Expand Down
59 changes: 59 additions & 0 deletions api/src/connection/datasource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { DataSource, DataSourceOptions, DefaultNamingStrategy } from 'typeorm';
import * as process from 'process';
import { SnakeNamingStrategy } from '../utils/snake-naming-strategy';

const env = process.env;

/**
* Retrieves the connection options for TypeORM DataSource or TypeORMModule.
*
* @returns The connection options for TypeORM DataSource or TypeORMModule.
*/
export const dataSourceOptions = (): DataSourceOptions => {
// Safely cast the database type or default to 'mysql'
const dbType = (env.TR_DB_TYPE as any) || 'mysql';

// Parse the port safely with fallback to 3306 if parsing fails
const parsedPort = parseInt(env.TR_DB_PORT, 10);
const port = Number.isNaN(parsedPort) ? 3306 : parsedPort;

// Base options object using the more generic DataSourceOptions
const options: DataSourceOptions = {
type: dbType,
host: env.TR_DB_HOST || '127.0.0.1',
port,
username: env.TR_DB_USER || 'root',
password: env.TR_DB_PASSWORD || '',
database: env.TR_DB_DATABASE || 'tr_dev',
charset: 'utf8mb4',
synchronize: false,
logging: false,
entities: [__dirname + '/../entity/*.entity.{js,ts}'],
migrations: [__dirname + '/../migrations/*.{js,ts}'],
namingStrategy: dbType === 'postgres' ? new SnakeNamingStrategy() : new DefaultNamingStrategy(),
};

return options;
};

/**
* Creates and initializes a TypeORM DataSource instance with the provided configuration options.
*
* @returns Initialized TypeORM DataSource instance.
*/
let dataSource: DataSource;
export const getDataSourceConnection = async (): Promise<DataSource> => {
if (!dataSource) {
dataSource = new DataSource(dataSourceOptions());
}

try {
if (!dataSource.isInitialized) {
await dataSource.initialize();
}
} catch (error) {
console.error(`Error initializing database connection: ${error?.message}`);
}

return dataSource;
};
8 changes: 6 additions & 2 deletions api/src/controllers/exports.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ export class ExportsController {
// Ensure locale is requested project locale
const projectLocale = await this.projectLocaleRepo.findOne({
where: {
project: membership.project,
project: {
id: membership.project.id,
},
locale: {
code: query.locale,
},
Expand Down Expand Up @@ -98,7 +100,9 @@ export class ExportsController {
if (query.fallbackLocale) {
const fallbackProjectLocale = await this.projectLocaleRepo.findOne({
where: {
project: membership.project,
project: {
id: membership.project.id,
},
locale: {
code: query.fallbackLocale,
},
Expand Down
4 changes: 3 additions & 1 deletion api/src/controllers/import.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ export class ImportController {
// Extract into service for creating project locales
projectLocale = this.projectLocaleRepo.create({
locale: locale,
project: membership.project,
project: {
id: membership.project.id,
},
});
projectLocale = await entityManager.save(ProjectLocale, projectLocale);
await entityManager.increment(Project, { id: membership.project.id }, 'localesCount', 1);
Expand Down
24 changes: 13 additions & 11 deletions api/src/controllers/project-label.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export default class ProjectLabelController {
async delete(@Req() req, @Param('projectId') projectId: string, @Param('labelId') labelId: string) {
const user = this.auth.getRequestUserOrClient(req);
const membership = await this.auth.authorizeProjectAction(user, projectId, ProjectAction.DeleteLabel);
const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: membership.project } });
const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: { id: membership.project.id } } });
await this.labelRepo.remove(label);
}

Expand All @@ -122,8 +122,8 @@ export default class ProjectLabelController {
const user = this.auth.getRequestUserOrClient(req);
const membership = await this.auth.authorizeProjectAction(user, projectId, ProjectAction.EditLabel);

const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: membership.project } });
const term = await this.termsRepo.findOneOrFail({ where: { id: termId, project: membership.project }, relations: ['labels'] });
const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: { id: membership.project.id } } });
const term = await this.termsRepo.findOneOrFail({ where: { id: termId, project: { id: membership.project.id } }, relations: ['labels'] });

term.labels.push(label);

Expand All @@ -149,8 +149,8 @@ export default class ProjectLabelController {
const user = this.auth.getRequestUserOrClient(req);
const membership = await this.auth.authorizeProjectAction(user, projectId, ProjectAction.EditLabel);

const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: membership.project } });
const term = await this.termsRepo.findOneOrFail({ where: { id: termId, project: membership.project }, relations: ['labels'] });
const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: { id: membership.project.id } } });
const term = await this.termsRepo.findOneOrFail({ where: { id: termId, project: { id: membership.project.id } }, relations: ['labels'] });

term.labels = term.labels.filter(t => t.id !== label.id);

Expand All @@ -174,19 +174,21 @@ export default class ProjectLabelController {
const user = this.auth.getRequestUserOrClient(req);
const membership = await this.auth.authorizeProjectAction(user, projectId, ProjectAction.EditLabel);

const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: membership.project } });
const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: { id: membership.project.id } } });

const projectLocale = await this.projectLocaleRepo.findOneOrFail({
where: {
project: membership.project,
project: {
id: membership.project.id,
},
locale: {
code: localeCode,
},
},
});

const translation = await this.translationsRepo.findOneOrFail({
where: { termId: termId, projectLocale: projectLocale },
where: { termId: termId, projectLocale: { id: projectLocale.id } },
relations: ['labels'],
});

Expand All @@ -212,19 +214,19 @@ export default class ProjectLabelController {
const user = this.auth.getRequestUserOrClient(req);
const membership = await this.auth.authorizeProjectAction(user, projectId, ProjectAction.EditLabel);

const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: membership.project } });
const label = await this.labelRepo.findOneOrFail({ where: { id: labelId, project: { id: membership.project.id } } });

const projectLocale = await this.projectLocaleRepo.findOneOrFail({
where: {
project: membership.project,
project: { id: membership.project.id },
locale: {
code: localeCode,
},
},
});

const translation = await this.translationsRepo.findOneOrFail({
where: { termId: termId, projectLocale: projectLocale },
where: { termId: termId, projectLocale: { id: projectLocale.id } },
relations: ['labels'],
});

Expand Down
2 changes: 1 addition & 1 deletion api/src/controllers/project-stats.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export default class ProjectStatsController {
const membership = await this.auth.authorizeProjectAction(user, projectId, ProjectAction.ViewTranslation);
const locales = await this.projectLocaleRepo.find({
where: {
project: membership.project,
project: { id: membership.project.id },
},
relations: ['locale'],
});
Expand Down
5 changes: 4 additions & 1 deletion api/src/controllers/project-user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ import AuthorizationService from '../services/authorization.service';
@ApiOAuth2([])
@ApiTags('Project Users')
export default class ProjectUserController {
constructor(private auth: AuthorizationService, @InjectRepository(ProjectUser) private projectUserRepo: Repository<ProjectUser>) {}
constructor(
private auth: AuthorizationService,
@InjectRepository(ProjectUser) private projectUserRepo: Repository<ProjectUser>,
) {}

@Get(':projectId/users')
@ApiOperation({ summary: 'List all users with access to a project' })
Expand Down
6 changes: 4 additions & 2 deletions api/src/controllers/term.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ export default class TermController {

const projectLocales = await this.projectLocaleRepo.find({
where: {
project: membership.project,
project: {
id: membership.project.id,
},
},
});

Expand Down Expand Up @@ -143,7 +145,7 @@ export default class TermController {
const user = this.auth.getRequestUserOrClient(req);
const membership = await this.auth.authorizeProjectAction(user, projectId, ProjectAction.DeleteTerm);
await this.termRepo.manager.transaction(async entityManager => {
const term = await entityManager.findOneOrFail(Term, { where: { id: termId, project: membership.project } });
const term = await entityManager.findOneOrFail(Term, { where: { id: termId, project: { id: membership.project.id } } });
await entityManager.remove(term);
await entityManager.decrement(Project, { id: membership.project.id }, 'termsCount', 1);
});
Expand Down
20 changes: 13 additions & 7 deletions api/src/controllers/translation.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export default class TranslationController {
const membership = await this.auth.authorizeProjectAction(user, projectId, ProjectAction.ViewTranslation);
const locales = await this.projectLocaleRepo.find({
where: {
project: membership.project,
project: { id: membership.project.id },
},
relations: ['locale'],
});
Expand Down Expand Up @@ -95,8 +95,10 @@ export default class TranslationController {
});

const result = await this.projectLocaleRepo.findOneByOrFail({
locale,
project: membership.project,
locale: {
code: locale.code,
},
project: { id: membership.project.id },
});

return {
Expand Down Expand Up @@ -126,7 +128,7 @@ export default class TranslationController {
// Ensure locale is requested project locale
const projectLocale = await this.projectLocaleRepo.findOneOrFail({
where: {
project: membership.project,
project: { id: membership.project.id },
locale: {
code: localeCode,
},
Expand All @@ -135,7 +137,9 @@ export default class TranslationController {
try {
const translations = await this.translationRepo.find({
where: {
projectLocale,
projectLocale: {
id: projectLocale.id,
},
},
relations: ['term', 'labels'],
});
Expand Down Expand Up @@ -186,7 +190,9 @@ export default class TranslationController {
let translation = await this.translationRepo.findOne({
where: {
termId: term.id,
projectLocale: projectLocale,
projectLocale: {
id: projectLocale.id,
},
},
relations: ['labels'],
});
Expand Down Expand Up @@ -231,7 +237,7 @@ export default class TranslationController {
await this.projectLocaleRepo.manager.transaction(async entityManager => {
const projectLocale = await entityManager.findOneOrFail(ProjectLocale, {
where: {
project: membership.project,
project: { id: membership.project.id },
locale: {
code: localeCode,
},
Expand Down
5 changes: 4 additions & 1 deletion api/src/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import { UserService } from '../services/user.service';
@ApiOAuth2([])
@ApiTags('Users')
export default class UserController {
constructor(private auth: AuthorizationService, private userService: UserService) {}
constructor(
private auth: AuthorizationService,
private userService: UserService,
) {}

@Get('me')
@ApiOperation({ summary: `Get the current user's profile` })
Expand Down
36 changes: 18 additions & 18 deletions api/src/formatters/fixtures/function-name-nested.json
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
{
"term": {
"one": "data.VWAnalyticssaleorder.docdate.day",
"two": {
"hour": "data.VWAnalyticssaleorder.docdate"
},
"three": "UPDATE_SCHEDULER_SCREEN.EDIT_EVENT.HOURS"
"term": {
"one": "data.VWAnalyticssaleorder.docdate.day",
"two": {
"hour": "data.VWAnalyticssaleorder.docdate"
},
"data": {
"VWAnalyticssaleorder": {
"docdate": {
"day": "foo"
}
}
},
"UPDATE_SCHEDULER_SCREEN": {
"EDIT_EVENT": {
"HOURS": "bar"
}
"three": "UPDATE_SCHEDULER_SCREEN.EDIT_EVENT.HOURS"
},
"data": {
"VWAnalyticssaleorder": {
"docdate": {
"day": "foo"
}
}
},
"UPDATE_SCHEDULER_SCREEN": {
"EDIT_EVENT": {
"HOURS": "bar"
}
}
}
}
10 changes: 5 additions & 5 deletions api/src/formatters/fixtures/simple-flat.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"term.one": "Current Plan: {{ project.plan.name }}",
"term two": "{VAR_PLURAL, plural, =0 {locales} =1 {locale} other {locales} }",
"TERM_THREE": "Export format...",
"term:four": "hello there you\\nthis should be in a newline"
}
"term.one": "Current Plan: {{ project.plan.name }}",
"term two": "{VAR_PLURAL, plural, =0 {locales} =1 {locale} other {locales} }",
"TERM_THREE": "Export format...",
"term:four": "hello there you\\nthis should be in a newline"
}
14 changes: 7 additions & 7 deletions api/src/formatters/fixtures/simple-nested.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"term": {
"one": "Current Plan: {{ project.plan.name }}"
},
"term two": "{VAR_PLURAL, plural, =0 {locales} =1 {locale} other {locales} }",
"TERM_THREE": "Export format...",
"term:four": "hello there you\\nthis should be in a newline"
}
"term": {
"one": "Current Plan: {{ project.plan.name }}"
},
"term two": "{VAR_PLURAL, plural, =0 {locales} =1 {locale} other {locales} }",
"TERM_THREE": "Export format...",
"term:four": "hello there you\\nthis should be in a newline"
}
16 changes: 8 additions & 8 deletions api/test/jest-e2e.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testTimeout": 60000,
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testTimeout": 120000,
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
Loading

0 comments on commit 96a2ec4

Please sign in to comment.