Skip to content

Commit 30bf9c7

Browse files
author
hirsch88
committed
increase ioc
1 parent edf7a06 commit 30bf9c7

File tree

11 files changed

+238
-27
lines changed

11 files changed

+238
-27
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { events } from '../../core/api/events';
2+
import { Log } from '../../core/log/';
3+
4+
const log = new Log('api:listeners:UserCreated');
5+
6+
7+
export class UserCreatedListener {
8+
9+
static Event = Symbol('UserCreated');
10+
11+
public async run(user: any): Promise<void> {
12+
log.info('Receive event UserCreated', user);
13+
}
14+
15+
}

src/api/models/User.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { injectable } from 'inversify';
12
import { Bookshelf } from '../../config/Database';
23
import { Tables } from '../../constants/Tables';
34

@@ -8,6 +9,7 @@ import { Tables } from '../../constants/Tables';
89
* @class User
910
* @extends {Bookshelf.Model<User>}
1011
*/
12+
@injectable()
1113
export class User extends Bookshelf.Model<User> {
1214

1315
public static async fetchById(id: number): Promise<User> {

src/api/repositories/UserRepository.ts

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
import * as Bookshelf from 'bookshelf';
2+
import { injectable, inject, named } from 'inversify';
3+
import { Types } from '../../constants/Types';
4+
import { Model } from '../../constants/Targets';
25
import { User } from '../models/User';
36
import { DatabaseException } from '../exceptions/DatabaseException';
47
import { NotFoundException } from '../exceptions/NotFoundException';
@@ -9,8 +12,13 @@ import { NotFoundException } from '../exceptions/NotFoundException';
912
* @export
1013
* @class UserRepository
1114
*/
15+
@injectable()
1216
export class UserRepository {
1317

18+
constructor(
19+
@inject(Types.Model) @named(Model.User) public UserModel: typeof User
20+
) { }
21+
1422
/**
1523
* Retrieves all user data out of the database
1624
*
@@ -19,8 +27,8 @@ export class UserRepository {
1927
*
2028
* @memberof UserRepository
2129
*/
22-
public static async findAll(): Promise<Bookshelf.Collection<User>> {
23-
const users = await User.fetchAll();
30+
public async findAll(): Promise<Bookshelf.Collection<User>> {
31+
const users = await this.UserModel.fetchAll();
2432
return <Bookshelf.Collection<User>>users;
2533
}
2634

@@ -31,8 +39,8 @@ export class UserRepository {
3139
* @param {number} id of the user
3240
* @returns {Promise<User>}
3341
*/
34-
public static async findOne(id: number): Promise<User> {
35-
return User.fetchById(id);
42+
public async findOne(id: number): Promise<User> {
43+
return this.UserModel.fetchById(id);
3644
}
3745

3846
/**
@@ -42,8 +50,8 @@ export class UserRepository {
4250
* @param {number} id of the user
4351
* @returns {Promise<User>}
4452
*/
45-
public static async findByUserId(userId: string): Promise<User> {
46-
return User.fetchByUserId(userId);
53+
public async findByUserId(userId: string): Promise<User> {
54+
return this.UserModel.fetchByUserId(userId);
4755
}
4856

4957
/**
@@ -54,11 +62,11 @@ export class UserRepository {
5462
* @param {*} data is the new user
5563
* @returns {Promise<User>}
5664
*/
57-
public static async create(data: any): Promise<User> {
58-
const user = User.forge<User>(data);
65+
public async create(data: any): Promise<User> {
66+
const user = this.UserModel.forge<User>(data);
5967
try {
6068
const createdUser = await user.save();
61-
return await User.fetchById(createdUser.id);
69+
return await this.UserModel.fetchById(createdUser.id);
6270
} catch (error) {
6371
throw new DatabaseException('Could not create the user!', error);
6472
}
@@ -72,11 +80,11 @@ export class UserRepository {
7280
* @param {*} data
7381
* @returns {Promise<User>}
7482
*/
75-
public static async update(id: number, data: any): Promise<User> {
76-
const user = User.forge<User>({ id: id });
83+
public async update(id: number, data: any): Promise<User> {
84+
const user = this.UserModel.forge<User>({ id: id });
7785
try {
7886
const updatedUser = await user.save(data, { patch: true });
79-
return await User.fetchById(updatedUser.id);
87+
return await this.UserModel.fetchById(updatedUser.id);
8088

8189
} catch (error) {
8290
throw new DatabaseException('Could not update the user!', error);
@@ -91,8 +99,8 @@ export class UserRepository {
9199
* @param {number} id
92100
* @returns {Promise<void>}
93101
*/
94-
public static async destroy(id: number): Promise<void> {
95-
let user = User.forge<User>({ id: id });
102+
public async destroy(id: number): Promise<void> {
103+
let user = this.UserModel.forge<User>({ id: id });
96104
try {
97105
user = await user.fetch({ require: true });
98106
} catch (error) {

src/api/services/UsersService.ts

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
import * as Bookshelf from 'bookshelf';
22
import { injectable, inject, named } from 'inversify';
3-
import { Repository } from '../../constants/Targets';
3+
import { Core, Repository } from '../../constants/Targets';
44
import { Types } from '../../constants/Types';
55
import { Log } from '../../core/log';
6+
import { EventEmitter } from '../../core/api/events';
67
import { Validate, Request } from '../../core/api/Validate';
78
import { NotFoundException } from '../exceptions/NotFoundException';
89
import { UserCreateRequest } from '../requests/UserCreateRequest';
910
import { UserUpdateRequest } from '../requests/UserUpdateRequest';
1011
import { UserRepository } from '../repositories/UserRepository';
1112
import { User } from '../models/User';
13+
import { UserCreatedListener } from '../listeners/UserCreatedListener';
1214

13-
const log = new Log('api:services:UserService');
1415

1516
/**
1617
* UserService
@@ -19,15 +20,21 @@ const log = new Log('api:services:UserService');
1920
* database actions. Furthermore you should throw events here if
2021
* necessary.
2122
*
22-
* @export0'
23+
* @export
2324
* @class UserService
2425
*/
2526
@injectable()
2627
export class UserService {
2728

29+
public log: Log;
30+
2831
constructor(
29-
@inject(Types.Repository) @named(Repository.UserRepository) public userRepo: typeof UserRepository
30-
) { }
32+
@inject(Types.Repository) @named(Repository.UserRepository) public userRepo: UserRepository,
33+
@inject(Types.Core) @named(Core.Log) public Logger: typeof Log,
34+
@inject(Types.Core) @named(Core.Events) public events: EventEmitter
35+
) {
36+
this.log = new Logger('api:services:UserService');
37+
}
3138

3239
/**
3340
* This returns all user database objects
@@ -45,7 +52,7 @@ export class UserService {
4552
public async findOne(id: number): Promise<User> {
4653
const user = await this.userRepo.findOne(id);
4754
if (user === null) {
48-
log.warn(`User with the id=${id} was not found!`);
55+
this.log.warn(`User with the id=${id} was not found!`);
4956
throw new NotFoundException(id);
5057
}
5158
return user;
@@ -60,7 +67,7 @@ export class UserService {
6067
public async findByUserId(userId: string): Promise<User> {
6168
const user = await this.userRepo.findByUserId(userId);
6269
if (user === null) {
63-
log.warn(`User with the userId=${userId} was not found!`);
70+
this.log.warn(`User with the userId=${userId} was not found!`);
6471
throw new NotFoundException(userId);
6572
}
6673
return user;
@@ -77,6 +84,7 @@ export class UserService {
7784
public async create( @Request(UserCreateRequest) data: any): Promise<User> {
7885
// If the request body was valid we will create the user
7986
const user = await this.userRepo.create(data);
87+
this.events.emit(UserCreatedListener.Event, user.toJSON());
8088
return user;
8189
}
8290

src/constants/Targets.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,15 @@
66
* our controllers, services and repositories
77
*/
88

9+
export const Lib = {
10+
Request: 'Request'
11+
};
12+
13+
export const Core = {
14+
Events: 'Events',
15+
Log: 'Log'
16+
};
17+
918
export const Controller = {
1019
UserController: 'UserController'
1120
};
@@ -14,6 +23,14 @@ export const Service = {
1423
UserService: 'UserService'
1524
};
1625

26+
export const Model = {
27+
User: 'User'
28+
};
29+
1730
export const Repository = {
1831
UserRepository: 'UserRepository'
1932
};
33+
34+
export const Middleware = {
35+
AuthenticateMiddleware: 'AuthenticateMiddleware'
36+
};

src/constants/Types.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ import { TYPE } from 'inversify-express-utils';
1010

1111

1212
const myType = {
13-
// UserService: Symbol('UserService'),
14-
// UserRepository: Symbol('UserRepository'),
13+
Lib: Symbol('Lib'),
14+
Core: Symbol('Core'),
15+
Model: Symbol('Model'),
1516
Service: Symbol('Service'),
16-
Repository: Symbol('Repository')
17+
Repository: Symbol('Repository'),
18+
Middleware: Symbol('Middleware')
1719
};
1820

1921
export const Types = Object.assign(TYPE, myType);

src/container.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,33 @@
99
import { interfaces } from 'inversify-express-utils';
1010
import { Container } from 'inversify';
1111
import { Types } from './constants/Types';
12-
import { Controller, Service, Repository } from './constants/Targets';
12+
import { Core, Model, Controller, Service, Repository } from './constants/Targets';
13+
14+
/**
15+
* Core Features
16+
*/
17+
import { events, EventEmitter } from './core/api/events';
18+
import { Log } from './core/log';
1319

1420
/**
1521
* User Resource
1622
*/
1723
import { UserController } from './api/controllers/UserController';
1824
import { UserService } from './api/services/UsersService';
1925
import { UserRepository } from './api/repositories/UserRepository';
26+
import { User } from './api/models/User';
27+
2028

2129
const container = new Container();
2230

31+
container.bind<EventEmitter>(Types.Core).toConstantValue(events).whenTargetNamed(Core.Events);
32+
container.bind<typeof Log>(Types.Core).toConstantValue(Log).whenTargetNamed(Core.Log);
33+
34+
/**
35+
* Model
36+
*/
37+
container.bind<any>(Types.Model).toConstantValue(User).whenTargetNamed(Model.User);
38+
2339
/**
2440
* Controllers
2541
*/
@@ -33,7 +49,7 @@ container.bind<UserService>(Types.Service).to(UserService).whenTargetNamed(Servi
3349
/**
3450
* Repositories
3551
*/
36-
container.bind<UserRepository>(Types.Repository).toConstantValue(UserRepository).whenTargetNamed(Repository.UserRepository);
52+
container.bind<UserRepository>(Types.Repository).to(UserRepository).whenTargetNamed(Repository.UserRepository);
3753

3854

3955
export default container;

src/core/Bootstrap.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@
99
* small monitor app.
1010
*/
1111

12+
import * as fs from 'fs';
1213
import * as express from 'express';
1314
import * as monitor from 'express-status-monitor';
1415
import { Container } from 'inversify';
1516
import { InversifyExpressServer } from 'inversify-express-utils';
1617
import { Environment } from './Environment';
1718
import { my } from 'my-express';
1819
import { exceptionHandler, extendExpressResponse } from './api';
20+
import { events } from './api/events';
1921
import { Log } from './log';
2022

2123
const log = new Log('core:Bootstrap');
@@ -155,6 +157,27 @@ export class Bootstrap {
155157
return app;
156158
}
157159

160+
/**
161+
* Sets up the event listeners and registers them.
162+
*
163+
* @static
164+
*
165+
* @memberof Bootstrap
166+
*/
167+
static setupEventListeners(): void {
168+
const baseFolder = __dirname.indexOf('/src/') >= 0 ? '/src/' : '/dist/';
169+
const basePath = __dirname.substring(0, __dirname.indexOf(baseFolder));
170+
const path = `${basePath}${baseFolder}api/listeners`;
171+
fs.readdir(path, (err: any, items: string[]): void => {
172+
for (let i = 0; i < items.length; i++) {
173+
const name = items[i].substring(0, items[i].length - 3);
174+
const Listener = require(`${path}/${items[i]}`)[name];
175+
const listener = new Listener();
176+
events.on(Listener.Event, (...args) => listener.run(...args));
177+
}
178+
});
179+
}
180+
158181
/**
159182
* Well this method just normalizes the given port :-)
160183
*

src/core/Server.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export class Server {
4343
*/
4444
static onStartUp(app: express.Application): void {
4545
log.info(``);
46-
log.info(`Aloha, your app is ready on ${app.get('host')}:${app.get('port')}`);
46+
log.info(`Aloha, your app is ready on ${app.get('host')}:${app.get('port')}${process.env.APP_URL_PREFIX}`);
4747
log.info(`To shut it down, press <CTRL> + C at any time.`);
4848
log.info(``);
4949
log.debug('-------------------------------------------------------');

src/core/api/events.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* core.api.events
3+
* -----------------------------------
4+
*
5+
* TODO
6+
*/
7+
8+
import { EventEmitter } from 'events';
9+
export { EventEmitter } from 'events';
10+
11+
export const events = new EventEmitter();

0 commit comments

Comments
 (0)