Skip to content

Commit

Permalink
Coroutes list support
Browse files Browse the repository at this point in the history
- Created seperate converter for coroutes
  • Loading branch information
Lucky38i committed Jan 15, 2022
1 parent 2a60a38 commit d48cda0
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 42 deletions.
7 changes: 5 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@
// overrides airbnb, use sparingly
"rules": {
"object-curly-newline": ["error", { "multiline": true }],

// Required for dependency injection
"no-useless-constructor": "off",
"no-empty-function": "off"
"no-empty-function": "off",

// Annoying shit
"linebreak-style": ["error", "unix"],
"no-await-in-loop":"off"
}
}
10 changes: 10 additions & 0 deletions src/coRoute/coroute.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,14 @@ export class CoRouteController {
async getRte(@Query('rteNum') routeNum: String): Promise<CoRouteDto> {
return this.coRouteService.getForRteNum(routeNum);
}

@Get('list')
@ApiResponse({
status: 200,
description: 'The list of company routes matching the given origin and destination ICAOs',
type: [CoRouteDto],
})
async getRteForIcaos(@Query('origin') originIcao: String, @Query('destination') destinationIcao: String) {
return this.coRouteService.getRoutesForIcao(originIcao, destinationIcao);
}
}
41 changes: 41 additions & 0 deletions src/coRoute/coroute.converter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { validateOrReject } from 'class-validator';
import { Airport } from './dto/airport.dto';
import { CoRouteDto } from './dto/coroute.dto';
import { Fix } from './dto/fix.dto';
import { General } from './dto/general.dto';
import { Navlog } from './dto/navlog.dto';

@Injectable()
export class CoRouteConverter {
private readonly logger = new Logger(CoRouteConverter.name)

convertJsonToDto(parsedObject: any): CoRouteDto {
try {
const tempCoRouteDto = new CoRouteDto();
const tempNavlog = new Navlog();
tempCoRouteDto.destination = plainToClass(Airport, parsedObject.OFP.destination);
tempCoRouteDto.origin = plainToClass(Airport, parsedObject.OFP.origin);
tempCoRouteDto.general = plainToClass(General, parsedObject.OFP.general);
parsedObject.OFP.navlog.fix.forEach((item: any) => tempNavlog.fix.push(plainToClass(Fix, item)));
tempCoRouteDto.navlog = tempNavlog;

return tempCoRouteDto;
} catch (errors) {
const message = 'Failed to instantiate DTO';
this.logger.warn(message, errors);
throw new HttpException(message, HttpStatus.UNPROCESSABLE_ENTITY);
}
}

async validateCoRoute(coRoute: CoRouteDto, rteNumber: String = 'PLACEHOLDER') {
try {
await validateOrReject(coRoute, { whitelist: true });
} catch (errors) {
const message = `${rteNumber} failed validation`;
this.logger.warn(`${rteNumber} failed validation`, errors);
throw new HttpException(message, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
}
3 changes: 2 additions & 1 deletion src/coRoute/coroute.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { CoRouteConverter } from './coroute.converter';
import { UtilitiesModule } from '../utilities/utilities.module';
import { CoRouteController } from './coroute.controller';
import { CoRouteService } from './coroute.service';

@Module({
controllers: [CoRouteController],
providers: [CoRouteService],
providers: [CoRouteService, CoRouteConverter],
imports: [UtilitiesModule],
})
export class CoRouteModule {}
66 changes: 27 additions & 39 deletions src/coRoute/coroute.service.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { validateOrReject } from 'class-validator';
import { Navlog } from './dto/navlog.dto';
import { Airport } from './dto/airport.dto';
import { Fix } from './dto/fix.dto';
import { General } from './dto/general.dto';
import { Injectable, Logger } from '@nestjs/common';
import { FileService } from '../utilities/file.service';
import { CoRouteDto } from './dto/coroute.dto';
import { CoRouteConverter } from './coroute.converter';

@Injectable()
export class CoRouteService {
constructor(private fileService: FileService) {}
constructor(private fileService: FileService, private coRouteConverter: CoRouteConverter) {}

private coRouteDirectory = 'resources/coroutes/';

Expand All @@ -26,42 +21,35 @@ export class CoRouteService {

const JsonString = await this.fileService.convertXmlToJson(buffer);

const coRoute = this.convertJsonToDto(JSON.parse(JsonString));
return this.validateRetrievedCoRoute(rteNumber, coRoute).then(() => coRoute);
}

convertJsonToDto(parsedObject): CoRouteDto {
try {
const tempCoRouteDto = new CoRouteDto();
const tempNavlog = new Navlog();
tempCoRouteDto.destination = plainToClass(Airport, parsedObject.OFP.destination);
tempCoRouteDto.origin = plainToClass(Airport, parsedObject.OFP.origin);
tempCoRouteDto.general = plainToClass(General, parsedObject.OFP.general);
parsedObject.OFP.navlog.fix.forEach((item) => tempNavlog.fix.push(plainToClass(Fix, item)));
tempCoRouteDto.navlog = tempNavlog;

return tempCoRouteDto;
} catch (errors) {
const message = 'Failed to instantiate DTO';
this.logger.warn(message, errors);
throw new HttpException(message, HttpStatus.UNPROCESSABLE_ENTITY);
}
const coRoute = this.coRouteConverter.convertJsonToDto(JSON.parse(JsonString));
return this.coRouteConverter.validateCoRoute(coRoute, rteNumber).then(() => coRoute);
}

getNumOfRoutes(): Promise<number> {
return this.fileService.getFileCount(this.coRouteDirectory);
}

private async validateRetrievedCoRoute(
rteNumber: String,
coRoute: CoRouteDto,
) {
try {
await validateOrReject(coRoute, { whitelist: true });
} catch (errors) {
const message = `${rteNumber} failed validation`;
this.logger.warn(`${rteNumber} failed validation`, errors);
throw new HttpException(message, HttpStatus.UNPROCESSABLE_ENTITY);
}
async getRoutesForIcao(originIcao: String, destinationIcao: String): Promise<CoRouteDto[]> {
this.logger.debug(`Searching for CoRoutes given origin: ${originIcao} and destination: ${destinationIcao}`);

const fileBuffers = await this.fileService.getFiles(this.coRouteDirectory);

const fileJsons = await Promise.all(fileBuffers.map(async (buffer) => this.fileService.convertXmlToJson(buffer)));

const coRoutes = fileJsons.map((jsonStrings) => this.coRouteConverter.convertJsonToDto(JSON.parse(jsonStrings)));

const validatedCoRoutes: CoRouteDto[] = [];
coRoutes.forEach((coRoute) => this.coRouteConverter.validateCoRoute(coRoute)
.then(() => {
if (coRoute.origin.icao_code === originIcao && coRoute.destination.icao_code) {
validatedCoRoutes.push(coRoute);
} else {
this.logger.debug(`coRoute didn't match req params, skipping: ${JSON.stringify(coRoute)}`);
}
})
// Should we print the entire coroute ?
.catch(() => this.logger.warn(`coRoute failed validation: ${JSON.stringify(coRoute)}`)));

return validatedCoRoutes;
}
}
19 changes: 19 additions & 0 deletions src/utilities/file.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,25 @@ export class FileService {
}
}

async getFiles(directory: PathLike): Promise<Buffer[]> {
try {
this.logger.debug(`Reading all files in directory: ${directory}`);

const fileNames = await readdir(`${process.cwd()}/${directory}`);

const files: Buffer[] = [];
for (const fileName of fileNames) {
files.push(await this.getFile(directory, fileName));
}

return files;
} catch (err) {
const message = `Error reading directory: ${directory}`;
this.logger.error(message, err);
throw new HttpException(message, HttpStatus.NOT_FOUND);
}
}

async getFile(directory: PathLike, fileName: PathLike): Promise<Buffer> {
try {
this.logger.debug(`Retreiving file: ${fileName} in folder: ${directory}`);
Expand Down

0 comments on commit d48cda0

Please sign in to comment.