Compare commits

..

No commits in common. "75b459b10f5b53bbe6d0b57c3b6f1ec61e80bea5" and "afebfc9150ba2581abc9cca2c5c07ad459343c68" have entirely different histories.

37 changed files with 175 additions and 737 deletions

View File

@ -1,4 +1,2 @@
database
coverage
tech-assignment-data
node_modules

5
.env
View File

@ -1,5 +0,0 @@
DB_HOST=database
DB_USER=root
DB_PASS=myfreight
DB_PORT=3306
DB_DABA=myfreight

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
/database/lib
/database
.eslintcache
# compiled output

View File

@ -5,7 +5,7 @@ WORKDIR /usr/src/app
COPY package*.json .
RUN npm ci --no-auditdc po
RUN npm ci
COPY . .

View File

@ -1,21 +1,3 @@
# MyFreight Assessment
## How to run
Easiest way to run this project is using docker compose:
`docker compose up`
It is possible that this will give some database connection issues on the first try, but after a couple of seconds, it should automatically reconnect.
Alternatively, it is possible to use your own mysql database, and run the code locally:
1. Import the `database/entrypoint/init.sql` into your own database
2. Update the `.env` file with the database credentials
3. Run `npm ci` to install all npm packages
4. Run `npm run build` to build the nestjs application
5. Run `npm run start:prod` to start the nestjs application
## Receiving Tracking information
When receiving Tracking information, the following steps need to be completed to process the data
```mermaid
flowchart TD
receiveTracking(["Receive Tracking"])
@ -44,16 +26,8 @@ containerNumber:**string**
%% isArrivingSoon -->|yes| sendArriveSoon
```
## Possible improvements
- Sending the actual notification, there should be a more general way to setup notifiers
- Moving some variables to config files
- when is a shipment "arriving soon"
- mock date
- Use the uuid package
- was not possible since the uuid's from the sample data were invalid uuid's
- Add end-to-end tests as well
- Get shipments should be paginated
- Could use a package like typeorm-crud
- Cleanup duplicate OpenApi decorators, perhaps consolidate them in a custom decorator
```mermaid
flowchart
getShipments([Get all shipments])
```

File diff suppressed because one or more lines are too long

View File

@ -3,11 +3,7 @@ services:
build: .
ports:
- "3001:3000"
command: "npm run start:prod"
depends_on:
- database
volumes:
- ".:/usr/src/app"
command: "npm run start:dev"
database:
image: "mysql:8"
command: --default-authentication-plugin=mysql_native_password

24
e2e-tests/app.e2e-spec.ts Normal file
View File

@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

9
e2e-tests/jest-e2e.json Normal file
View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

50
package-lock.json generated
View File

@ -10,13 +10,13 @@
"license": "UNLICENSED",
"dependencies": {
"@nestjs/common": "^10.3.5",
"@nestjs/config": "^3.2.1",
"@nestjs/core": "^10.3.5",
"@nestjs/platform-express": "^10.3.5",
"@nestjs/swagger": "^7.3.0",
"@nestjs/typeorm": "^10.0.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"jest-mock": "^29.7.0",
"mysql2": "^3.9.2",
"reflect-metadata": "^0.2.1",
"rxjs": "^7.8.1",
@ -1432,7 +1432,6 @@
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz",
"integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==",
"dev": true,
"dependencies": {
"@sinclair/typebox": "^0.27.8"
},
@ -1514,7 +1513,6 @@
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz",
"integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==",
"dev": true,
"dependencies": {
"@jest/schemas": "^29.6.3",
"@types/istanbul-lib-coverage": "^2.0.0",
@ -1768,21 +1766,6 @@
}
}
},
"node_modules/@nestjs/config": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/@nestjs/config/-/config-3.2.1.tgz",
"integrity": "sha512-tFZyLJKanSAu51ygQ6ZBSpx95pRcwS6qSpJDW6FFgRQzkOaOUXpL8qD8yMNoYoYxuJCxph+waiBaWKgFWxn3sw==",
"dependencies": {
"dotenv": "16.4.5",
"dotenv-expand": "10.0.0",
"lodash": "4.17.21",
"uuid": "9.0.1"
},
"peerDependencies": {
"@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0",
"rxjs": "^7.1.0"
}
},
"node_modules/@nestjs/core": {
"version": "10.3.5",
"resolved": "https://registry.npmjs.org/@nestjs/core/-/core-10.3.5.tgz",
@ -2031,8 +2014,7 @@
"node_modules/@sinclair/typebox": {
"version": "0.27.8",
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz",
"integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==",
"dev": true
"integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA=="
},
"node_modules/@sinonjs/commons": {
"version": "3.0.1",
@ -2215,14 +2197,12 @@
"node_modules/@types/istanbul-lib-coverage": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
"integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==",
"dev": true
"integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w=="
},
"node_modules/@types/istanbul-lib-report": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz",
"integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==",
"dev": true,
"dependencies": {
"@types/istanbul-lib-coverage": "*"
}
@ -2231,7 +2211,6 @@
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz",
"integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==",
"dev": true,
"dependencies": {
"@types/istanbul-lib-report": "*"
}
@ -2268,7 +2247,6 @@
"version": "20.11.30",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.30.tgz",
"integrity": "sha512-dHM6ZxwlmuZaRmUPfv1p+KrdD1Dci04FbdEm/9wEMouFqxYoFl5aMkt0VMAUtYRQDyYvD41WJLukhq/ha3YuTw==",
"devOptional": true,
"dependencies": {
"undici-types": "~5.26.4"
}
@ -2354,7 +2332,6 @@
"version": "17.0.32",
"resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.32.tgz",
"integrity": "sha512-xQ67Yc/laOG5uMfX/093MRlGGCIBzZMarVa+gfNKJxWAIgykYpVGkBdbqEzGDDfCrVUj6Hiff4mTZ5BA6TmAog==",
"dev": true,
"dependencies": {
"@types/yargs-parser": "*"
}
@ -2362,8 +2339,7 @@
"node_modules/@types/yargs-parser": {
"version": "21.0.3",
"resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz",
"integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
"dev": true
"integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ=="
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "7.3.1",
@ -3404,7 +3380,6 @@
"version": "3.9.0",
"resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz",
"integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==",
"dev": true,
"funding": [
{
"type": "github",
@ -4079,14 +4054,6 @@
"url": "https://dotenvx.com"
}
},
"node_modules/dotenv-expand": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-10.0.0.tgz",
"integrity": "sha512-GopVGCpVS1UKH75VKHGuQFqS1Gusej0z4FyQkPdwjil2gNIv+LNsqBlboOzpJFZKVT95GkCyWJbBSdFEFUWI2A==",
"engines": {
"node": ">=12"
}
},
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
@ -5159,8 +5126,7 @@
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"dev": true
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="
},
"node_modules/graphemer": {
"version": "1.4.0",
@ -6007,7 +5973,6 @@
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz",
"integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==",
"dev": true,
"dependencies": {
"@jest/types": "^29.6.3",
"@types/node": "*",
@ -6237,7 +6202,6 @@
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz",
"integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==",
"dev": true,
"dependencies": {
"@jest/types": "^29.6.3",
"@types/node": "*",
@ -6254,7 +6218,6 @@
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"engines": {
"node": ">=8.6"
},
@ -9519,8 +9482,7 @@
"node_modules/undici-types": {
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
"devOptional": true
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="
},
"node_modules/universalify": {
"version": "2.0.1",

View File

@ -11,23 +11,24 @@
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/src/main",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config e2e-tests/jest-e2e.json",
"prepare": "husky install"
},
"dependencies": {
"@nestjs/common": "^10.3.5",
"@nestjs/config": "^3.2.1",
"@nestjs/core": "^10.3.5",
"@nestjs/platform-express": "^10.3.5",
"@nestjs/swagger": "^7.3.0",
"@nestjs/typeorm": "^10.0.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"jest-mock": "^29.7.0",
"mysql2": "^3.9.2",
"reflect-metadata": "^0.2.1",
"rxjs": "^7.8.1",
@ -67,12 +68,8 @@
"ts"
],
"rootDir": ".",
"roots": [
"<rootDir>/tests"
],
"testPathIgnorePatterns": [
"./database"
],
"roots": ["<rootDir>/tests"],
"testPathIgnorePatterns": ["./database"],
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
@ -80,7 +77,7 @@
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "<rootDir>/coverage",
"coverageDirectory": "../coverage",
"testEnvironment": "node",
"moduleNameMapper": {
"@/(.*)": "<rootDir>/src/$1",

21
src/app.controller.ts Normal file
View File

@ -0,0 +1,21 @@
import {
ClassSerializerInterceptor,
Controller,
Get,
UseInterceptors,
} from '@nestjs/common';
import { AppService } from './app.service';
import { ApiExtraModels } from '@nestjs/swagger';
import { TrackingDto } from '@/dtos/tracking.dto';
@Controller()
@ApiExtraModels(TrackingDto)
@UseInterceptors(ClassSerializerInterceptor)
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
debug(): unknown {
return this.appService.debug();
}
}

View File

@ -1,51 +1,35 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ContainerEntity } from '@/entities/container.entity';
import { LiveTrackingEntity } from '@/entities/liveTracking.entity';
import { ShipmentEntity } from '@/entities/shipment.entity';
import { TrackingModule } from './tracking/tracking.module';
import { ShipmentsModule } from './shipments/shipments.module';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from '@/guards/auth.guard';
import { ApiKeyEntity } from '@/entities/apiKey.entity';
import { AuthService } from '@/auth.service';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
TypeOrmModule.forRootAsync({
imports: [ConfigModule.forRoot()],
useFactory: async (configService: ConfigService) => {
return {
type: 'mysql',
host: configService.get('DB_HOST'),
port: Number(configService.get('DB_PORT')),
username: configService.get('DB_USER'),
password: configService.get('DB_PASS'),
database: configService.get('DB_DABA'),
entities: [
ContainerEntity,
LiveTrackingEntity,
ShipmentEntity,
ApiKeyEntity,
],
synchronize: true,
logging: false,
};
},
inject: [ConfigService],
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 13306,
username: 'root',
password: 'myfreight',
database: 'myfreight',
entities: [ContainerEntity, LiveTrackingEntity, ShipmentEntity],
synchronize: true,
logging: false,
}),
TypeOrmModule.forFeature([ApiKeyEntity]),
TypeOrmModule.forFeature([
ContainerEntity,
LiveTrackingEntity,
ShipmentEntity,
]),
TrackingModule,
ShipmentsModule,
],
controllers: [],
providers: [
AuthService,
{
provide: APP_GUARD,
useClass: AuthGuard,
},
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

19
src/app.service.ts Normal file
View File

@ -0,0 +1,19 @@
import { Injectable } from '@nestjs/common';
import { ContainerEntity } from '@/entities/container.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
@Injectable()
export class AppService {
constructor(
@InjectRepository(ContainerEntity)
private readonly containerRepository: Repository<ContainerEntity>,
) {}
async debug(): Promise<unknown> {
return this.containerRepository.find({
take: 5,
});
// return 'Hello World!';
}
}

View File

@ -1,28 +0,0 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ApiKeyEntity } from '@/entities/apiKey.entity';
import * as crypto from 'crypto';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(ApiKeyEntity)
private readonly apiKeyRepository: Repository<ApiKeyEntity>,
) {}
async isAllowed(apiKey: string, apiSecret: string): Promise<boolean> {
const apiKeyEntity = await this.apiKeyRepository.findOneBy({
apiKey,
});
if (!apiKeyEntity || !apiKeyEntity.enabled) {
return false;
}
const hmac = crypto.createHmac('sha256', apiSecret);
const digest = hmac.update(apiKey).digest('hex');
return digest === apiKeyEntity.digest;
}
}

View File

@ -1,23 +0,0 @@
import { Column, Entity, PrimaryColumn } from 'typeorm';
@Entity({
name: 'apiKeys',
})
export class ApiKeyEntity {
@PrimaryColumn({
type: 'char',
length: 25,
})
apiKey!: string;
@Column({
type: 'char',
length: 64,
})
digest!: string;
@Column({
type: 'boolean',
})
enabled!: boolean;
}

View File

@ -1,47 +0,0 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Request } from 'express';
import { AuthService } from '@/auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly authService: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const apiCredentials = this.extractCredentialsFromRequestApiKey(request);
if (!apiCredentials) {
return false;
}
return this.authService.isAllowed(
apiCredentials.key,
apiCredentials.secret,
);
}
private extractCredentialsFromRequestApiKey(request: Request):
| {
key: string;
secret: string;
}
| false {
const authorization = request.headers.authorization;
if (!authorization) {
return false;
}
const [key, secret] = Buffer.from(authorization, 'base64')
.toString('utf8')
.split(':', 2);
if (!key || !secret) {
return false;
}
return {
key,
secret,
};
}
}

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ShipmentsController } from './shipments.controller';
describe('ShipmentsController', () => {
let controller: ShipmentsController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ShipmentsController],
}).compile();
controller = module.get<ShipmentsController>(ShipmentsController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
it('should', () => {
expect(true).toBe(true);
});
});

View File

@ -1,13 +1,6 @@
import { Controller, Get } from '@nestjs/common';
import { ShipmentsService } from '@/shipments/shipments.service';
import {
ApiExtraModels,
ApiOkResponse,
ApiSecurity,
ApiTags,
ApiUnauthorizedResponse,
getSchemaPath,
} from '@nestjs/swagger';
import { ApiExtraModels, ApiOkResponse, getSchemaPath } from '@nestjs/swagger';
import {
ShipmentContainerDto,
ShipmentDto,
@ -20,41 +13,15 @@ export class ShipmentsController {
constructor(private readonly shipmentsService: ShipmentsService) {}
@Get()
@ApiTags('Shipping')
@ApiOkResponse({
description: 'Returns a list of shipments',
schema: {
type: 'object',
properties: {
data: {
items: {
$ref: getSchemaPath(ShipmentDto),
},
},
items: {
$ref: getSchemaPath(ShipmentDto),
},
},
})
@ApiUnauthorizedResponse({
description: 'Unauthorized request',
schema: {
type: 'object',
properties: {
message: {
type: 'string',
},
error: {
type: 'string',
},
statusCode: {
type: 'number',
},
},
},
})
@ApiSecurity('API key')
async getShipments() {
return {
data: await this.shipmentsService.getAll(),
};
getShipments() {
return this.shipmentsService.getAll();
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ShipmentsService } from './shipments.service';
describe('ShipmentsService', () => {
let service: ShipmentsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ShipmentsService],
}).compile();
service = module.get<ShipmentsService>(ShipmentsService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -10,6 +10,7 @@ export class ShipmentsService {
private readonly shipmentRepository: Repository<ShipmentEntity>,
) {}
// @todo add pagination
getAll() {
return this.shipmentRepository.find({
relations: ['liveTracking', 'containers'],

View File

@ -20,7 +20,7 @@ export class ConsoleNotifier extends NotifierAbstract implements INotifier {
private generateMessages(): string[] {
const messages: string[] = [];
if (this.isDelayed) {
messages.push('Your shipment has been delayed');
messages.push('Your shipment has been delayed.');
}
if (this.daysToArrival <= 0) {

View File

@ -4,9 +4,6 @@ import {
ApiExtraModels,
ApiNotFoundResponse,
ApiOkResponse,
ApiSecurity,
ApiTags,
ApiUnauthorizedResponse,
ApiUnprocessableEntityResponse,
getSchemaPath,
} from '@nestjs/swagger';
@ -29,58 +26,11 @@ export class TrackingController {
@ApiUnprocessableEntityResponse({
description:
'The shipment has been found, but the shipment data does not match.',
schema: {
type: 'object',
properties: {
message: {
type: 'string',
},
error: {
type: 'string',
},
statusCode: {
type: 'number',
},
},
},
})
@ApiNotFoundResponse({
description: 'We could not find any shipment matching the request.',
schema: {
type: 'object',
properties: {
message: {
type: 'string',
},
error: {
type: 'string',
},
statusCode: {
type: 'number',
},
},
},
})
@ApiUnauthorizedResponse({
description: 'Unauthorized request',
schema: {
type: 'object',
properties: {
message: {
type: 'string',
},
error: {
type: 'string',
},
statusCode: {
type: 'number',
},
},
},
})
@HttpCode(200)
@ApiSecurity('API key')
@ApiTags('Tracking')
track(@Body() body: TrackingDto): Promise<unknown> {
return this.trackingService
.track(body)

View File

@ -21,7 +21,7 @@ export class TrackingService {
) {}
public async track(trackingInfo: TrackingDto) {
const container = await this.containerRepository.findOne({
const container = await this.containerRepository.findOneOrFail({
relations: ['shipment'],
where: {
containerNumber: trackingInfo.containerNumber,
@ -38,22 +38,18 @@ export class TrackingService {
}
private validate(
container: ContainerEntity | null,
{ shipment }: ContainerEntity,
trackingInfo: TrackingDto,
): ShipmentEntity {
if (!container) {
throw new NotFoundException('Container not found');
}
if (!container.shipment) {
if (!shipment) {
throw new NotFoundException('Shipment not found');
}
if (container.shipment.carrierName !== trackingInfo.carrierName) {
if (shipment.carrierName !== trackingInfo.carrierName) {
throw new UnprocessableEntityException('CarrierName does not match');
}
return container.shipment;
return shipment;
}
private async updateShipment(

View File

@ -6,11 +6,7 @@ export function openApi(app: INestApplication) {
.setTitle('MyFreight Assessment')
.setDescription('Backend assessment for MyFreight')
.setVersion('1.0')
.addSecurity('API key', {
type: 'apiKey',
in: 'header',
name: 'Authorization',
})
.addTag('MyFreight')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);

@ -1 +1 @@
Subproject commit 89136dcd85c5de7b8a927c9cfaa21bee61506254
Subproject commit b753a440a945ba260c1c583d6f0a0361591d0fc8

View File

@ -6,7 +6,7 @@ import { ContainerEntity } from '@/entities/container.entity';
export const mockTrackingInfo: TrackingDto = {
carrierName: 'Evergreen',
destinationUnLoCode: 'NLAMS',
departureDate: new Date('2023-01-14T11:00:00.000Z'),
departureDate: new Date('2023-05-14T11:00:00.000Z'),
arrivalDateEstimate: new Date('2023-02-14T15:00:00.000Z'),
containerNumber: 'AAAA000000000',
};
@ -17,7 +17,7 @@ export const mockShipment: ShipmentEntity = {
carrierName: 'Evergreen',
originPort: 'NLAMS',
destinationPort: 'NLAMS',
departureDate: new Date('2023-01-14T11:00:00.000Z'),
departureDate: new Date('2023-05-14T11:00:00.000Z'),
arrivalDateOriginal: new Date('2023-02-14T15:00:00.000Z'),
arrivalDateEstimate: new Date('2023-02-14T15:00:00.000Z'),
};

View File

@ -1,36 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ShipmentsController } from '@/shipments/shipments.controller';
import { ShipmentsService } from '@/shipments/shipments.service';
describe('ShipmentsController', () => {
let controller: ShipmentsController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ShipmentsController],
})
.useMocker((token) => {
if (token === ShipmentsService) {
return {
getAll: jest.fn().mockResolvedValue([]),
};
}
})
.compile();
controller = module.get<ShipmentsController>(ShipmentsController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
it('should have a method getShipments', () => {
expect(controller.getShipments).toBeDefined();
});
it('should return an object with message: ok', async () => {
await expect(controller.getShipments()).resolves.toEqual({ data: [] });
});
});

View File

@ -1,59 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ShipmentsService } from '@/shipments/shipments.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ShipmentEntity } from '@/entities/shipment.entity';
import { Repository } from 'typeorm';
import { mockShipment } from '@tests/data/tracking.mock';
describe('ShipmentsService', () => {
const shipmentEntityToken = getRepositoryToken(ShipmentEntity);
let service: ShipmentsService;
let repository: Repository<ShipmentEntity>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ShipmentsService],
})
.useMocker((token) => {
switch (token) {
case shipmentEntityToken:
return {
find: jest.fn().mockResolvedValue([]),
save: jest
.fn()
.mockImplementation((shipmentEntity: ShipmentEntity) =>
Promise.resolve(shipmentEntity),
),
};
}
})
.compile();
service = module.get<ShipmentsService>(ShipmentsService);
repository = module.get<Repository<ShipmentEntity>>(shipmentEntityToken);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('should have a getAll method', () => {
expect(service.getAll).toBeDefined();
});
it('should fetch data with relations liveTracking and containers', async () => {
await expect(service.getAll()).resolves.toEqual([]);
expect(repository.find).toHaveBeenCalledWith({
relations: ['liveTracking', 'containers'],
});
});
it('should have an update method', () => {
expect(service.update).toBeDefined();
});
it('should fetch data with relations liveTracking and containers', async () => {
await expect(service.update(mockShipment)).resolves.toEqual(mockShipment);
expect(repository.save).toHaveBeenCalledWith(mockShipment);
});
});

View File

@ -29,6 +29,6 @@ describe('NotificationsService', () => {
it('should have a method send that resolves', async () => {
await expect(
service.send(mockShipment, mockTrackingInfo),
).resolves.not.toThrow();
).resolves.toBeDefined();
});
});

View File

@ -1,118 +0,0 @@
import { mockShipment, mockTrackingInfo } from '@tests/data/tracking.mock';
import { ConsoleNotifier } from '@/tracking/notifications/console.notifier';
import { resetDate, setDate } from '@/utils/fakeDate';
import { TrackingDto } from '@/dtos/tracking.dto';
import { ShipmentEntity } from '@/entities/shipment.entity';
describe('ConsoleNotifier', () => {
beforeEach(() => {
jest.clearAllMocks();
setDate('2023-02-14 14:00:00');
});
afterAll(() => {
resetDate();
jest.clearAllMocks();
});
it('should be defined', () => {
expect(ConsoleNotifier).toBeDefined();
});
it('should be arriving soon if arrivalEstimate is between 0 and 1 days of today', async () => {
const logSpy = jest.spyOn(global.console, 'log').mockImplementation();
const consoleNotifier = new ConsoleNotifier(mockShipment, mockTrackingInfo);
expect(consoleNotifier.isDelayed).toBe(false);
expect(consoleNotifier.daysToArrival).toBeGreaterThan(0);
expect(consoleNotifier.daysToArrival).toBeLessThan(1);
await expect(consoleNotifier.send()).resolves.toBe(true);
expect(logSpy).toHaveBeenCalledWith(
'Send email with the following messages: Your shipment will arrive soon',
);
});
it('should be arriving soon if arrivalEstimate is less than or equal to today', async () => {
const logSpy = jest.spyOn(global.console, 'log').mockImplementation();
const arrivesTodayTrackingInfo: TrackingDto = {
...mockTrackingInfo,
arrivalDateEstimate: new Date(),
};
const consoleNotifier = new ConsoleNotifier(
mockShipment,
arrivesTodayTrackingInfo,
);
expect(consoleNotifier.isDelayed).toBe(false);
expect(consoleNotifier.daysToArrival).toBeLessThanOrEqual(0);
await expect(consoleNotifier.send()).resolves.toBe(true);
expect(logSpy).toHaveBeenCalledWith(
'Send email with the following messages: Your shipment has arrived',
);
});
it('should be delayed if arrivalDateEstimate is more than 1 day after arrivalDateOriginal', async () => {
const logSpy = jest.spyOn(global.console, 'log').mockImplementation();
const trackingDelay = 2;
const newArrivalDate = new Date();
newArrivalDate.setDate(
mockShipment.arrivalDateOriginal.getDate() + trackingDelay,
);
const delayedTrackingInfo: TrackingDto = {
...mockTrackingInfo,
arrivalDateEstimate: newArrivalDate,
};
delayedTrackingInfo.arrivalDateEstimate;
const consoleNotifier = new ConsoleNotifier(
mockShipment,
delayedTrackingInfo,
);
expect(consoleNotifier.isDelayed).toBe(true);
expect(consoleNotifier.daysToArrival).toBe(trackingDelay);
await expect(consoleNotifier.send()).resolves.toBe(true);
expect(logSpy).toHaveBeenCalledTimes(1);
expect(logSpy).toHaveBeenCalledWith(
'Send email with the following messages: Your shipment has been delayed',
);
});
it('should log multiple messages if shipment has arrived but original time has been exceeded by more than 1 day', async () => {
const logSpy = jest.spyOn(global.console, 'log').mockImplementation();
const shipment: ShipmentEntity = {
...mockShipment,
arrivalDateOriginal: new Date('2023-02-12 14:00:00'),
};
const trackingInfo: TrackingDto = {
...mockTrackingInfo,
arrivalDateEstimate: new Date('2023-02-14 14:00:00'),
};
const consoleNotifier = new ConsoleNotifier(shipment, trackingInfo);
expect(consoleNotifier.isDelayed).toBe(true);
expect(consoleNotifier.daysToArrival).toBe(0);
await expect(consoleNotifier.send()).resolves.toBe(true);
expect(logSpy).toHaveBeenCalledWith(
'Send email with the following messages: Your shipment has been delayed\nYour shipment has arrived',
);
});
it('should log multiple messages if shipment will arrive soon but original time has been exceeded by more than 1 day', async () => {
const logSpy = jest.spyOn(global.console, 'log').mockImplementation();
const shipment: ShipmentEntity = {
...mockShipment,
arrivalDateOriginal: new Date('2023-02-12 14:00:00'),
};
const trackingInfo: TrackingDto = {
...mockTrackingInfo,
arrivalDateEstimate: new Date('2023-02-14 15:00:00'),
};
const consoleNotifier = new ConsoleNotifier(shipment, trackingInfo);
expect(consoleNotifier.isDelayed).toBe(true);
expect(consoleNotifier.daysToArrival).toBeGreaterThan(0);
expect(consoleNotifier.daysToArrival).toBeLessThanOrEqual(1);
await expect(consoleNotifier.send()).resolves.toBe(true);
expect(logSpy).toHaveBeenCalledWith(
'Send email with the following messages: Your shipment has been delayed\nYour shipment will arrive soon',
);
});
});

View File

@ -1,14 +0,0 @@
import { mockShipment, mockTrackingInfo } from '@tests/data/tracking.mock';
import { NotifierFactory } from '@/tracking/notifications/notifier.factory';
import { ConsoleNotifier } from '@/tracking/notifications/console.notifier';
describe('NotifierFactory', () => {
it('should be defined', () => {
expect(NotifierFactory).toBeDefined();
});
it('should create a notifier instance', () => {
const factory = new NotifierFactory(mockShipment, mockTrackingInfo);
expect(factory.createNotifier()).toBeInstanceOf(ConsoleNotifier);
});
});

View File

@ -26,7 +26,7 @@ describe('TrackingService', () => {
switch (token) {
case containerEntityToken:
return {
findOne: jest.fn().mockResolvedValue(mockContainerEntity),
findOneOrFail: jest.fn().mockResolvedValue(mockContainerEntity),
};
case ShipmentsService:
return {
@ -55,7 +55,7 @@ describe('TrackingService', () => {
it('should have a track method that returns true', async () => {
await expect(trackingService.track(mockTrackingInfo)).resolves.toBe(true);
expect(containerEntityRepository.findOne).toHaveBeenCalledWith({
expect(containerEntityRepository.findOneOrFail).toHaveBeenCalledWith({
relations: ['shipment'],
where: {
containerNumber: mockTrackingInfo.containerNumber,
@ -83,21 +83,16 @@ describe('TrackingService', () => {
};
jest
.spyOn(containerEntityRepository, 'findOne')
.mockResolvedValueOnce(null);
await expect(trackingService.track(mockTrackingInfo)).rejects.toThrow(
'Container not found',
);
jest
.spyOn(containerEntityRepository, 'findOne')
.spyOn(containerEntityRepository, 'findOneOrFail')
.mockResolvedValueOnce(mockShipmentNotFound);
await expect(trackingService.track(mockTrackingInfo)).rejects.toThrow(
'Shipment not found',
);
expect(notificationsService.send).toHaveBeenCalledTimes(0);
expect(shipmentsService.update).toHaveBeenCalledTimes(0);
jest
.spyOn(containerEntityRepository, 'findOne')
.spyOn(containerEntityRepository, 'findOneOrFail')
.mockResolvedValueOnce(mockShipmentCarrierNameMismatch);
await expect(trackingService.track(mockTrackingInfo)).rejects.toThrow(
'CarrierName does not match',

View File

@ -17,24 +17,11 @@ describe('uuidTransformer util', () => {
expect(transformer.from(null)).toBe(NIL);
});
it('From method should throw an error if paring an invalid length buffer', () => {
expect(() => transformer.from(Buffer.alloc(15))).toThrow();
});
it('From method should return a nil uuid if empty 16 length buffer is passed', () => {
expect(transformer.from(Buffer.alloc(16))).toBe(NIL);
});
it('From and To methods should be each others inverse', () => {
const uuid = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
expect(transformer.from(transformer.to(uuid))).toBe(uuid);
});
it('To method should return a buffer matching the uuid', () => {
expect(transformer.to(NIL)).toEqual(Buffer.alloc(16));
});
it('To method throw an error if passing a string that does not match a uuid', () => {
expect(() => transformer.to('test')).toThrow();
});
});

View File

@ -1,7 +1,5 @@
POST http://localhost:3000/tracking
Accept: application/json
Content-Type: application/json
Authorization: eG5nVnZGaWtCMFN6NjRRaWQ2TUJsUTJWaDpjeGg1R3FKRUl0UTlzSGRQdElGMGg0bFJp
{
"carrierName": "Evergreen",
@ -10,9 +8,3 @@ Authorization: eG5nVnZGaWtCMFN6NjRRaWQ2TUJsUTJWaDpjeGg1R3FKRUl0UTlzSGRQdElGMGg0b
"arrivalDateEstimate": "2023-02-14T15:00:00.000Z",
"containerNumber": "EGLU866139144"
}
###
GET http://localhost:3000/shipments
Accept: application/json
Authorization: eG5nVnZGaWtCMFN6NjRRaWQ2TUJsUTJWaDpjeGg1R3FKRUl0UTlzSGRQdElGMGg0bFJp