Update with wiring, bundling, unittests, code coverage

This commit is contained in:
2018-05-22 15:20:32 +02:00
parent 2c7496578b
commit dcb055a1e0
23 changed files with 1897 additions and 638 deletions

12
.editorconfig Normal file
View File

@@ -0,0 +1,12 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

View File

@@ -1,20 +1,28 @@
module.exports = function(config) {
config.set({
frameworks: ["jasmine", "karma-typescript"],
files: [
{ pattern: "src/**/*.ts" }
],
karmaTypescriptConfig: {
compilerOptions: {
module: "commonjs"
basePath: './',
frameworks: ['jasmine', 'karma-typescript'],
files: [{
pattern: './src/tests.ts'
},
tsconfig: "./tsconfig.json",
},
{
pattern: './src/**/*.ts'
}
],
exclude: [
'./src/index.ts'
],
preprocessors: {
"**/*.ts": ["karma-typescript"]
'**/*.ts': ['karma-typescript']
},
reporters: ["progress", "karma-typescript"],
browsers: ["Chrome"]
// optionally, configure the reporter
coverageReporter: {
type: 'html',
dir: 'coverage/'
},
tsconfig: "./tsconfig-tests.json",
//reporters: ['spec', 'progress', 'kjhtml', 'coverage'],
reporters: ['coverage', 'kjhtml', 'spec' ],
browsers: ['Chrome']
});
};

2161
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,14 @@
{
"name": "typescript-starter",
"name": "@nx/typescript-starter",
"version": "1.0.0",
"description": "Starter project for a typescript app",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"main": "dist/bundle.js",
"types": "dist/bundle.d.ts",
"scripts": {
"build": "tsc --listEmittedFiles",
"_install": "tsc --listEmittedFiles",
"build": "tsc --listEmittedFiles --project tsconfig-app.json",
"test": "karma start karma.conf.js -sm=false",
"test-build": "karma start karma.conf.js -sm=false --watch=false --single-run=true --reporters=junit,progress --browsers=Chrome"
"_install": "tsc --listEmittedFiles",
"_test-build": "karma start karma.conf.js -sm=false --watch=false --single-run=true --reporters=junit,progress,kjhtml --browsers=Chrome"
},
"repository": {
"type": "git",
@@ -20,14 +20,18 @@
"@types/jasmine": "^2.8.6",
"diff": "^3.4.0",
"handlebars": "^4.0.11",
"jasmine-core": "^2.99.1",
"karma": "^1.7.1",
"jasmine-core": "^3.1.0",
"karma": "^2.0.2",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.1.1",
"karma-commonjs": "^1.0.0",
"karma-jasmine": "^1.1.2",
"karma-jasmine-html-reporter": "^1.1.0",
"karma-junit-reporter": "^1.2.0",
"karma-spec-reporter": "0.0.32",
"karma-typescript": "^3.0.12",
"socket.io": "^2.0.4",
"typescript": "^2.7.2"
"typescript": "^2.9.0-dev.20180519"
},
"dependencies": {}
}

View File

@@ -0,0 +1,31 @@
import { IPortResolver } from '../domain/ports/IPortResolver';
export class PortResolver implements IPortResolver {
private _container : any = {};
constructor() {
}
register<T>(name : string, fn : () => T) {
this._container[name] = fn;
}
registerInstance<T>(name : string, fn : () => T) {
let _instance : any = null;
let getInstance = (fn : Function) => {
return () => {
if (!_instance) {
_instance = fn();
}
return _instance;
};
};
this._container[name] = getInstance(fn);
}
resolve<T>(name : string) : T {
if (name in this._container && typeof this._container[name] == 'function') {
return this._container[name]();
}
throw new Error('PortResolver can not resolve '+ name);
}
}

View File

@@ -1,7 +1,7 @@
import { Track } from "../../domain/models/Track";
import { MusicRepository } from "../../domain/ports/MusicRepository";
import { IMusicRepository } from "../../domain/ports/IMusicRepository";
export class VinylCatalog implements MusicRepository {
export class VinylCatalog implements IMusicRepository {
private vinylList: Track[] = new Array(
new Track(1, "DNA.", "Kendrick Lamar", 340),
@@ -14,8 +14,8 @@ export class VinylCatalog implements MusicRepository {
get(): Track[] {
return this.vinylList;
}
getById(id: number): Track | null {
return this.vinylList.filter(track => track.id == id).pop() as Track;
getById(id: number): Track {
return this.vinylList.filter(track => track.id == id).pop();
}
add(track: Track): number {
return this.vinylList.push(track);
@@ -30,7 +30,7 @@ export class VinylCatalog implements MusicRepository {
}
throw new Error("Track not found");
}
delete(id: number): Track | null {
delete(id: number): Track {
var track = this.getById(id);
if (track) {
var targetIndex = this.vinylList.indexOf(track);

View File

@@ -0,0 +1,10 @@
import { Track } from "../models/Track";
export interface IMusicRepository {
get() : Track[];
getById(id: number) : Track;
add(track: Track) : number;
edit(id: number, track: Track) : Track;
delete(id: number) : Track;
}

View File

@@ -0,0 +1,8 @@
export interface IPortResolver {
resolve<T>(name : string) : T;
}
export let currentPortResolver : IPortResolver;
export let setCurrentPortResolver = (resolver : IPortResolver) => currentPortResolver = resolver;

View File

@@ -1,3 +0,0 @@
export abstract class Injector {
abstract inject<T>(constructorFn: Function) : T;
}

View File

@@ -1,10 +0,0 @@
import { Track } from "../models/Track";
export abstract class MusicRepository {
abstract get() : Track[];
abstract getById(id: number) : Track | null;
abstract add(track: Track) : number;
abstract edit(id: number, track: Track) : Track;
abstract delete(id: number) : Track | null;
}

View File

@@ -0,0 +1,9 @@
import { IPortResolver, currentPortResolver } from '../ports/IPortResolver';
export class BaseService {
protected PortResolver: IPortResolver;
constructor() {
this.PortResolver = currentPortResolver;
}
}

View File

@@ -0,0 +1,26 @@
import {PortResolver} from '../../adapters/PortResolver';
import { currentPortResolver } from '../ports/IPortResolver';
const portResolver = currentPortResolver as PortResolver;
import { MusicCatalogService } from './MusicCatalogService';
import { IMusicRepository } from '../ports/IMusicRepository';
import { Track } from '../models/Track';
let fakeMusicRepository = { get: () =>{ console.log('fakeMusicRepository'); } } as IMusicRepository;
describe("MusicCatalogService", () => {
it('should create a new MusicCatalogService', (done) => {
let spiedGet = spyOn(fakeMusicRepository, 'get').and.returnValue([]);
portResolver.registerInstance<IMusicRepository>('IMusicRepository', () => fakeMusicRepository);
let musicCatalogService = new MusicCatalogService();
musicCatalogService.get();
expect(spiedGet.calls.count()).toBe(1);
done();
});
});

View File

@@ -1,20 +1,15 @@
import { MusicRepository } from "../../domain/ports/MusicRepository";
import { BaseService } from './BaseService';
import { IMusicRepository } from "../../domain/ports/IMusicRepository";
import { Track } from "../../domain/models/Track";
import { Injector } from "../../domain/ports/Injector";
export class MusicCatalogService extends BaseService {
private repository : IMusicRepository;
export class MusicCatalogService {
private repository: MusicRepository;
constructor(repository:MusicRepository){
this.repository = repository;
constructor(){
super();
this.repository = this.PortResolver.resolve<IMusicRepository>('IMusicRepository');
}
static fromInjector(injector : Injector) : MusicCatalogService {
return new MusicCatalogService(injector.inject(MusicRepository))
}
get(): Track[] {
return this.repository.get();
}

3
src/index.ts Normal file
View File

@@ -0,0 +1,3 @@
import { Wiring } from './wiring/Wiring';
const wiring = new Wiring();
wiring.apply();

3
src/tests.ts Normal file
View File

@@ -0,0 +1,3 @@
import { TestWiring } from './wiring/TestWiring';
const wiring = new TestWiring();
wiring.apply();

View File

@@ -1,11 +1,26 @@
import { PortResolver } from '../adapters/PortResolver';
import { currentPortResolver } from '../domain/ports/IPortResolver';
const portResolver = currentPortResolver as PortResolver;
import { MusicComponent } from "./MusicComponent";
import { MusicCatalogService } from '../domain/services/MusicCatalogService';
import { IMusicRepository } from '../domain/ports/IMusicRepository';
let fakeMusicRepository = {
get: () => [],
add: (Track: number) => null
} as any as IMusicRepository;
describe("MusicComponent", () => {
it('should create a new MusicComponent', (done) => {
console.log('Creating MusicComponent');
//let spiedAdd = spyOn(fakeMusicRepository, 'add').and.returnValue([]);
portResolver.registerInstance<IMusicRepository>('IMusicRepository', () => fakeMusicRepository);
let musicCatalogService = new MusicCatalogService();
let musicComponent = new MusicComponent();
console.log('MusicComponent created!');
expect(musicComponent).not.toBe(null);
done();
});

View File

@@ -1,19 +1,16 @@
import { MusicCatalogService } from "../domain/services/MusicCatalogService"
import { MusicRepository } from "../domain/ports/MusicRepository";
import { IMusicRepository } from "../domain/ports/IMusicRepository";
import { Track } from "../domain/models/Track";
import { VinylCatalog } from "../adapters/music/VinylCatalog";
import { Wiring } from "../wiring/Wiring";
export class MusicComponent {
constructor() {
const injector = Wiring.getInjector();
let musicCatalogService = MusicCatalogService.fromInjector(injector);
let musicCatalogService = new MusicCatalogService();
let track = new Track(8, "Niels 1st", "Niels Kooiman", 45);
musicCatalogService.add(track);
let tracks = musicCatalogService.get();
console.log(tracks);
}
}

View File

@@ -1,22 +0,0 @@
import { Injector } from "../domain/ports/Injector"
export class Container implements Injector {
private items : any = { };
public registerName(name : string, fn : Function) : void {
console.log(`registering ${name}`);
this.items[name] = fn;
}
public register(nameFn : Function, fn : Function) : void {
let name = (nameFn as any).name || nameFn.prototype.name;
console.log(`registering ${name}`);
this.items[name] = fn;
}
public inject<T>(fn: Function) : T {
let name = (fn as any).name || fn.prototype.name;
if (this.items[name]) {
return this.items[name]();
}
throw new Error(`Failed to resolve ${name} of ${JSON.stringify(Object.keys(this.items))}`);
}
}

13
src/wiring/TestWiring.ts Normal file
View File

@@ -0,0 +1,13 @@
import { IPortResolver, setCurrentPortResolver } from "../domain/ports/IPortResolver";
import { PortResolver } from "../adapters/PortResolver";
import { VinylCatalog } from "../adapters/music/VinylCatalog";
import { IMusicRepository } from "../domain/ports/IMusicRepository";
export class TestWiring {
public apply() : void {
const portResolver = new PortResolver();
portResolver.register<IMusicRepository>('IMusicRepository', () => new VinylCatalog());
setCurrentPortResolver(portResolver);
}
}

View File

@@ -1,19 +1,13 @@
import { Injector } from "../domain/ports/Injector";
import { Container } from "./Container";
import { IPortResolver, setCurrentPortResolver } from "../domain/ports/IPortResolver";
import { PortResolver } from "../adapters/PortResolver";
import { VinylCatalog } from "../adapters/music/VinylCatalog";
import { MusicRepository } from "../domain/ports/MusicRepository";
import { IMusicRepository } from "../domain/ports/IMusicRepository";
export class Wiring {
private static injector : Injector;
public static apply() : void {
const container = new Container();
container.register(MusicRepository, () => new VinylCatalog());
Wiring.injector = container;
}
public static getInjector() : Injector {
if (!Wiring.injector) {
Wiring.apply();
}
return Wiring.injector;
public apply() : void {
const portResolver = new PortResolver();
portResolver.register<IMusicRepository>('IMusicRepository', () => new VinylCatalog());
setCurrentPortResolver(portResolver);
}
}

10
tsconfig-app.json Normal file
View File

@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "amd",
"outFile": "./dist/bundle.js"
},
"files": [
"./src/index.ts"
]
}

9
tsconfig-tests.json Normal file
View File

@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
},
"include": [
"./src/**/*.ts"
]
}

View File

@@ -1,57 +1,15 @@
{
"compilerOptions": {
/* Basic Options */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
"compilerOptions": {
"target": "es5",
"declaration": true,
"sourceMap": true,
"outDir": "./dist",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
}
}