├── mocha.opts ├── tsconfig.build.json ├── .editorconfig ├── test ├── test-utils │ ├── CustomSinonMatchers.ts │ ├── WrongArgumentsError.ts │ ├── simulation │ │ ├── SimulationServer.ts │ │ ├── TestSimulationServer.ts │ │ ├── Simulation.ts │ │ └── DynamicSimulationDataInterpreter.ts │ ├── DocumentDbTestUtil.ts │ ├── ValidationErrorTestUtil.ts │ └── TestRepository.ts ├── tslint.json ├── int │ ├── global-test-setup.spec.ts │ ├── services │ │ ├── VehicleServiceDatabaseInt.spec.ts │ │ ├── backends │ │ │ └── DamageService.spec.ts │ │ └── VehicleServiceComponent.spec.ts │ └── controller │ │ └── VehicleEndpoint.spec.ts ├── data │ └── rest │ │ └── simulation │ │ ├── TestDynamicInterpreterInteraction.ts │ │ └── DamageInteractions.ts ├── contract │ ├── contract │ │ └── pacts │ │ │ └── vehicle-service-damage-service.json │ └── damageService │ │ └── GetDamageStateByVehicleIdContract.spec.ts └── unit │ └── services │ └── VehicleService.spec.ts ├── src ├── errors │ ├── UnexpectedServiceError.ts │ ├── RepositoryError.ts │ ├── DbQueryError.ts │ └── HttpError.ts ├── persistence │ ├── common │ │ ├── IRepository.ts │ │ ├── stored-procedures │ │ │ ├── BulkDeleteStoredProcedure.ts │ │ │ └── bulkDeleteAll.ts │ │ ├── DocumentClientFactory.ts │ │ ├── DatabaseUtils.ts │ │ └── BaseCRUDRepository.ts │ ├── VehicleRepository.ts │ └── entities │ │ └── VehicleEntity.ts ├── util │ └── ValidationErrorUtil.ts ├── models │ └── VehicleDto.ts ├── common │ └── config.ts ├── Server.ts ├── App.ts ├── services │ ├── backends │ │ └── DamageService.ts │ └── VehicleService.ts ├── controller │ └── VehiclesController.ts └── middlewares │ ├── AsyncControllerHandler.ts │ └── ErrorHandler.ts ├── .nycrc ├── .gitignore ├── tsconfig.json ├── tslint.json ├── README.md ├── package.json └── LICENSE /mocha.opts: -------------------------------------------------------------------------------- 1 | --require ts-node/register 2 | --require source-map-support/register 3 | --sort 4 | --full-trace 5 | --exit -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": [ 4 | "test/**/*.ts" 5 | ], 6 | "compilerOptions": { 7 | "typeRoots": [ 8 | "./node_modules/@types" 9 | ] 10 | } 11 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: http://EditorConfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | indent_style = space 11 | indent_size = 4 12 | tab_width = 2 13 | -------------------------------------------------------------------------------- /test/test-utils/CustomSinonMatchers.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Custom matchers for sinon. 3 | */ 4 | export class CustomSinonMatchers { 5 | public static MATCH_UUID_4_MESSAGE = 'uuid.v4()'; 6 | public static matchUUID4(value: any): boolean { 7 | return /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i.test(value); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/errors/UnexpectedServiceError.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This Error indicates that a unexpected error in a service occured. 3 | */ 4 | export class UnexpectedServiceError extends Error { 5 | constructor(message?: string) { 6 | super(message); 7 | Object.setPrototypeOf(this, new.target.prototype); 8 | this.name = new.target.name; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/errors/RepositoryError.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This Error indicates that a documentdb query error occurred. 3 | */ 4 | export class RepositoryError extends Error { 5 | 6 | constructor(message?: string, public retry?: boolean) { 7 | super(message); 8 | Object.setPrototypeOf(this, new.target.prototype); 9 | this.name = new.target.name; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/persistence/common/IRepository.ts: -------------------------------------------------------------------------------- 1 | import { AbstractMeta } from 'documentdb'; 2 | 3 | /** 4 | * Common Repository 5 | */ 6 | export interface IRepository { 7 | create(obj: T): Promise; 8 | findOne(id: string): Promise; 9 | findAll(): Promise; 10 | remove(obj: T): Promise; 11 | removeAll(): Promise; 12 | } 13 | -------------------------------------------------------------------------------- /test/test-utils/WrongArgumentsError.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This Error indicates that a stub was called with wrong arguments. 3 | */ 4 | export class WrongArgumentsError extends Error { 5 | 6 | constructor(message = 'Stub was called with wrong arguments.') { 7 | super(message); 8 | Object.setPrototypeOf(this, new.target.prototype); 9 | this.name = new.target.name; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /test/test-utils/simulation/SimulationServer.ts: -------------------------------------------------------------------------------- 1 | import { createServer } from 'http'; 2 | import app from './Simulation'; 3 | 4 | /** 5 | * Create HTTP server. 6 | */ 7 | const port = '8080'; 8 | app.set('port', port); 9 | const server = createServer(app); 10 | server.listen(app.get('port'), () => { 11 | // tslint:disable-next-line:no-console 12 | console.log('Simulation server listening on port ' + app.get('port')); 13 | }); 14 | -------------------------------------------------------------------------------- /test/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "max-line-length": [ 5 | true, 6 | 300 7 | ], 8 | "no-duplicate-imports":false, 9 | "ordered-imports":false, 10 | "no-submodule-imports":false, 11 | "no-unused-expression":false, 12 | "no-implicit-dependencies": [true, "dev"], 13 | "object-literal-sort-keys":false 14 | } 15 | } -------------------------------------------------------------------------------- /.nycrc: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | "src/**/*.ts" 4 | ], 5 | "exclude": [ 6 | "**/*.d.ts" 7 | ], 8 | "extension": [ 9 | ".ts" 10 | ], 11 | "require": [ 12 | "ts-node/register" 13 | ], 14 | "reporter": [ 15 | "html" 16 | ], 17 | "report-dir": "test/reports/coverage", 18 | "sourceMap": true, 19 | "instrument": true, 20 | "all": true, 21 | "cache": true 22 | } -------------------------------------------------------------------------------- /src/persistence/common/stored-procedures/BulkDeleteStoredProcedure.ts: -------------------------------------------------------------------------------- 1 | import { Procedure } from 'documentdb'; 2 | import { bulkDeleteAll } from './bulkDeleteAll'; 3 | 4 | export const bulkDeleteProc: Procedure = { 5 | id: 'bulkDelete', 6 | serverScript: bulkDeleteAll, 7 | }; 8 | 9 | /** 10 | * The object that will be returned by the stored procedure 11 | */ 12 | export interface IBulkDeleteResponseBody { 13 | deleted: number; 14 | continuation: boolean; 15 | } 16 | -------------------------------------------------------------------------------- /src/persistence/VehicleRepository.ts: -------------------------------------------------------------------------------- 1 | import { BaseCRUDRepository } from './common/BaseCRUDRepository'; 2 | import { IVehicleEntity, VehicleEntity } from './entities/VehicleEntity'; 3 | 4 | /** 5 | * The vehicle repository. CRUD operations and more on the VehicleEntity in the documentdb. 6 | */ 7 | class VehicleRepository extends BaseCRUDRepository { 8 | constructor() { 9 | super('vehicles', VehicleEntity); 10 | } 11 | } 12 | 13 | export default new VehicleRepository(); 14 | -------------------------------------------------------------------------------- /src/errors/DbQueryError.ts: -------------------------------------------------------------------------------- 1 | import { QueryError } from 'documentdb'; 2 | 3 | /** 4 | * This Error indicates that a documentdb query error occurred. 5 | */ 6 | export class DbQueryError extends Error implements QueryError { 7 | 8 | public code: any; 9 | public body: any; 10 | 11 | constructor(err: QueryError, message?: string) { 12 | super(message); 13 | this.code = err.code; 14 | this.body = err.body; 15 | Object.setPrototypeOf(this, new.target.prototype); 16 | this.name = new.target.name; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /spec/tsc-out 4 | /test/reports 5 | .nyc_output 6 | /docs 7 | /test/contract/contract/logs/pact.log 8 | 9 | # dependencies 10 | /node_modules 11 | 12 | # IDEs and editors 13 | /.idea 14 | .project 15 | .classpath 16 | .c9/ 17 | *.launch 18 | .settings/ 19 | *.sublime-workspace 20 | 21 | # IDE - VSCode 22 | .vscode/ 23 | !.vscode/settings.json 24 | !.vscode/tasks.json 25 | !.vscode/launch.json 26 | !.vscode/extensions.json 27 | 28 | # misc 29 | npm-debug.log 30 | testem.log 31 | 32 | # System Files 33 | .DS_Store 34 | Thumbs.db 35 | 36 | # Gradle files 37 | **/.gradle 38 | -------------------------------------------------------------------------------- /src/errors/HttpError.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This Error is for indicating which http error should be send. 3 | */ 4 | export class HttpError extends Error { 5 | 6 | public statusCode: AllowedStatus; 7 | 8 | constructor(statusCode: AllowedStatus, message?: string) { 9 | super(message); 10 | this.statusCode = statusCode; 11 | Object.setPrototypeOf(this, new.target.prototype); 12 | this.name = new.target.name; 13 | } 14 | 15 | public toString(): string { 16 | return `${this.name}(${this.statusCode}): ${this.message}`; 17 | } 18 | } 19 | 20 | type AllowedStatus = 200 | 400 | 401 | 404 | 409 | 500 | 503; 21 | -------------------------------------------------------------------------------- /test/test-utils/DocumentDbTestUtil.ts: -------------------------------------------------------------------------------- 1 | import { UriFactory, DocumentClient } from 'documentdb'; 2 | import { DATABASE_ID, DATABASE_URL, DATABASE_MASTER_KEY } from '../../src/common/config'; 3 | 4 | /** 5 | * Util for document db usage in the tests. 6 | */ 7 | export class DocumentDbTestUtil { 8 | public static async deleteTestDatabase(): Promise { 9 | const documentClient = new DocumentClient(DATABASE_URL, { masterKey: DATABASE_MASTER_KEY }); 10 | return new Promise((res, rej) => { 11 | documentClient.deleteDatabase(UriFactory.createDatabaseUri(DATABASE_ID), (err) => { 12 | err ? rej(err) : res(); 13 | }); 14 | }); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /test/test-utils/simulation/TestSimulationServer.ts: -------------------------------------------------------------------------------- 1 | import { createServer, Server } from 'http'; 2 | import app from './Simulation'; 3 | 4 | /** 5 | * Simulation server for the tests. 6 | */ 7 | export class TestSimulationServer { 8 | 9 | private server: Server; 10 | 11 | constructor(port = '8080') { 12 | app.set('port', port); 13 | } 14 | 15 | public async create(): Promise { 16 | this.server = createServer(app); 17 | await new Promise((resolve, reject) => { 18 | this.server.listen(app.get('port'), () => { 19 | resolve(); 20 | }); 21 | }); 22 | } 23 | 24 | public async close(): Promise { 25 | await new Promise((resolve, reject) => { 26 | this.server.close(resolve); 27 | }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/util/ValidationErrorUtil.ts: -------------------------------------------------------------------------------- 1 | import { ValidationError } from 'class-validator'; 2 | 3 | /** 4 | * Utility functions regarding ValidationErrors. 5 | */ 6 | export class ValidationErrorUtil { 7 | /** 8 | * Checks if the given object is an Array of ValidationErrors. 9 | * @param e The error. 10 | * @param logMeta The log meta data 11 | */ 12 | public static async checkForValidationErrors(e: any): Promise { 13 | if (Array.isArray(e) && e.length > 0 && e.every((error) => Array.isArray(error))) { 14 | return (await Promise.all((e as any[][]).map((errors: any[]) => ValidationErrorUtil.checkForValidationErrors(errors)))).every((result) => result); 15 | } else { 16 | return (Array.isArray(e) && e.length > 0 && e.every((error) => error instanceof ValidationError)); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "noImplicitAny": true, 6 | "moduleResolution": "node", 7 | "sourceMap": true, 8 | "experimentalDecorators": true, 9 | "removeComments": true, 10 | "noEmitOnError": true, 11 | "strictNullChecks": true, 12 | "allowJs": true, 13 | "pretty": true, 14 | "outDir": "dist", 15 | "lib": [ 16 | "es2017", 17 | "dom" 18 | ], 19 | "plugins": [ 20 | { 21 | "name": "tslint-language-service", 22 | "disableNoUnusedVariableRule": false 23 | } 24 | ], 25 | "typeRoots": [ 26 | "./typings", 27 | "./node_modules/@types" 28 | ] 29 | }, 30 | "include": [ 31 | "src/**/*.ts", 32 | "test/**/*.ts" 33 | ] 34 | } -------------------------------------------------------------------------------- /src/models/VehicleDto.ts: -------------------------------------------------------------------------------- 1 | import { Exclude, Expose } from 'class-transformer'; 2 | import 'reflect-metadata'; 3 | import { COLORS } from '../persistence/entities/VehicleEntity'; 4 | 5 | /** 6 | * The external representation of a vehicle. 7 | */ 8 | @Exclude() 9 | export class VehicleDto { 10 | @Expose() 11 | public id: string; 12 | 13 | @Expose() 14 | public color: COLORS; 15 | 16 | @Expose() 17 | public damaged?: boolean; 18 | 19 | constructor(id: string, color: COLORS, damaged?: boolean) { 20 | this.id = id; 21 | this.color = color; 22 | if (damaged !== undefined) { 23 | this.damaged = damaged; 24 | } 25 | } 26 | 27 | public toString(): string { 28 | return this.damaged !== undefined ? 29 | `${this.constructor.name}{id: ${this.id}, color: ${this.color}, damaged: ${this.damaged}}` : 30 | `${this.constructor.name}{id: ${this.id}, color: ${this.color}}`; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/common/config.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * General 3 | */ 4 | export const PORT: string = process.env.PORT || '3000'; 5 | export const REQUEST_TIMEOUT: number = 6000; 6 | export const TIMEOUT: number = process.env.TIMEOUT !== undefined ? Number.parseInt(process.env.TIMEOUT!) : 10000; 7 | export const AUTHORIZATION_HEADER: string = 'Authorization'; 8 | 9 | /** 10 | * Database 11 | */ 12 | export const DATABASE_URL: string = process.env.DATABASE_URL || ''; 13 | export const DATABASE_MASTER_KEY: string = process.env.DATABASE_MASTER_KEY || ''; 14 | export const DATABASE_ID: string = process.env.DATABASE_ID || 'test-' + Math.round(Math.random() * 1000); 15 | export const MAX_DATABASE_QUERY_RETRIES: number = 3; 16 | export const DATABASE_COLLECTION_THROUGHPUT: number = 400; 17 | 18 | /** 19 | * Damage backend 20 | */ 21 | export const DAMAGE_ENDPOINT: string = process.env.NODE_ENV === 'test' ? 'http://localhost:8080/damage' : 'https://damage.example.com'; 22 | export const BASIC_AUTH: string = process.env.DAMAGE_BACKEND_BASIC_AUTH || 'AUTH'; 23 | -------------------------------------------------------------------------------- /src/Server.ts: -------------------------------------------------------------------------------- 1 | import { createServer } from 'http'; 2 | import App from './App'; 3 | import { PORT } from './common/config'; 4 | import VehicleRepository from './persistence/VehicleRepository'; 5 | 6 | const port = PORT; 7 | 8 | const server = createServer(App); 9 | 10 | server.listen(port); 11 | 12 | server.on('listening', onListening); 13 | server.on('error', onError); 14 | 15 | function onListening(): void { 16 | // tslint:disable-next-line:no-console 17 | console.log(`Running on port ${PORT}`); 18 | initializeRepositories().catch((e) => { 19 | throw e; 20 | }); 21 | } 22 | 23 | async function initializeRepositories() { 24 | VehicleRepository.findOne('1'); 25 | } 26 | 27 | function onError(error: any) { 28 | if (error.syscall !== 'listen') { 29 | throw error; 30 | } 31 | 32 | // handle specific listen errors with friendly messages 33 | switch (error.code) { 34 | case 'EACCES': 35 | case 'EADDRINUSE': 36 | process.exit(1); 37 | break; 38 | default: 39 | throw error; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /test/int/global-test-setup.spec.ts: -------------------------------------------------------------------------------- 1 | import { DocumentDbTestUtil } from '../test-utils/DocumentDbTestUtil'; 2 | import VehicleRepository from '../../src/persistence/VehicleRepository'; 3 | import { TestSimulationServer } from '../test-utils/simulation/TestSimulationServer'; 4 | 5 | /** 6 | * This is the global integration test setup. 7 | * Mocha provides global hooks to call before all suites (before / after) and before each test (beforeEach / afterEach). 8 | */ 9 | 10 | let server: TestSimulationServer; 11 | 12 | before(async () => { 13 | // Init test simulation server 14 | server = new TestSimulationServer(); 15 | await server.create(); 16 | 17 | // Init Repositories and create the database by the first call to the repository 18 | await VehicleRepository.findOne(''); 19 | }); 20 | 21 | after(async () => { 22 | // Shut down test simulation server 23 | await server.close(); 24 | 25 | // Delete the testing Database 26 | await DocumentDbTestUtil.deleteTestDatabase(); 27 | }); 28 | 29 | afterEach(async () => { 30 | // Clean Repositories after each test. 31 | await VehicleRepository.removeAll(); 32 | }); 33 | -------------------------------------------------------------------------------- /src/persistence/entities/VehicleEntity.ts: -------------------------------------------------------------------------------- 1 | import { IsEnum, IsNotEmpty, IsString } from 'class-validator'; 2 | import { AbstractMeta, NewDocument } from 'documentdb'; 3 | import 'reflect-metadata'; 4 | 5 | /** 6 | * Available colors 7 | */ 8 | export enum COLORS { 9 | RED, 10 | YELLOW, 11 | BLUE, 12 | GREEN, 13 | } 14 | 15 | /** 16 | * The vehicle entity. 17 | */ 18 | export class VehicleEntity implements IVehicleEntity { 19 | 20 | @IsNotEmpty() 21 | @IsString() 22 | public id: string; 23 | 24 | @IsNotEmpty() 25 | @IsEnum(COLORS) 26 | public color: COLORS; 27 | 28 | public _self: string; 29 | public _ts: number; 30 | public _rid?: string; 31 | public _etag?: string; 32 | public _attachments?: string; 33 | public ttl?: number; 34 | 35 | /** 36 | * Constructs the VehicleEntity 37 | * @param id The id. 38 | * @param color The color. 39 | */ 40 | constructor(id: string, color: COLORS) { 41 | this.id = id; 42 | this.color = color; 43 | } 44 | 45 | public toString(): string { 46 | return `${this.constructor.name}{id: ${this.id}}`; 47 | } 48 | } 49 | 50 | /** 51 | * The vehicle interface. 52 | */ 53 | export interface IVehicleEntity extends AbstractMeta, NewDocument { 54 | color: COLORS; 55 | } 56 | -------------------------------------------------------------------------------- /test/test-utils/ValidationErrorTestUtil.ts: -------------------------------------------------------------------------------- 1 | import { ValidationError } from 'class-validator'; 2 | 3 | /** 4 | * Util class for helping with ValidationErrors to be handled easier. 5 | */ 6 | export class ValidationErrorTestUtil { 7 | public static validationErrorToStringArray(validationErrors: ValidationError[] | ValidationError[][]): string[] | string[][] { 8 | if ((validationErrors as ValidationError[][]).every((e: ValidationError[]) => Array.isArray(e))) { 9 | return (validationErrors as ValidationError[][]).map((val: ValidationError[]) => ValidationErrorTestUtil.validationErrorToStringArray(val)) as string[][]; 10 | } else { 11 | return (validationErrors as ValidationError[]).reduce((accumulator: string[], currentError: ValidationError): string[] => { 12 | if (currentError.constraints === undefined && currentError.children !== undefined) { 13 | accumulator.push(...ValidationErrorTestUtil.validationErrorToStringArray(currentError.children) as string[]); 14 | } 15 | if (currentError.constraints !== undefined) { 16 | accumulator.push(...Object.values(currentError.constraints).map((value) => value + '.')); 17 | } 18 | return accumulator; 19 | }, []); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultSeverity": "error", 3 | "extends": "tslint:latest", 4 | "rulesDirectory": [], 5 | "rules": { 6 | "max-line-length": [ 7 | true, 8 | 170 9 | ], 10 | "quotemark": [ 11 | true, 12 | "single", 13 | "avoid-escape", 14 | "avoid-template" 15 | ], 16 | "max-classes-per-file": [true, 8], 17 | "completed-docs": [ 18 | true, 19 | { 20 | "enums": true, 21 | "classes": { 22 | "visibilities": [ 23 | "all" 24 | ] 25 | }, 26 | "interfaces": { 27 | "visibilities": [ 28 | "all" 29 | ] 30 | }, 31 | "functions": { 32 | "visibilities": [ 33 | "exported" 34 | ] 35 | }, 36 | "methods": { 37 | "locations": "all", 38 | "privacies": [ 39 | "public", 40 | "protected" 41 | ] 42 | } 43 | } 44 | ], 45 | "variable-name": [ 46 | true, 47 | "check-format", 48 | "allow-leading-underscore" 49 | ], 50 | "no-unused-variable": [ 51 | true 52 | ] 53 | } 54 | } -------------------------------------------------------------------------------- /test/test-utils/simulation/Simulation.ts: -------------------------------------------------------------------------------- 1 | import { json, urlencoded } from 'body-parser'; 2 | import * as express from 'express'; 3 | import { Request, Response, NextFunction } from 'express'; 4 | import { DynamicSimulationDataInterpreter } from './DynamicSimulationDataInterpreter'; 5 | import { TestDynamicInterpreterInteraction } from '../../data/rest/simulation/TestDynamicInterpreterInteraction'; 6 | import { DamageInteractions } from '../../data/rest/simulation/DamageInteractions'; 7 | import { INTERNAL_SERVER_ERROR } from 'http-status-codes'; 8 | 9 | /** 10 | * Create Express server. 11 | */ 12 | const app = express(); 13 | 14 | /** 15 | * Express configuration. 16 | */ 17 | app.use(urlencoded({ extended: true })); 18 | app.use(json()); 19 | 20 | /** 21 | * Test Route 22 | */ 23 | const testRouter = (req: Request, res: Response) => { 24 | DynamicSimulationDataInterpreter.interpret(TestDynamicInterpreterInteraction, req, res); 25 | }; 26 | 27 | /** 28 | * Damage Routes 29 | */ 30 | const damageRouter = (req: Request, res: Response) => { 31 | DynamicSimulationDataInterpreter.interpret(DamageInteractions, req, res); 32 | }; 33 | 34 | /** 35 | * ROUTES registration 36 | */ 37 | app.post('/test/:userid/:anyOtherParam', testRouter); 38 | app.get('/damage/vehicle/:id', damageRouter); 39 | 40 | app.use((err: any, req: Request, res: Response, next: NextFunction) => { 41 | // tslint:disable-next-line:no-console 42 | console.error(err); 43 | res.status(INTERNAL_SERVER_ERROR).send(); 44 | }); 45 | 46 | export default app; 47 | -------------------------------------------------------------------------------- /src/App.ts: -------------------------------------------------------------------------------- 1 | import { json, urlencoded } from 'body-parser'; 2 | import { Application } from 'express'; 3 | // tslint:disable-next-line:no-duplicate-imports 4 | import * as express from 'express'; 5 | import 'reflect-metadata'; // needed for class-transformer 6 | import { PORT } from './common/config'; 7 | import { VehiclesController } from './controller/VehiclesController'; 8 | import { AsyncControllerHandler } from './middlewares/AsyncControllerHandler'; 9 | import { ErrorHandler } from './middlewares/ErrorHandler'; 10 | 11 | /** 12 | * Configures and utilizes the express application. 13 | */ 14 | class App { 15 | 16 | public express: Application; 17 | 18 | constructor() { 19 | this.express = express(); 20 | this.middleware(); 21 | this.routes(); 22 | this.final(); 23 | } 24 | 25 | private final(): void { 26 | this.express.use(ErrorHandler.handleNotFound); 27 | this.express.use(ErrorHandler.handleErrors); 28 | this.express.set('port', PORT); 29 | } 30 | 31 | private middleware(): void { 32 | this.express.use(urlencoded({ extended: false })); 33 | this.express.use(json()); 34 | } 35 | 36 | private routes(): void { 37 | this.express.get('/vehicles', AsyncControllerHandler.control(VehiclesController.list)); 38 | this.express.get('/vehicles/:id', AsyncControllerHandler.control(VehiclesController.get)); 39 | this.express.post('/vehicles', AsyncControllerHandler.control(VehiclesController.post)); 40 | } 41 | } 42 | 43 | export default new App().express; 44 | -------------------------------------------------------------------------------- /test/data/rest/simulation/TestDynamicInterpreterInteraction.ts: -------------------------------------------------------------------------------- 1 | import { IInteraction } from '../../../test-utils/simulation/DynamicSimulationDataInterpreter'; 2 | 3 | /** 4 | * This is only for testing purpose of the dynamic simulation data interpreter. 5 | */ 6 | export class TestDynamicInterpreterInteraction { 7 | public static TEST_ONE: IInteraction = { 8 | request: { 9 | params: { 10 | userid: 'testuser', 11 | anyOtherParam: 'test', 12 | }, 13 | queryParams: { 14 | queryParamOne: '34', 15 | anotherQuery: 'test', 16 | }, 17 | headers: { 18 | 'X-ApplicationName': 'test-app', 19 | 'testHeader': 'test', 20 | }, 21 | body: { 22 | test: 'test', 23 | }, 24 | }, 25 | response: { 26 | status: 200, 27 | headers: { 28 | 'test-1': 'test', 29 | 'test2': 'test', 30 | }, 31 | body: { 32 | test: 'test', 33 | data: [ '1', 1 ], 34 | }, 35 | }, 36 | }; 37 | 38 | public static TEST_TWO: IInteraction = { 39 | request: { 40 | params: { 41 | userid: 'testuser', 42 | anyOtherParam: 'test', 43 | }, 44 | headers: { 45 | 'X-ApplicationName': 'test-app', 46 | 'otherHeader': /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, 47 | }, 48 | }, 49 | response: { 50 | status: 200, 51 | }, 52 | }; 53 | } 54 | -------------------------------------------------------------------------------- /src/services/backends/DamageService.ts: -------------------------------------------------------------------------------- 1 | import { Exclude, Expose } from 'class-transformer'; 2 | import { transformAndValidate } from 'class-transformer-validator'; 3 | import { IsBoolean } from 'class-validator'; 4 | import { get, OptionsWithUrl } from 'request-promise-native'; 5 | import { AUTHORIZATION_HEADER, BASIC_AUTH, DAMAGE_ENDPOINT, REQUEST_TIMEOUT } from '../../common/config'; 6 | import { UnexpectedServiceError } from '../../errors/UnexpectedServiceError'; 7 | import { ErrorHandler } from '../../middlewares/ErrorHandler'; 8 | 9 | /** 10 | * Handles everything regarding consuming Damage Service routes 11 | */ 12 | export class DamageService { 13 | 14 | /** 15 | * Sends a get request to the damage endpoint and retrieves the damage state for a given vehicle id. 16 | * @param vehicleId The vehicle id, the damaged state should be retrieved for. 17 | */ 18 | public static async getDamageState(vehicleId: string): Promise { 19 | try { 20 | const options: OptionsWithUrl = { 21 | headers: { 22 | [AUTHORIZATION_HEADER]: `Basic ${BASIC_AUTH}`, 23 | }, 24 | timeout: REQUEST_TIMEOUT, 25 | url: `${DAMAGE_ENDPOINT}/vehicle/${vehicleId}`, 26 | }; 27 | const response = await transformAndValidate(DamageStateResponse , (JSON.parse(await get(options)) as object)); 28 | return response.damaged; 29 | } catch (e) { 30 | await ErrorHandler.handleServiceErrors(e); 31 | } 32 | throw new UnexpectedServiceError(); 33 | } 34 | } 35 | 36 | /** 37 | * The expected response from the damage state call. 38 | */ 39 | @Exclude() 40 | class DamageStateResponse { 41 | @Expose() 42 | @IsBoolean() 43 | public damaged: boolean; 44 | } 45 | -------------------------------------------------------------------------------- /src/controller/VehiclesController.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response } from 'express'; 2 | import { NOT_FOUND, OK } from 'http-status-codes'; 3 | import { HttpError } from '../errors/HttpError'; 4 | import { ControllerResponse, IControllerResponse } from '../middlewares/AsyncControllerHandler'; 5 | import { VehicleDto } from '../models/VehicleDto'; 6 | import { VehicleService } from '../services/VehicleService'; 7 | 8 | /** 9 | * Serves an vehicle response. 10 | */ 11 | export class VehiclesController { 12 | 13 | /** 14 | * Serves the one vehicle on GET requests. 15 | * @param req The request. 16 | * @param res The response. 17 | */ 18 | public static async get(req: Request, res: Response): Promise { 19 | let id: string; 20 | if (req.params.id && req.params.id !== '') { 21 | id = req.params.id; 22 | } else { 23 | throw new HttpError(NOT_FOUND); 24 | } 25 | const vehicle: VehicleDto = await VehicleService.getDetailedVehicle(id); 26 | return new ControllerResponse(OK, vehicle); 27 | } 28 | 29 | /** 30 | * Serves all vehicles on GET requests. 31 | * @param req The request. 32 | * @param res The response. 33 | */ 34 | public static async list(req: Request, res: Response): Promise { 35 | const vehicles: VehicleDto[] = await VehicleService.listAllVehicles(); 36 | return new ControllerResponse(OK, vehicles); 37 | } 38 | 39 | /** 40 | * Creates a vehicle on POST requests and serves it as response. 41 | * @param req The request. 42 | * @param res The response. 43 | */ 44 | public static async post(req: Request, res: Response): Promise { 45 | const vehicle: VehicleDto = await VehicleService.create(req.body); 46 | return new ControllerResponse(OK, vehicle); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Microservices testing with Node.js and TypeScript 2 | 3 | This demo repository corresponds to [this blog post](https://blog.novatec-gmbh.de/modern-microservice-testing-concept-real-world-example). It shows a real world example for realization of the testing pyramid with TypeScript and Node.js in combination with Microsoft Azure. 4 | 5 | Basically the project is serving a RESTful API for dealing with vehicles. The idea behind it, is that a vehicle can be created and retrieved. Moreover a list of all vehicles can be retrieved. 6 | 7 | In order to demonstrate a RESTful microservice communication, the vehicle service can get more detailed information on the damage status from another service in this example. This looks like the following: 8 | 9 | 10 | 11 | ## Prerequisites 12 | 13 | Setup an Microsoft Azure CosmosDB Acoount with SQL API and set the following environment variables to the corresponding values of your created DB in order to be able to run the application: 14 | 15 | - ```DATABASE_URL``` 16 | - ```DATABASE_MASTER_KEY``` 17 | 18 | ## Commands / scripts 19 | 20 | Following npm scripts can be used to run, test and build the project: 21 | 22 | - ```start``` starts the compiled js output of the TypeScript compiler inside of an Azure App Service instance (do not use locally). 23 | - ```build``` compiles and lints the project. 24 | - ```serve``` starts the compiled js output of the TypeScript compiler locally. 25 | - ```serve-sim``` starts the compiled js output of the TypeScript compiler locally and connect to the simulation server (use this in combination with the simulation script in order to run the app locally). 26 | - ```ts:build``` compiles the project. 27 | - ```ts:doc``` creates the TypeDoc. 28 | - ```test``` runs all tests. 29 | - ```test:unit``` runs all unit tests. 30 | - ```test:int``` runs all integration tests. 31 | - ```test:contract``` runs all contract tests. 32 | - ```simulation``` starts the simulation server. 33 | -------------------------------------------------------------------------------- /src/persistence/common/DocumentClientFactory.ts: -------------------------------------------------------------------------------- 1 | import { ConnectionPolicy, DocumentClient, MediaReadMode, RetryOptions } from 'documentdb'; 2 | import { DATABASE_MASTER_KEY, DATABASE_URL } from '../../common/config'; 3 | 4 | /** 5 | * Returns the documentdb document client. 6 | */ 7 | class DocumentClientFactory { 8 | 9 | public documentClient: DocumentClient; 10 | 11 | constructor() { 12 | this.documentClient = new DocumentClient(DATABASE_URL, 13 | { masterKey: DATABASE_MASTER_KEY }, 14 | new ConnPolicy(8000, 8000, new RetOptions(5, 1)), 15 | 'Session', 16 | ); 17 | } 18 | } 19 | 20 | // tslint:disable:variable-name 21 | 22 | /** 23 | * Represents a ConnectionPolicy for DocumentClient. 24 | */ 25 | class ConnPolicy implements ConnectionPolicy { 26 | public ConnectionMode: number; 27 | public RetryOptions: RetryOptions; 28 | public MediaReadMode: MediaReadMode; 29 | 30 | constructor(public MediaRequestTimeout: number = 300000, public RequestTimeout: number = 60000, retryOptions?: RetryOptions, 31 | mediaReadMode: MediaReadMode = 'Buffered', public EnableEndpointDiscovery: boolean = true, public PreferredLocations: any[] = [], 32 | public DisableSSLVerification: boolean = false) { 33 | this.ConnectionMode = 0; // Gateway at the moment this is the only option. DirectMode would be much nicer and better in performance. 34 | this.RetryOptions = retryOptions !== undefined ? retryOptions : new RetOptions(); 35 | this.MediaReadMode = mediaReadMode; 36 | } 37 | } 38 | 39 | /** 40 | * Represents the RetryOptions object for ConnectionPolicy. 41 | */ 42 | class RetOptions implements RetryOptions { 43 | constructor(public MaxRetryAttemptCount: number = 9, public MaxWaitTimeInSeconds: number = 30, public FixedRetryIntervalInMilliseconds?: number) { } 44 | } 45 | 46 | export default new DocumentClientFactory().documentClient; 47 | -------------------------------------------------------------------------------- /test/data/rest/simulation/DamageInteractions.ts: -------------------------------------------------------------------------------- 1 | import { IInteraction } from '../../../test-utils/simulation/DynamicSimulationDataInterpreter'; 2 | import { AUTHORIZATION_HEADER, BASIC_AUTH } from '../../../../src/common/config'; 3 | import { OK, NOT_FOUND } from 'http-status-codes'; 4 | 5 | /** 6 | * Provides Damage endpoint possible interactions 7 | * @version v1 - https://damage.example.com 8 | */ 9 | export class DamageInteractions { 10 | public static VALID_INTERACTION_ID_1: IInteraction = { 11 | request: { 12 | params: { 13 | id: '1', 14 | }, 15 | headers: { 16 | [AUTHORIZATION_HEADER]: `Basic ${BASIC_AUTH}`, 17 | }, 18 | }, 19 | response: { 20 | status: OK, 21 | body: { 22 | damaged: false, 23 | }, 24 | }, 25 | }; 26 | 27 | public static VALID_INTERACTION_ID_2: IInteraction = { 28 | request: { 29 | params: { 30 | id: '2', 31 | }, 32 | headers: { 33 | [AUTHORIZATION_HEADER]: `Basic ${BASIC_AUTH}`, 34 | }, 35 | }, 36 | response: { 37 | status: OK, 38 | body: { 39 | damaged: true, 40 | }, 41 | }, 42 | }; 43 | 44 | public static INVALID_INTERACTION_ID_1: IInteraction = { 45 | request: { 46 | params: { 47 | id: '3', 48 | }, 49 | headers: { 50 | [AUTHORIZATION_HEADER]: `Basic ${BASIC_AUTH}`, 51 | }, 52 | }, 53 | response: { 54 | status: NOT_FOUND, 55 | }, 56 | }; 57 | 58 | public static INVALID_INTERACTION_ID_2: IInteraction = { 59 | request: { 60 | params: { 61 | id: '4', 62 | }, 63 | headers: { 64 | [AUTHORIZATION_HEADER]: `Basic ${BASIC_AUTH}`, 65 | }, 66 | }, 67 | response: { 68 | status: OK, 69 | body: 'INVALID', 70 | }, 71 | }; 72 | } 73 | -------------------------------------------------------------------------------- /test/test-utils/TestRepository.ts: -------------------------------------------------------------------------------- 1 | import 'reflect-metadata'; 2 | import { BaseCRUDRepository } from '../../src/persistence/common/BaseCRUDRepository'; 3 | import { AbstractMeta, NewDocument } from 'documentdb'; 4 | import { IsNotEmpty, IsString } from 'class-validator'; 5 | import { Type } from 'class-transformer'; 6 | 7 | /** 8 | * The test repository setup. CRUD operations and more on the TestEntity. 9 | */ 10 | export class TestRepository extends BaseCRUDRepository { 11 | constructor() { 12 | super('test', TestEntity); 13 | } 14 | } 15 | 16 | /** 17 | * The TestEntity definition. 18 | */ 19 | export interface ITestEntity extends AbstractMeta, NewDocument { 20 | name: string; 21 | phonenumbers: number[]; 22 | friends: IFriend[]; 23 | } 24 | 25 | /** 26 | * The TestEntity update properties definition. 27 | */ 28 | export interface ITestEntityUpdateProperties { 29 | id?: string; 30 | phonenumbers?: number[] | number; 31 | name?: string; 32 | friends?: IFriend; 33 | } 34 | 35 | /** 36 | * The TestEntity. 37 | */ 38 | export class TestEntity implements ITestEntity { 39 | @IsNotEmpty() 40 | @IsString() 41 | public id: string; 42 | public name: string; 43 | public phonenumbers: number[]; 44 | @Type(() => Friend) 45 | public friends: IFriend[]; 46 | public _self: string; 47 | public _ts: number; 48 | public _rid?: string; 49 | public _etag?: string; 50 | public _attachments?: string; 51 | public ttl?: number; 52 | 53 | /** 54 | * toString method 55 | */ 56 | public toString(): string { 57 | return `TestEntity{id: ${this.id}, phonenumbers: [${this.phonenumbers ? this.phonenumbers.join() : ''}], friends: [${this.friends ? this.friends.join() : ''}]}`; 58 | } 59 | } 60 | 61 | /** 62 | * Some test entity addition. 63 | */ 64 | export interface IFriend { 65 | id: string; 66 | name?: string; 67 | } 68 | 69 | /** 70 | * Some test entity addition. 71 | */ 72 | export class Friend implements IFriend { 73 | constructor(public id: string, public name?: string) { } 74 | 75 | public toString(): string { 76 | return `Friend{id: ${this.id}}`; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /test/int/services/VehicleServiceDatabaseInt.spec.ts: -------------------------------------------------------------------------------- 1 | // General imports 2 | import * as chai from 'chai'; 3 | import * as chaiAsPromised from 'chai-as-promised'; 4 | import { VehicleEntity, COLORS } from '../../../src/persistence/entities/VehicleEntity'; 5 | import { VehicleDto } from '../../../src/models/VehicleDto'; 6 | // Database util 7 | import VehicleRepository from '../../../src/persistence/VehicleRepository'; 8 | // Class under test 9 | import { VehicleService } from '../../../src/services/VehicleService'; 10 | 11 | chai.use(chaiAsPromised); 12 | const expect = chai.expect; 13 | 14 | describe('VehicleService Database Integration tests', () => { 15 | describe('listing all vehicles from the repository', () => { 16 | 17 | const vehicleEntityOne = new VehicleEntity('1GNKVEED5CJ144006', COLORS.GREEN); 18 | const vehicleEntityTwo = new VehicleEntity('1FTFW1EF7BFC78504', COLORS.RED); 19 | 20 | it(`GIVEN two existing vehicles with ids: {${vehicleEntityOne.id}, ${vehicleEntityTwo.id}} in the database, WHEN listAllVehicles() is executed, THEN the Promise will be resolved with an array from 2 VehicleDto objects.`, async () => { 21 | await VehicleRepository.create(vehicleEntityOne); 22 | await VehicleRepository.create(vehicleEntityTwo); 23 | 24 | const expectedFirstVehicle = new VehicleDto(vehicleEntityOne.id, vehicleEntityOne.color); 25 | expectedFirstVehicle.damaged = undefined; 26 | const expectedSecondVehicle = new VehicleDto(vehicleEntityTwo.id, vehicleEntityTwo.color); 27 | expectedSecondVehicle.damaged = undefined; 28 | const expectedVehicles = [expectedFirstVehicle, expectedSecondVehicle]; 29 | 30 | const result = VehicleService.listAllVehicles(); 31 | 32 | await expect(result).to.be.eventually.an('array').that.has.deep.members(expectedVehicles); 33 | }); 34 | 35 | it('GIVEN no existing vehicles in the database, WHEN listAllVehicles() is executed, THEN the Promise will be resolved with an empty array.', async () => { 36 | 37 | const result = VehicleService.listAllVehicles(); 38 | 39 | await expect(result).to.be.eventually.an('array').that.is.empty; 40 | }); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /src/middlewares/AsyncControllerHandler.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, RequestHandler, Response } from 'express'; 2 | import { OK, SERVICE_UNAVAILABLE } from 'http-status-codes'; 3 | import { TIMEOUT } from '../common/config'; 4 | import { HttpError } from '../errors/HttpError'; 5 | 6 | /** 7 | * Handles each controller method in order to set the response or handle errors. 8 | */ 9 | export class AsyncControllerHandler { 10 | /** 11 | * Async controller handler middleware to set response or to handle an error. 12 | * @param requestHandlerFunction The Async request handler function. 13 | */ 14 | public static control(requestHandlerFunction: IAsyncRequestHandler): IRequestHandler { 15 | return (req: Request, res: Response, next: NextFunction): void => { 16 | let to: NodeJS.Timer; 17 | const routePromise = requestHandlerFunction(req, res, next); 18 | const timeoutPromise = new Promise((resolve, reject) => { 19 | to = setTimeout(() => { 20 | reject(new HttpError(SERVICE_UNAVAILABLE)); 21 | }, TIMEOUT); 22 | }); 23 | Promise.race([routePromise, timeoutPromise]) 24 | .then((ctlRes: IControllerResponse) => { 25 | clearTimeout(to); 26 | res.status(ctlRes.code).send(ctlRes.body); 27 | }, (err) => { 28 | clearTimeout(to); 29 | next(err); 30 | }); 31 | }; 32 | } 33 | } 34 | 35 | /** 36 | * An async RequestHandler. 37 | */ 38 | export interface IAsyncRequestHandler extends RequestHandler { 39 | (req: Request, res: Response, next: NextFunction): Promise; 40 | } 41 | 42 | /** 43 | * The returned RequestHandler function. 44 | */ 45 | export interface IRequestHandler extends RequestHandler { 46 | (req: Request, res: Response, next: NextFunction): void; 47 | } 48 | 49 | /** 50 | * Defines a controller response. 51 | */ 52 | export interface IControllerResponse { 53 | code: number; 54 | body?: any; 55 | } 56 | 57 | /** 58 | * The controller response each controller should respond with. 59 | */ 60 | export class ControllerResponse implements IControllerResponse { 61 | constructor(public code: number = OK, public body?: any) { } 62 | } 63 | -------------------------------------------------------------------------------- /test/int/controller/VehicleEndpoint.spec.ts: -------------------------------------------------------------------------------- 1 | import * as chai from 'chai'; 2 | import chaiHttp = require('chai-http'); 3 | import * as chaiAsPromised from 'chai-as-promised'; 4 | import { OK, BAD_REQUEST, CONFLICT } from 'http-status-codes'; 5 | import VehicleRepository from '../../../src/persistence/VehicleRepository'; 6 | import App from '../../../src/App'; 7 | import { VehicleEntity } from '../../../src/persistence/entities/VehicleEntity'; 8 | import { transformAndValidate } from 'class-transformer-validator'; 9 | 10 | chai.use(chaiHttp); 11 | chai.use(chaiAsPromised); 12 | const expect = chai.expect; 13 | 14 | describe('Endpoint test for VehicleController: POST /vehicles', () => { 15 | 16 | const VEHICLE_ENDPOINT = '/vehicles'; 17 | 18 | it('GIVEN a valid vehicle, WHEN posting to vehicles endpoint, THEN a Response with HTTP STATUS OK and the created vehicle will be sent.', async () => { 19 | const vehicle = { 20 | id: '1', 21 | color: 1, 22 | }; 23 | 24 | const result = await chai.request(App) 25 | .post(VEHICLE_ENDPOINT) 26 | .send(vehicle); 27 | 28 | expect(result).to.have.status(OK); 29 | expect(result.body).to.be.deep.equal(vehicle); 30 | }); 31 | 32 | it('GIVEN an invalid vehicle with wrong color code, WHEN posting to vehicles endpoint, THEN a Response with HTTP STATUS BAD_REQUEST and no body will be sent.', async () => { 33 | const vehicle = { 34 | id: '1', 35 | color: 9, 36 | }; 37 | 38 | const result = await chai.request(App) 39 | .post(VEHICLE_ENDPOINT) 40 | .send(vehicle); 41 | 42 | expect(result).to.have.status(BAD_REQUEST); 43 | expect(result.body).to.be.empty; 44 | }); 45 | 46 | it('GIVEN a valid vehicle that already exists in the database, WHEN posting to vehicles endpoint, THEN a Response with HTTP STATUS CONFLICT and no body will be sent.', async () => { 47 | const vehicle = { 48 | id: '1', 49 | color: 1, 50 | }; 51 | 52 | await VehicleRepository.create(await transformAndValidate(VehicleEntity, vehicle)); 53 | 54 | const result = await chai.request(App) 55 | .post(VEHICLE_ENDPOINT) 56 | .send(vehicle); 57 | 58 | expect(result).to.have.status(CONFLICT); 59 | expect(result.body).to.be.empty; 60 | }); 61 | }); 62 | -------------------------------------------------------------------------------- /test/contract/contract/pacts/vehicle-service-damage-service.json: -------------------------------------------------------------------------------- 1 | { 2 | "consumer": { 3 | "name": "vehicle-service" 4 | }, 5 | "provider": { 6 | "name": "damage-service" 7 | }, 8 | "interactions": [ 9 | { 10 | "description": "a valid vehicle ID from Vehicle Service", 11 | "providerState": "Valid vehicle ID = 1", 12 | "request": { 13 | "method": "GET", 14 | "path": "/damage/vehicle/1", 15 | "headers": { 16 | "Authorization": "Basic AUTH" 17 | }, 18 | "matchingRules": { 19 | "$.headers.Authorization": { 20 | "match": "regex", 21 | "regex": "^Basic " 22 | } 23 | } 24 | }, 25 | "response": { 26 | "status": 200, 27 | "headers": { 28 | }, 29 | "body": { 30 | "damaged": true 31 | }, 32 | "matchingRules": { 33 | "$.body": { 34 | "match": "type" 35 | } 36 | } 37 | } 38 | }, 39 | { 40 | "description": "a valid vehicle ID from Vehicle Service", 41 | "providerState": "Valid vehicle ID = 2", 42 | "request": { 43 | "method": "GET", 44 | "path": "/damage/vehicle/2", 45 | "headers": { 46 | "Authorization": "Basic AUTH" 47 | }, 48 | "matchingRules": { 49 | "$.headers.Authorization": { 50 | "match": "regex", 51 | "regex": "^Basic " 52 | } 53 | } 54 | }, 55 | "response": { 56 | "status": 200, 57 | "headers": { 58 | }, 59 | "body": { 60 | "damaged": false 61 | }, 62 | "matchingRules": { 63 | "$.body": { 64 | "match": "type" 65 | } 66 | } 67 | } 68 | }, 69 | { 70 | "description": "a valid non existing vehicle ID from Vehicle Service", 71 | "providerState": "Valid vehicle ID = 17", 72 | "request": { 73 | "method": "GET", 74 | "path": "/damage/vehicle/17", 75 | "headers": { 76 | "Authorization": "Basic AUTH" 77 | }, 78 | "matchingRules": { 79 | "$.headers.Authorization": { 80 | "match": "regex", 81 | "regex": "^Basic " 82 | } 83 | } 84 | }, 85 | "response": { 86 | "status": 404, 87 | "headers": { 88 | } 89 | } 90 | } 91 | ], 92 | "metadata": { 93 | "pactSpecification": { 94 | "version": "2.0.0" 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /test/int/services/backends/DamageService.spec.ts: -------------------------------------------------------------------------------- 1 | // General imports 2 | import * as chai from 'chai'; 3 | import * as chaiAsPromised from 'chai-as-promised'; 4 | import { HttpError } from '../../../../src/errors/HttpError'; 5 | import { VehicleEntity, COLORS } from '../../../../src/persistence/entities/VehicleEntity'; 6 | import { SERVICE_UNAVAILABLE } from 'http-status-codes'; 7 | // Class under test 8 | import { DamageService } from '../../../../src/services/backends/DamageService'; 9 | 10 | chai.use(chaiAsPromised); 11 | const expect = chai.expect; 12 | 13 | describe('Integration test for DamageService', () => { 14 | describe('get damage state with DamageService interaction', () => { 15 | const healthyVehicle = new VehicleEntity('1', COLORS.RED); 16 | const damagedVehicle = new VehicleEntity('2', COLORS.BLUE); 17 | const notFoundVehicle = new VehicleEntity('3', COLORS.YELLOW); 18 | const invalidResponseVehicle = new VehicleEntity('4', COLORS.GREEN); 19 | 20 | it(`GIVEN vehicle id="${healthyVehicle.id}", WHEN getDamageState() is executed THEN the Promise will be resolved with false.`, async () => { 21 | 22 | const result = DamageService.getDamageState(healthyVehicle.id); 23 | 24 | await expect(result).to.be.eventually.false; 25 | }); 26 | 27 | it(`GIVEN vehicle id="${damagedVehicle.id}", WHEN getDamageState() is executed THEN the Promise will be resolved with true.`, async () => { 28 | 29 | const result = DamageService.getDamageState(damagedVehicle.id); 30 | 31 | await expect(result).to.be.eventually.true; 32 | }); 33 | 34 | it(`GIVEN vehicle id="${notFoundVehicle.id}", WHEN getDamageState() is executed AND DamageService responds with NOT_FOUND THEN the Promise will be rejected with HttpError(SERVICE_UNAVAILABLE).`, async () => { 35 | 36 | const result = DamageService.getDamageState(notFoundVehicle.id); 37 | 38 | await expect(result).to.be.rejectedWith(HttpError).and.eventually.has.property('statusCode', SERVICE_UNAVAILABLE); 39 | }); 40 | 41 | it(`GIVEN vehicle id="${invalidResponseVehicle.id}", WHEN getDamageState() is executed AND DamageService responds with invalid body THEN the Promise will be rejected with HttpError(SERVICE_UNAVAILABLE).`, async () => { 42 | 43 | const result = DamageService.getDamageState(invalidResponseVehicle.id); 44 | 45 | await expect(result).to.be.rejectedWith(HttpError).and.eventually.has.property('statusCode', SERVICE_UNAVAILABLE); 46 | }); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /test/int/services/VehicleServiceComponent.spec.ts: -------------------------------------------------------------------------------- 1 | // General imports 2 | import * as chai from 'chai'; 3 | import * as chaiAsPromised from 'chai-as-promised'; 4 | import { HttpError } from '../../../src/errors/HttpError'; 5 | import { VehicleEntity, COLORS } from '../../../src/persistence/entities/VehicleEntity'; 6 | import { SERVICE_UNAVAILABLE, NOT_FOUND } from 'http-status-codes'; 7 | import { VehicleDto } from '../../../src/models/VehicleDto'; 8 | import VehicleRepository from '../../../src/persistence/VehicleRepository'; 9 | // Class under test 10 | import { VehicleService } from '../../../src/services/VehicleService'; 11 | 12 | chai.use(chaiAsPromised); 13 | const expect = chai.expect; 14 | 15 | describe('Component tests for VehicleService', () => { 16 | describe('getting detailed vehicle via Database and DamageService interactions', () => { 17 | const nonExistingVehicleId = '12'; 18 | const existingVehicleId = '2'; 19 | const invalidResponseVehicleId = '4'; 20 | 21 | it(`GIVEN a non existing vehicle ID = ${nonExistingVehicleId} in the database, WHEN getDetailedVehicle() is executed, THEN the Promise will be rejected with HttpError(NOT_FOUND).`, async () => { 22 | 23 | const result = VehicleService.getDetailedVehicle(nonExistingVehicleId); 24 | 25 | await expect(result).to.be.rejectedWith(HttpError).and.eventually.has.property('statusCode', NOT_FOUND); 26 | }); 27 | 28 | it(`GIVEN an existing vehicle ID = ${existingVehicleId} in the database, WHEN getDetailedVehicle() is executed AND DamageService responds with true, THEN the Promise will be resolved with the correct VehicleDto.`, async () => { 29 | const expectedVehicleDto = new VehicleDto(existingVehicleId, COLORS.GREEN, true); 30 | const vehicleEntity = new VehicleEntity(existingVehicleId, COLORS.GREEN); 31 | await VehicleRepository.create(vehicleEntity); 32 | 33 | const result = VehicleService.getDetailedVehicle(existingVehicleId); 34 | 35 | await expect(result).to.be.eventually.deep.equal(expectedVehicleDto); 36 | }); 37 | 38 | it(`GIVEN an existing vehicle ID = ${invalidResponseVehicleId} in the database, WHEN getDetailedVehicle() is executed AND DamageService responds with invalid body, THEN the Promise will be rejected with HttpError(SERVICE_UNAVAILABLE).`, async () => { 39 | const vehicleEntity = new VehicleEntity(invalidResponseVehicleId, COLORS.BLUE); 40 | await VehicleRepository.create(vehicleEntity); 41 | 42 | const result = VehicleService.getDetailedVehicle(invalidResponseVehicleId); 43 | 44 | await expect(result).to.be.rejectedWith(HttpError).and.to.have.eventually.property('statusCode', SERVICE_UNAVAILABLE); 45 | }); 46 | 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /src/services/VehicleService.ts: -------------------------------------------------------------------------------- 1 | import { plainToClass } from 'class-transformer'; 2 | import { transformAndValidate } from 'class-transformer-validator'; 3 | import { BAD_REQUEST, NOT_FOUND } from 'http-status-codes'; 4 | import { HttpError } from '../errors/HttpError'; 5 | import { UnexpectedServiceError } from '../errors/UnexpectedServiceError'; 6 | import { ErrorHandler } from '../middlewares/ErrorHandler'; 7 | import { VehicleDto } from '../models/VehicleDto'; 8 | import { VehicleEntity } from '../persistence/entities/VehicleEntity'; 9 | import VehicleRepository from '../persistence/VehicleRepository'; 10 | import { ValidationErrorUtil } from '../util/ValidationErrorUtil'; 11 | import { DamageService } from './backends/DamageService'; 12 | 13 | /** 14 | * Deals with everything regarding vehicles. 15 | */ 16 | export class VehicleService { 17 | 18 | /** 19 | * Find the vehicle for the id and enrich the dto by the damage information. 20 | * @param id The id. 21 | */ 22 | public static async getDetailedVehicle(id: string): Promise { 23 | try { 24 | const vehicle = await VehicleRepository.findOne(id); 25 | if (vehicle === null) { 26 | throw new HttpError(NOT_FOUND); 27 | } 28 | const vehicleDto = plainToClass(VehicleDto, vehicle); 29 | vehicleDto.damaged = await DamageService.getDamageState(vehicleDto.id); 30 | return vehicleDto; 31 | } catch (e) { 32 | await ErrorHandler.handleServiceErrors(e); 33 | } 34 | throw new UnexpectedServiceError(); 35 | } 36 | 37 | /** 38 | * List all vehicles. 39 | */ 40 | public static async listAllVehicles(): Promise { 41 | try { 42 | const vehicles = await VehicleRepository.findAll(); 43 | if (vehicles === null) { 44 | return []; 45 | } else { 46 | return plainToClass(VehicleDto, vehicles); 47 | } 48 | } catch (e) { 49 | await ErrorHandler.handleServiceErrors(e); 50 | } 51 | throw new UnexpectedServiceError(); 52 | } 53 | 54 | /** 55 | * Creates a vehicle for the given body and returns the newly created entity. 56 | * @param body The request body. 57 | */ 58 | public static async create(body: object): Promise { 59 | try { 60 | const vehicle = await transformAndValidate(VehicleEntity, body); 61 | return plainToClass(VehicleDto, await VehicleRepository.create(vehicle)); 62 | } catch (e) { 63 | if (await ValidationErrorUtil.checkForValidationErrors(e)) { 64 | throw new HttpError(BAD_REQUEST); 65 | } 66 | await ErrorHandler.handleServiceErrors(e); 67 | } 68 | throw new UnexpectedServiceError(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/middlewares/ErrorHandler.ts: -------------------------------------------------------------------------------- 1 | import { ErrorRequestHandler, NextFunction, Request, RequestHandler, Response } from 'express'; 2 | import { CONFLICT, INTERNAL_SERVER_ERROR, NOT_FOUND, SERVICE_UNAVAILABLE } from 'http-status-codes'; 3 | import { DbQueryError } from '../errors/DbQueryError'; 4 | import { HttpError } from '../errors/HttpError'; 5 | import { RepositoryError } from '../errors/RepositoryError'; 6 | import { UnexpectedServiceError } from '../errors/UnexpectedServiceError'; 7 | import { ValidationErrorUtil } from '../util/ValidationErrorUtil'; 8 | 9 | /** 10 | * Handles any kind of error for all endpoints and provides handler functions for different kind of services (backend, internal, etc.). 11 | */ 12 | export class ErrorHandler { 13 | 14 | /** 15 | * Handles different kind of errors thrown by services or controllers and send respective response. 16 | */ 17 | public static handleErrors: ErrorRequestHandler = (err: any, req: Request, res: Response, next: NextFunction): void => { 18 | if (err instanceof HttpError) { 19 | res.status(err.statusCode).send(); 20 | } else { 21 | res.status(INTERNAL_SERVER_ERROR).send(); 22 | } 23 | } 24 | 25 | /** 26 | * Handles all not mappable requests with a specific NOT_FOUND error. 27 | */ 28 | public static handleNotFound: RequestHandler = (req: Request, res: Response, next: NextFunction) => { 29 | next(new HttpError(NOT_FOUND)); 30 | } 31 | 32 | /** 33 | * Handles any kind of service errors and maps them on the respective HttpError. 34 | * Can also be used for handling Errors in Controllers, if Service layer isn't necessary. 35 | * Example: A request to a backend results in a RequestError, caused by a Timeout: HttpError(503) 36 | * @param e Any kind of Error. 37 | * @param logMeta The log meta data. 38 | */ 39 | public static async handleServiceErrors(e: any): Promise { 40 | if (e.constructor === HttpError) { 41 | throw e; 42 | } 43 | throw new HttpError(SERVICE_UNAVAILABLE); 44 | } 45 | 46 | /** 47 | * Handles any kind of repository errors and maps them on the respective RepositoryError. 48 | * @param e Any kind of Error. 49 | * @param logMeta The log meta data. 50 | */ 51 | public static async handleRepositoryErrors(e: any): Promise { 52 | if (e instanceof RepositoryError) { 53 | throw e; 54 | } else if (e instanceof TypeError) { 55 | throw new RepositoryError(e.message); 56 | } else if (e instanceof DbQueryError) { 57 | throw e.code !== 'ECONNRESET' ? e.code === CONFLICT ? new HttpError(CONFLICT) : new RepositoryError(e.message) : new RepositoryError(e.message, true); 58 | } else if (await ValidationErrorUtil.checkForValidationErrors(e)) { 59 | throw new RepositoryError('Validation error(s) occured during transformation from database document into entity.'); 60 | } else { 61 | throw new UnexpectedServiceError(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/persistence/common/stored-procedures/bulkDeleteAll.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * The stored procedure to delete all documents for a collection. 3 | * @param query A query that provides the documents to be deleted. eg. 'SELECT * FROM root' 4 | */ 5 | export function bulkDeleteAll(query: string) { 6 | const collection: ICollection = getContext().getCollection(); 7 | const collectionLink: string = collection.getSelfLink(); 8 | const response: IResponse = getContext().getResponse(); 9 | const responseBody = { 10 | continuation: true, 11 | deleted: 0, 12 | }; 13 | 14 | if (!query) { throw new Error('The query is undefined or null.'); } 15 | 16 | tryQueryAndDelete(); 17 | 18 | function tryQueryAndDelete(continuation?: string) { 19 | const requestOptions: IFeedOptions = { continuation }; 20 | const isAccepted: boolean = collection.queryDocuments( 21 | collectionLink, query, requestOptions, (err: IFeedCallbackError, retrievedDocs: any[], responseOptions: IFeedCallbackOptions) => { 22 | if (err) { 23 | throw err; 24 | } 25 | 26 | if (retrievedDocs.length > 0) { 27 | // Begin deleting documents as soon as documents are returned form the query results. 28 | // tryDelete() resumes querying after deleting; no need to page through continuation tokens. 29 | // - this is to prioritize writes over reads given timeout constraints. 30 | tryDelete(retrievedDocs); 31 | } else if (responseOptions.continuation) { 32 | // Else if the query came back empty, but with a continuation token; repeat the query w/ the token. 33 | tryQueryAndDelete(responseOptions.continuation); 34 | } else { 35 | // Else if there are no more documents and no continuation token - we are finished deleting documents. 36 | responseBody.continuation = false; 37 | response.setBody(responseBody); 38 | } 39 | }); 40 | 41 | // If we hit execution bounds - return continuation: true. 42 | if (!isAccepted) { 43 | response.setBody(responseBody); 44 | } 45 | } 46 | 47 | function tryDelete(documents: IDocumentMeta[]) { 48 | if (documents.length > 0) { 49 | // Delete the first document in the array. 50 | const isAccepted: boolean = collection.deleteDocument(documents[0]._self, (err: IRequestCallbackError, 51 | resources: object, responseOptions: IRequestCallbackOptions) => { 52 | if (err) { 53 | throw err; 54 | } 55 | responseBody.deleted++; 56 | documents.shift(); 57 | // Delete the next document in the array. 58 | tryDelete(documents); 59 | }); 60 | 61 | // If we hit execution bounds - return continuation: true. 62 | if (!isAccepted) { 63 | response.setBody(responseBody); 64 | } 65 | } else { 66 | // If the document array is empty, query for more documents. 67 | tryQueryAndDelete(); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "blog-microservices-testing-nodejs-typescript", 3 | "version": "1.0.0", 4 | "description": "Examples for the corresponding blog post.", 5 | "main": "dist/Server.js", 6 | "scripts": { 7 | "start": "node dist/Server.js", 8 | "build": "npm run ts:build && npm run ts:lint", 9 | "serve": "cross-env NODE_ENV=int DATABASE_ID=\"blog\" nodemon dist/Server.js", 10 | "serve-sim": "cross-env NODE_ENV=test DATABASE_ID=\"blog\" nodemon dist/Server.js", 11 | "ts:build": "rimraf dist && tsc -p tsconfig.build.json", 12 | "ts:watch": "tsc -w -p tsconfig.build.json", 13 | "ts:lint": "tslint -c tslint.json -p tsconfig.build.json 'src/**/*.ts' && tslint -c test/tslint.json -p tsconfig.json 'test/**/*.ts'", 14 | "ts:doc": "typedoc --out docs/ --mode file --excludeExternals --module commonjs --target ES6 --tsconfig tsconfig.build.json --readme none", 15 | "test": "npm run test:unit && npm run test:int", 16 | "test:unit": "cross-env NODE_ENV=test nyc mocha \"test/unit/**/*.spec.ts\" --opts ./mocha.opts", 17 | "test:int": "cross-env NODE_ENV=test mocha \"test/int/**/*.spec.ts\" --opts ./mocha.opts --timeout 10000", 18 | "test:contract": "cross-env NODE_ENV=test mocha \"test/contract/**/*.spec.ts\" --opts ./mocha.opts --timeout 10000", 19 | "simulation": "node -r ts-node/register test/test-utils/simulation/SimulationServer.ts" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/nt-ca-aqe/blog-microservices-testing-nodejs-typescript.git" 24 | }, 25 | "keywords": [ 26 | "microservice", 27 | "testing", 28 | "nodejs", 29 | "typescript" 30 | ], 31 | "author": "Antoniya Atanasova, Janis Koehr", 32 | "license": "GPL-3.0", 33 | "bugs": { 34 | "url": "https://github.com/nt-ca-aqe/blog-microservices-testing-nodejs-typescript/issues" 35 | }, 36 | "homepage": "https://github.com/nt-ca-aqe/blog-microservices-testing-nodejs-typescript#readme", 37 | "devDependencies": { 38 | "@types/body-parser": "^1.17.0", 39 | "@types/chai": "^4.1.3", 40 | "@types/chai-as-promised": "^7.1.0", 41 | "@types/chai-http": "^3.0.4", 42 | "@types/documentdb": "^1.10.4", 43 | "@types/documentdb-server": "0.0.32", 44 | "@types/express": "^4.11.1", 45 | "@types/http-status-codes": "^1.2.0", 46 | "@types/mocha": "^5.2.0", 47 | "@types/node": "^9.6.18", 48 | "@types/request": "^2.47.0", 49 | "@types/request-promise-native": "^1.0.14", 50 | "@types/sinon": "^5.0.0", 51 | "@types/sinon-chai": "^2.7.32", 52 | "chai": "^4.1.2", 53 | "chai-as-promised": "^7.1.1", 54 | "chai-http": "^4.0.0", 55 | "cross-env": "^5.1.6", 56 | "mocha": "^5.2.0", 57 | "nodemon": "^1.17.5", 58 | "nyc": "^11.8.0", 59 | "rimraf": "^2.6.2", 60 | "sinon": "^5.0.10", 61 | "sinon-chai": "^3.1.0", 62 | "source-map-support": "^0.5.6", 63 | "ts-node": "^6.0.5", 64 | "tslint": "^5.10.0", 65 | "tslint-language-service": "^0.9.9", 66 | "typedoc": "^0.11.1", 67 | "typescript": "^2.8.3" 68 | }, 69 | "dependencies": { 70 | "@pact-foundation/pact": "^5.9.1", 71 | "body-parser": "^1.18.3", 72 | "class-transformer": "^0.1.9", 73 | "class-transformer-validator": "^0.5.0", 74 | "class-validator": "^0.8.5", 75 | "documentdb": "^1.14.4", 76 | "express": "^4.16.3", 77 | "http-status-codes": "^1.3.0", 78 | "reflect-metadata": "^0.1.12", 79 | "request": "^2.87.0", 80 | "request-promise-native": "^1.0.5" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /test/test-utils/simulation/DynamicSimulationDataInterpreter.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response } from 'express'; 2 | import { INTERNAL_SERVER_ERROR } from 'http-status-codes'; 3 | import { deepStrictEqual } from 'assert'; 4 | 5 | /** 6 | * Matches the request part of an interaction and responds with the corresponding response 7 | * when given an interactions class and request and response from express. 8 | */ 9 | export class DynamicSimulationDataInterpreter { 10 | 11 | public static interpret(clazz: new () => any, req: Request, res: Response): void { 12 | const rightInteraction = (Object.values(clazz) as IInteraction[]).find( 13 | (interaction) => DynamicSimulationDataInterpreter.testRequest(interaction.request, req), 14 | ); 15 | if (rightInteraction !== undefined) { 16 | DynamicSimulationDataInterpreter.createAndSendResponse(rightInteraction.response, res); 17 | } else { 18 | res.status(INTERNAL_SERVER_ERROR).send(); 19 | } 20 | } 21 | 22 | /** 23 | * Compares the actual request with the given expected interaction request. 24 | * @param interactionRequest The interaction request part. 25 | * @param req The actual request. 26 | */ 27 | private static testRequest(interactionRequest: IRequest, req: Request): boolean { 28 | if (interactionRequest.params !== undefined && !Object.entries(interactionRequest.params).every((reqPV) => reqPV[1] instanceof RegExp ? (req.params[reqPV[0]] as string).match(reqPV[1]) !== null : req.params[reqPV[0]] === reqPV[1])) { 29 | return false; 30 | } 31 | if (interactionRequest.queryParams !== undefined && !Object.entries(interactionRequest.queryParams).every((reqQpV) => reqQpV[1] instanceof RegExp ? (req.query[reqQpV[0]] as string).match(reqQpV[1]) !== null : req.query[reqQpV[0]] === reqQpV[1])) { 32 | return false; 33 | } 34 | if (interactionRequest.headers !== undefined && !Object.entries(interactionRequest.headers).every((reqH) => reqH[1] instanceof RegExp ? (req.get(reqH[0]) as string).match(reqH[1]) !== null : req.get(reqH[0]) === reqH[1])) { 35 | return false; 36 | } 37 | if (interactionRequest.body !== undefined) { 38 | try { 39 | deepStrictEqual(req.body, interactionRequest.body); 40 | } catch (e) { 41 | return false; 42 | } 43 | } 44 | return true; 45 | } 46 | 47 | /** 48 | * Sets / prepares the necessary parts of the response and sends it. 49 | * @param interactionResponse The interaction response part. 50 | * @param res The express response. 51 | */ 52 | private static createAndSendResponse(interactionResponse: IResponse, res: Response): void { 53 | if (interactionResponse.headers !== undefined) { 54 | Object.entries(interactionResponse.headers).forEach((entry) => res.setHeader(entry[0], entry[1])); 55 | } 56 | interactionResponse.body === undefined ? res.status(interactionResponse.status).send() : 57 | interactionResponse.body === 'INVALID' ? res.status(interactionResponse.status).type('json').send('INVALID') : res.status(interactionResponse.status).json(interactionResponse.body); 58 | } 59 | } 60 | 61 | /** 62 | * An interaction for one endpoint for the simulation. 63 | */ 64 | export interface IInteraction { 65 | request: IRequest; 66 | response: IResponse; 67 | } 68 | 69 | /** 70 | * The request matching parameters for an interaction. 71 | */ 72 | interface IRequest { 73 | headers?: IRequestHeaders; 74 | body?: object | any[] | RegExp; // object or the regex that should match here 75 | params?: IRequestParams; 76 | queryParams?: IRequestQueryParams; 77 | } 78 | 79 | /** 80 | * Header fields for an interaction request or the regex that should match here. 81 | */ 82 | interface IRequestHeaders { 83 | [propName: string]: string | RegExp; 84 | } 85 | 86 | /** 87 | * Parameters for the endpoint interaction or the regex that should match here. 88 | */ 89 | interface IRequestParams { 90 | [propName: string]: string | RegExp; 91 | } 92 | 93 | /** 94 | * Query parameters for the endpoint interaction or the regex that should match here. 95 | */ 96 | interface IRequestQueryParams { 97 | [propName: string]: string | RegExp; 98 | } 99 | 100 | /** 101 | * The response for a specific interaction. 102 | */ 103 | interface IResponse { 104 | headers?: IHeaders; 105 | status: number; 106 | body?: object | any[] | 'INVALID'; 107 | } 108 | 109 | /** 110 | * Header fields for an interaction response. 111 | */ 112 | interface IHeaders { 113 | [propName: string]: string; 114 | } 115 | -------------------------------------------------------------------------------- /test/contract/damageService/GetDamageStateByVehicleIdContract.spec.ts: -------------------------------------------------------------------------------- 1 | // General imports 2 | import * as chai from 'chai'; 3 | import * as chaiAsPromised from 'chai-as-promised'; 4 | import { Pact, Interaction, Matchers } from '@pact-foundation/pact'; 5 | import { AUTHORIZATION_HEADER, BASIC_AUTH } from '../../../src/common/config'; 6 | import { OK, NOT_FOUND, SERVICE_UNAVAILABLE } from 'http-status-codes'; 7 | import { resolve } from 'path'; 8 | import { HttpError } from '../../../src/errors/HttpError'; 9 | // Class under test 10 | import { DamageService } from '../../../src/services/backends/DamageService'; 11 | 12 | chai.use(chaiAsPromised); 13 | const expect = chai.expect; 14 | 15 | describe('Contract test for DamageService: getDamageState', () => { 16 | const provider: Pact = new Pact({ 17 | consumer: 'vehicle-service', 18 | provider: 'damage-service', 19 | port: 8080, 20 | host: 'localhost', 21 | dir: resolve(__dirname, '../contract/pacts'), 22 | log: resolve(__dirname, '../contract/logs/pact.log'), 23 | spec: 2, 24 | }); 25 | const BASIC_AUTH_MATCHER: string = '^Basic '; 26 | 27 | const damagedVehicleId = '1'; 28 | const notDamagedVehicleId = '2'; 29 | const nonExistingDamagedVehicleId = '17'; 30 | 31 | const validInteractionForDamagedVehicle = new Interaction() 32 | .given(`Valid vehicle ID = ${damagedVehicleId}`) 33 | .uponReceiving('a valid vehicle ID from Vehicle Service') 34 | .withRequest({ 35 | method: 'GET', 36 | path: `/damage/vehicle/${damagedVehicleId}`, 37 | headers: { 38 | [AUTHORIZATION_HEADER]: Matchers.term({ 39 | generate: `Basic ${BASIC_AUTH}`, 40 | matcher: BASIC_AUTH_MATCHER, 41 | }), 42 | }, 43 | }) 44 | .willRespondWith({ 45 | status: OK, 46 | body: Matchers.somethingLike({ damaged: true }), 47 | }); 48 | 49 | const validInteractionForNotDamagedVehicle = new Interaction() 50 | .given(`Valid vehicle ID = ${notDamagedVehicleId}`) 51 | .uponReceiving('a valid vehicle ID from Vehicle Service') 52 | .withRequest({ 53 | method: 'GET', 54 | path: `/damage/vehicle/${notDamagedVehicleId}`, 55 | headers: { 56 | [AUTHORIZATION_HEADER]: Matchers.term({ 57 | generate: `Basic ${BASIC_AUTH}`, 58 | matcher: BASIC_AUTH_MATCHER, 59 | }), 60 | }, 61 | }) 62 | .willRespondWith({ 63 | status: OK, 64 | body: Matchers.somethingLike({ damaged: false }), 65 | }); 66 | 67 | const validInteractionForNonExisitingVehicle = new Interaction() 68 | .given(`Valid vehicle ID = ${nonExistingDamagedVehicleId}`) 69 | .uponReceiving('a valid non existing vehicle ID from Vehicle Service') 70 | .withRequest({ 71 | method: 'GET', 72 | path: `/damage/vehicle/${nonExistingDamagedVehicleId}`, 73 | headers: { 74 | [AUTHORIZATION_HEADER]: Matchers.term({ 75 | generate: `Basic ${BASIC_AUTH}`, 76 | matcher: BASIC_AUTH_MATCHER, 77 | }), 78 | }, 79 | }) 80 | .willRespondWith({ 81 | status: NOT_FOUND, 82 | }); 83 | 84 | before(async () => { 85 | await provider.setup(); 86 | }); 87 | 88 | after(async () => { 89 | await provider.finalize(); 90 | }); 91 | 92 | afterEach(async () => { 93 | await provider.removeInteractions(); 94 | }); 95 | 96 | it(`GIVEN vehicle id="${damagedVehicleId}", WHEN getDamageState() is executed, THEN the Promise will be resolved with true.`, async () => { 97 | await provider.addInteraction(validInteractionForDamagedVehicle); 98 | 99 | const result = DamageService.getDamageState(damagedVehicleId); 100 | 101 | await expect(result).to.be.eventually.true; 102 | await expect(provider.verify()).to.not.be.rejected; 103 | }); 104 | 105 | it(`GIVEN vehicle id="${notDamagedVehicleId}", WHEN getDamageState() is executed, THEN the Promise will be resolved with false.`, async () => { 106 | await provider.addInteraction(validInteractionForNotDamagedVehicle); 107 | 108 | const result = DamageService.getDamageState(notDamagedVehicleId); 109 | 110 | await expect(result).to.be.eventually.false; 111 | await expect(provider.verify()).to.not.be.rejected; 112 | }); 113 | 114 | it(`GIVEN non existing vehicle id="${nonExistingDamagedVehicleId}", WHEN getDamageState() is executed AND DamageService responds with NOT_FOUND, THEN the Promise will be rejected with HttpError(SERVICE_UNAVAILABLE).`, async () => { 115 | await provider.addInteraction(validInteractionForNonExisitingVehicle); 116 | 117 | const result = DamageService.getDamageState(nonExistingDamagedVehicleId); 118 | 119 | await expect(result).to.be.rejectedWith(HttpError).and.eventually.has.property('statusCode', SERVICE_UNAVAILABLE); 120 | await expect(provider.verify()).to.not.be.rejected; 121 | }); 122 | }); 123 | -------------------------------------------------------------------------------- /test/unit/services/VehicleService.spec.ts: -------------------------------------------------------------------------------- 1 | // General imports 2 | import * as chai from 'chai'; 3 | import * as sinonChai from 'sinon-chai'; 4 | import * as chaiAsPromised from 'chai-as-promised'; 5 | import { SinonStub, match, createSandbox } from 'sinon'; 6 | import { WrongArgumentsError } from '../../test-utils/WrongArgumentsError'; 7 | import { VehicleEntity, COLORS } from '../../../src/persistence/entities/VehicleEntity'; 8 | import { VehicleDto } from '../../../src/models/VehicleDto'; 9 | import { HttpError } from '../../../src/errors/HttpError'; 10 | import { SERVICE_UNAVAILABLE, NOT_FOUND } from 'http-status-codes'; 11 | import { RepositoryError } from '../../../src/errors/RepositoryError'; 12 | // Stubbing 13 | import VehicleRepository from '../../../src/persistence/VehicleRepository'; 14 | import { DamageService } from '../../../src/services/backends/DamageService'; 15 | import * as ClassTransformer from 'class-transformer'; 16 | import { ErrorHandler } from '../../../src/middlewares/ErrorHandler'; 17 | // Class under test 18 | import { VehicleService } from '../../../src/services/VehicleService'; 19 | 20 | chai.use(sinonChai); 21 | chai.use(chaiAsPromised); 22 | const expect = chai.expect; 23 | const sb = createSandbox(); 24 | 25 | describe('VehicleService', () => { 26 | describe('#getDetailedVehicle()', () => { 27 | const id = '1'; 28 | const vehicleEntity = new VehicleEntity(id, COLORS.BLUE); 29 | const vehicleDto = new VehicleDto(vehicleEntity.id, vehicleEntity.color); 30 | const expectedVehicleDto = new VehicleDto(vehicleDto.id, vehicleDto.color, true); 31 | const httpError = new HttpError(SERVICE_UNAVAILABLE); 32 | const someError = new TypeError('Some TypeError.'); 33 | const repositoryError = new RepositoryError('Some RepositoryError.'); 34 | const notFoundError = new HttpError(NOT_FOUND); 35 | 36 | beforeEach(() => { 37 | sb.stub(VehicleRepository, 'findOne').rejects(new WrongArgumentsError()); 38 | sb.stub(DamageService, 'getDamageState').rejects(new WrongArgumentsError()); 39 | sb.stub(ClassTransformer, 'plainToClass').throws(new WrongArgumentsError()); 40 | sb.stub(ErrorHandler, 'handleServiceErrors').rejects(new WrongArgumentsError()); 41 | }); 42 | 43 | afterEach(() => { 44 | sb.restore(); 45 | }); 46 | 47 | it(`GIVEN an id = "${id}", WHEN getDetailedVehicle() is executed, THEN the Promise will be resolved with ${expectedVehicleDto}.`, async () => { 48 | (VehicleRepository.findOne as SinonStub).withArgs(id).resolves(vehicleEntity); 49 | (ClassTransformer.plainToClass as SinonStub).withArgs(VehicleDto, vehicleEntity).returns(vehicleDto); 50 | (DamageService.getDamageState as SinonStub).withArgs(vehicleDto.id).resolves(true); 51 | 52 | const result = VehicleService.getDetailedVehicle(id); 53 | 54 | await expect(result).to.be.eventually.deep.equal(expectedVehicleDto); 55 | }); 56 | 57 | it(`GIVEN an id = "${id}" that doesn't exist, WHEN getDetailedVehicle() is executed, THEN the Promise will be rejected with HttpError(${NOT_FOUND}).`, async () => { 58 | (VehicleRepository.findOne as SinonStub).withArgs(id).resolves(null); 59 | (ErrorHandler.handleServiceErrors as SinonStub).withArgs(match.instanceOf(HttpError).and(match.hasOwn('statusCode', NOT_FOUND))).rejects(notFoundError); 60 | 61 | const result = VehicleService.getDetailedVehicle(id); 62 | 63 | await expect(result).to.be.rejectedWith(notFoundError); 64 | }); 65 | 66 | it(`GIVEN an id = "${id}", WHEN getDetailedVehicle() is executed AND getDamageState() rejects with ${httpError}, THEN the Promise will be rejected with ${httpError}.`, async () => { 67 | (VehicleRepository.findOne as SinonStub).withArgs(id).resolves(vehicleEntity); 68 | (ClassTransformer.plainToClass as SinonStub).withArgs(VehicleDto, vehicleEntity).returns(vehicleDto); 69 | (DamageService.getDamageState as SinonStub).withArgs(vehicleDto.id).rejects(httpError); 70 | (ErrorHandler.handleServiceErrors as SinonStub).withArgs(httpError).rejects(httpError); 71 | 72 | const result = VehicleService.getDetailedVehicle(id); 73 | 74 | await expect(result).to.be.rejectedWith(httpError); 75 | }); 76 | 77 | it(`GIVEN an id = "${id}", WHEN getDetailedVehicle() is executed AND plainToClass() rejects with ${someError}, THEN the Promise will be rejected with ${httpError}.`, async () => { 78 | (VehicleRepository.findOne as SinonStub).withArgs(id).resolves(vehicleEntity); 79 | (ClassTransformer.plainToClass as SinonStub).withArgs(VehicleDto, vehicleEntity).throws(someError); 80 | (ErrorHandler.handleServiceErrors as SinonStub).withArgs(someError).rejects(httpError); 81 | 82 | const result = VehicleService.getDetailedVehicle(id); 83 | 84 | await expect(result).to.be.rejectedWith(httpError); 85 | }); 86 | 87 | it(`GIVEN an id = "${id}", WHEN getDetailedVehicle() is executed AND findOne() rejects with ${repositoryError}, THEN the Promise will be rejected with ${httpError}.`, async () => { 88 | (VehicleRepository.findOne as SinonStub).withArgs(id).rejects(repositoryError); 89 | (ErrorHandler.handleServiceErrors as SinonStub).withArgs(repositoryError).rejects(httpError); 90 | 91 | const result = VehicleService.getDetailedVehicle(id); 92 | 93 | await expect(result).to.be.rejectedWith(httpError); 94 | }); 95 | }); 96 | }); 97 | -------------------------------------------------------------------------------- /src/persistence/common/DatabaseUtils.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Collection, CollectionMeta, DatabaseMeta, DocumentClient, ProcedureMeta, QueryError, RequestOptions, 3 | SqlQuerySpec, UniqueId, 4 | } from 'documentdb'; 5 | import { DATABASE_COLLECTION_THROUGHPUT } from '../../common/config'; 6 | import { bulkDeleteProc } from './stored-procedures/BulkDeleteStoredProcedure'; 7 | 8 | /** 9 | * Offers some basic database utils. 10 | */ 11 | export class DatabaseUtils { 12 | 13 | /** 14 | * Gets the database meta data or creates a new database if not found. 15 | * @param client The DocumentClient. 16 | * @param databaseId The database id. 17 | */ 18 | public static async getOrCreateDatabase(client: DocumentClient, databaseId: string): Promise { 19 | const querySpec: SqlQuerySpec = { 20 | parameters: [{ 21 | name: '@id', 22 | value: databaseId, 23 | }], 24 | query: 'SELECT * FROM root r WHERE r.id= @id', 25 | }; 26 | return new Promise((resolve, reject) => { 27 | client.queryDatabases(querySpec).toArray((queryErr: QueryError, results: DatabaseMeta[]) => { 28 | if (queryErr) { 29 | reject(queryErr); 30 | } else { 31 | if (results.length === 0) { 32 | const databaseSpec: UniqueId = { 33 | id: databaseId, 34 | }; 35 | client.createDatabase(databaseSpec, (createErr: QueryError, result: DatabaseMeta) => { 36 | if (createErr) { 37 | reject(createErr); 38 | } else { 39 | resolve(result); 40 | } 41 | }); 42 | } else { 43 | resolve(results[0]); 44 | } 45 | } 46 | }); 47 | }); 48 | } 49 | 50 | /** 51 | * Gets the collection meta data or creates a new collection if not found for the given database link. 52 | * @param client The DocumentClient. 53 | * @param databaseLink The link to the database. 54 | * @param collectionId The collection id. 55 | */ 56 | public static async getOrCreateCollection(client: DocumentClient, databaseLink: string, collectionId: string): Promise { 57 | const querySpec: SqlQuerySpec = { 58 | parameters: [{ 59 | name: '@id', 60 | value: collectionId, 61 | }], 62 | query: 'SELECT * FROM root r WHERE r.id=@id', 63 | }; 64 | return new Promise((resolve, reject) => { 65 | client.queryCollections(databaseLink, querySpec).toArray((queryErr: QueryError, results: CollectionMeta[]) => { 66 | if (queryErr) { 67 | reject(queryErr); 68 | } else { 69 | if (results.length === 0) { 70 | const collectionSpec: Collection = { 71 | id: collectionId, 72 | }; 73 | const options: RequestOptions = { 74 | offerThroughput: DATABASE_COLLECTION_THROUGHPUT, 75 | }; 76 | client.createCollection(databaseLink, collectionSpec, options, (createErr: QueryError, result: CollectionMeta) => { 77 | if (createErr) { 78 | reject(createErr); 79 | } else { 80 | resolve(result); 81 | } 82 | }); 83 | } else { 84 | resolve(results[0]); 85 | } 86 | } 87 | }); 88 | }); 89 | } 90 | 91 | /** 92 | * Gets the 'bulkDelete' stored procedure meta data or creates a new 'bulkDelete' stored procedure if not found for the given collection link. 93 | * @param client The DocumentClient. 94 | * @param collectionLink The collection link. 95 | */ 96 | public static async getOrCreateBulkDeleteStoredProcedure(client: DocumentClient, collectionLink: string): Promise { 97 | const querySpec: SqlQuerySpec = { 98 | parameters: [{ 99 | name: '@id', 100 | value: bulkDeleteProc.id, 101 | }], 102 | query: 'SELECT * FROM root r WHERE r.id=@id', 103 | }; 104 | 105 | return new Promise((resolve, reject) => { 106 | client.queryStoredProcedures(collectionLink, querySpec).toArray((queryErr: QueryError, resources: ProcedureMeta[]) => { 107 | if (queryErr) { 108 | reject(queryErr); 109 | } else { 110 | if (resources.length === 0) { 111 | client.createStoredProcedure(collectionLink, bulkDeleteProc, (err: QueryError, result: ProcedureMeta) => { 112 | if (err) { 113 | reject(err); 114 | } else { 115 | resolve(result); 116 | } 117 | }); 118 | } else { 119 | resolve(resources[0]); 120 | } 121 | } 122 | }); 123 | }); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/persistence/common/BaseCRUDRepository.ts: -------------------------------------------------------------------------------- 1 | import { transformAndValidate } from 'class-transformer-validator'; 2 | import { AbstractMeta, CollectionMeta, DatabaseMeta, DocumentClient, ProcedureMeta, QueryError, RetrievedDocument, SqlQuerySpec } from 'documentdb'; 3 | import { DATABASE_ID, MAX_DATABASE_QUERY_RETRIES } from '../../common/config'; 4 | import { DbQueryError } from '../../errors/DbQueryError'; 5 | import { RepositoryError } from '../../errors/RepositoryError'; 6 | import { UnexpectedServiceError } from '../../errors/UnexpectedServiceError'; 7 | import { ErrorHandler } from '../../middlewares/ErrorHandler'; 8 | import { DatabaseUtils } from './DatabaseUtils'; 9 | import DocumentDbClient from './DocumentClientFactory'; 10 | import { IRepository } from './IRepository'; 11 | import { IBulkDeleteResponseBody } from './stored-procedures/BulkDeleteStoredProcedure'; 12 | 13 | /** 14 | * The Base class for all Repositories. 15 | * Each Repository should extend this class and call its' construcotr first. 16 | */ 17 | export abstract class BaseCRUDRepository implements IRepository { 18 | 19 | /** 20 | * The database this service is running against. 21 | * Should not be manipulated in common cases. Is public for testing reasons. 22 | */ 23 | protected database: DatabaseMeta | undefined; 24 | 25 | /** 26 | * The collection of this repository. 27 | * Should not be manipulated in common cases. Is public for testing reasons. 28 | */ 29 | protected collection: CollectionMeta | undefined; 30 | 31 | /** 32 | * The stored procedure reference for cleaning the collection. 33 | */ 34 | protected bulkDeleteProcedure: ProcedureMeta | undefined; 35 | 36 | /** 37 | * The DocumentClient to work with the documentdb. 38 | */ 39 | protected docDbClient: DocumentClient; 40 | 41 | /** 42 | * The class constructor of the entity that is handled by the repository. 43 | */ 44 | protected classType: new (...args: any[]) => T; 45 | 46 | /** 47 | * The collectionId that is set initially. 48 | */ 49 | private collectionId: string; 50 | 51 | /** 52 | * Constructor of the BaseCRUDRepository. Is used to initialize the database and the collection. 53 | * It is setting up the connect and creates or gets both. 54 | * @param collectionId The collection id. 55 | * @param classType The class constructor of the entity that the repository handles. 56 | */ 57 | constructor(collectionId: string, classType: new (...args: any[]) => T) { 58 | this.docDbClient = DocumentDbClient; 59 | this.collectionId = collectionId; 60 | this.classType = classType; 61 | } 62 | 63 | /** 64 | * Creates a new object. 65 | * @param obj The object to create. 66 | * @returns {Promise} 67 | * @throws {RepositoryError | UnexpectedServiceError} 68 | */ 69 | public async create(obj: T): Promise { 70 | return this.retry(this.cr, obj); 71 | } 72 | 73 | /** 74 | * Finds an object by id. 75 | * Returns the retrieved document or null in case nothing was found. 76 | * @param id The id to search for. 77 | * @returns {Promise} 78 | * @throws {RepositoryError | UnexpectedServiceError} 79 | */ 80 | public async findOne(id: string): Promise { 81 | return this.retry(this.fi, id); 82 | } 83 | 84 | /** 85 | * Finds all objects. 86 | * Returns array of result if retrieved at least one document or null if nothing was found. 87 | * @returns {Promise} 88 | * @throws {RepositoryError | UnexpectedServiceError} 89 | */ 90 | public async findAll(): Promise { 91 | return this.retry(this.fiAll); 92 | } 93 | 94 | /** 95 | * Deletes an object. 96 | * @param obj The object. 97 | * @returns {Promise} 98 | * @throws {RepositoryError | UnexpectedServiceError} 99 | */ 100 | public async remove(obj: T): Promise { 101 | return this.retry(this.rm, obj); 102 | } 103 | 104 | /** 105 | * Deletes all objects. 106 | * @returns {Promise} 107 | * @throws {RepositoryError} 108 | */ 109 | public async removeAll(): Promise { 110 | return this.retry(this.rmAll); 111 | } 112 | 113 | /** 114 | * Retries the given method with the given arguments for docdb client timeout error (ECONNRESET) until the limit is reached. 115 | * @param method The method to retry. 116 | * @param args The arguments to apply to the given method. 117 | */ 118 | protected async retry(method: (...args: any[]) => A, ...args: any[]): Promise { 119 | // tslint:disable-next-line:no-unused-variable 120 | for (const retry of new Array(MAX_DATABASE_QUERY_RETRIES)) { 121 | try { 122 | return await method.apply(this, args); 123 | } catch (e) { 124 | if (e.retry === undefined || !e.retry) { 125 | throw e; 126 | } 127 | } 128 | } 129 | throw new RepositoryError('Maximum database query retries.'); 130 | } 131 | 132 | /** 133 | * Checks if the asynchronous initialization has already happened, or if it should be ran. 134 | * Should be considered to be placed in front of each repository method. 135 | */ 136 | protected async evaluateInit(): Promise { 137 | if (this.database === undefined || this.collection === undefined || this.bulkDeleteProcedure === undefined) { 138 | await this.initDbCollAndStoredProcedures(); 139 | } 140 | } 141 | 142 | /** 143 | * Initializes the database and the collection for the respective repository, as wells as the stored procedures needed. 144 | * Only public, that it can be used in integration testing to reinitialize the database and the collection. 145 | * @throws Error when getting or creating db or collection is not successful 146 | */ 147 | private async initDbCollAndStoredProcedures(): Promise { 148 | try { 149 | this.database = await DatabaseUtils.getOrCreateDatabase(this.docDbClient, DATABASE_ID); 150 | this.collection = await DatabaseUtils.getOrCreateCollection(this.docDbClient, this.database._self, this.collectionId); 151 | this.bulkDeleteProcedure = await DatabaseUtils.getOrCreateBulkDeleteStoredProcedure(this.docDbClient, this.collection._self); 152 | } catch (e) { 153 | throw e; 154 | } 155 | } 156 | 157 | /** 158 | * Creates a new object. 159 | * @param obj The object to create. 160 | * @returns {Promise} 161 | * @throws {RepositoryError | UnexpectedServiceError} 162 | */ 163 | private async cr(obj: T): Promise { 164 | try { 165 | await this.evaluateInit(); 166 | const retrieved = await new Promise((resolve, reject) => { 167 | this.docDbClient.createDocument(this.collection!._self, obj, (err: QueryError, result: RetrievedDocument) => { 168 | if (err) { 169 | reject(new DbQueryError(err)); 170 | } else { 171 | resolve(result); 172 | } 173 | }); 174 | }); 175 | return await transformAndValidate(this.classType, retrieved); 176 | } catch (e) { 177 | await ErrorHandler.handleRepositoryErrors(e); 178 | } 179 | throw new UnexpectedServiceError(); 180 | } 181 | 182 | /** 183 | * Finds an object by id. 184 | * Returns the retrieved document or null in case nothing was found. 185 | * @param id The id to search for. 186 | * @returns {Promise} 187 | * @throws {RepositoryError | UnexpectedServiceError} 188 | */ 189 | private async fi(id: string): Promise { 190 | try { 191 | await this.evaluateInit(); 192 | const querySpec: SqlQuerySpec = { 193 | parameters: [{ 194 | name: '@id', 195 | value: id, 196 | }], 197 | query: 'SELECT * FROM root r WHERE r.id=@id', 198 | }; 199 | const retrieved = await new Promise((resolve, reject) => { 200 | this.docDbClient.queryDocuments(this.collection!._self, querySpec).toArray((err: QueryError, results: RetrievedDocument[]) => { 201 | if (err) { 202 | reject(new DbQueryError(err)); 203 | } else { 204 | if (results.length === 0) { 205 | resolve(null); 206 | } else { 207 | resolve(results[0]); 208 | } 209 | } 210 | }); 211 | }); 212 | return retrieved !== null ? await transformAndValidate(this.classType, retrieved) : null; 213 | } catch (e) { 214 | await ErrorHandler.handleRepositoryErrors(e); 215 | } 216 | throw new UnexpectedServiceError(); 217 | } 218 | 219 | /** 220 | * Finds all objects. 221 | * Returns array of result if retrieved at least one document or null if nothing was found. 222 | * @returns {Promise} 223 | * @throws {RepositoryError | UnexpectedServiceError} 224 | */ 225 | private async fiAll(): Promise { 226 | try { 227 | await this.evaluateInit(); 228 | const querySpec: SqlQuerySpec = { 229 | parameters: [], 230 | query: 'SELECT * FROM root r', 231 | }; 232 | const retrieved = await new Promise((resolve, reject) => { 233 | this.docDbClient.queryDocuments(this.collection!._self, querySpec).toArray((err: QueryError, results: RetrievedDocument[]) => { 234 | if (err) { 235 | reject(new DbQueryError(err)); 236 | } else { 237 | if (results.length === 0) { 238 | resolve(null); 239 | } else { 240 | resolve(results); 241 | } 242 | } 243 | }); 244 | }); 245 | return retrieved !== null ? await transformAndValidate(this.classType, retrieved) : null; 246 | } catch (e) { 247 | await ErrorHandler.handleRepositoryErrors(e); 248 | } 249 | throw new UnexpectedServiceError(); 250 | } 251 | 252 | /** 253 | * Deletes an object. 254 | * @param obj The object. 255 | * @returns {Promise} 256 | * @throws {RepositoryError | UnexpectedServiceError} 257 | */ 258 | private async rm(obj: T): Promise { 259 | try { 260 | await this.evaluateInit(); 261 | let documentLink: string; 262 | if (obj._self !== undefined) { 263 | documentLink = obj._self; 264 | } else { 265 | throw new TypeError('The given type is not possible to remove.'); 266 | } 267 | await new Promise((resolve, reject) => { 268 | this.docDbClient.deleteDocument(documentLink, (err: QueryError, result: void) => { 269 | if (err) { 270 | reject(new DbQueryError(err)); 271 | } else { 272 | resolve(); 273 | } 274 | }); 275 | }); 276 | } catch (e) { 277 | await ErrorHandler.handleRepositoryErrors(e); 278 | } 279 | } 280 | 281 | /** 282 | * Deletes all objects. 283 | * @returns {Promise} 284 | * @throws {RepositoryError | UnexpectedServiceError} 285 | */ 286 | private async rmAll(): Promise { 287 | try { 288 | await this.evaluateInit(); 289 | if (await new Promise((resolve, reject) => { 290 | this.docDbClient.executeStoredProcedure(this.bulkDeleteProcedure!._self, ['SELECT * FROM root'], (err: QueryError, result: IBulkDeleteResponseBody) => { 291 | if (err) { 292 | reject(new DbQueryError(err)); 293 | } else { 294 | resolve(result.continuation); 295 | } 296 | }); 297 | })) { 298 | await this.rmAll(); 299 | } 300 | } catch (e) { 301 | await ErrorHandler.handleRepositoryErrors(e); 302 | } 303 | } 304 | } 305 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------