Skip to content

Commit

Permalink
Many small fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Saulo Vallory committed Aug 1, 2019
1 parent bdda6e1 commit 11a9287
Show file tree
Hide file tree
Showing 7 changed files with 143 additions and 143 deletions.
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,18 @@
"url": "https://github.com/tokilabs/tractor/issues"
},
"homepage": "https://github.com/tokilabs/tractor#README",
"peerDependencies": {
"@cashfarm/plow": "^0.5.0"
},
"dependencies": {
"@cashfarm/lang": "^0.8.0",
"@cashfarm/plow": "^0.5.0",
"@hapi/boom": "^7.4.2",
"@hapi/glue": "6.x.x",
"@hapi/good": "8.x.x",
"@hapi/good-console": "8.x.x",
"@hapi/good-squeeze": "5.x.x",
"@hapi/hapi": "18.x.x",
"@hapi/inert": "5.x.x",
"@hapi/inert": "^5.2.1",
"@hapi/joi": "15.x.x",
"@hapi/joi-date": "1.x.x",
"@hapi/vision": "5.x.x",
Expand All @@ -65,6 +67,7 @@
"@types/eslint": "^4.16.6",
"@types/gh-pages": "^2.0.0",
"@types/hapi__boom": "^7.4.0",
"@types/hapi__glue": "^6.1.0",
"@types/hapi__hapi": "^18.2.5",
"@types/hapi__joi": "^15.0.0",
"@types/pubsub-js": "^1.5.18",
Expand Down
161 changes: 76 additions & 85 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,73 +1,82 @@
import * as Confidence from 'confidence';
import * as Glue from '@hapi/glue';

const goodOptions = {
ops: {
interval: 1000
},
reporters: {
console: [
{
module: 'good-squeeze',
name: 'Squeeze',
args: [
{
// log: '*',
error: '*',
response: '*'
// ops: '*'
}
]
},
{
module: 'good-console',
args: [
{
log: '*',
error: '*',
response: '*',
ops: '*'
}
]
},
'stdout'
]
}
};

const manifest: any = {
const manifest /*: Glue.Manifest*/ = {
$meta: 'This file defines the microservice.',
connections: [{
labels: [ 'http', 'api' ],
port: 3000
}],
registrations: {
$filter: 'env',
$default: [
{ plugin: 'inert' },
{ plugin: 'vision' },
{ plugin: 'blipp' },
{
plugin: 'tv'
// options: {
// endpoint: 'tv'
// }
},
{
plugin: {
register: 'good',
options: goodOptions
}
},
{
plugin: {
register: 'hapi-swagger',
server: {
port: { $param: 'port' },
debug: {
$filter: 'debug',
$default: { log: ['debug', 'error', 'uncaught'], request: ['debug', 'error', 'uncaught'] },
off: { log: false, request: false }
},

router: {
isCaseSensitive: false,
stripTrailingSlash: true
},
routes: {
cors: {
$filter: 'cors',
'on': {
origin: ['*']
},
'off': false
}
}
},
register: {
plugins: {
$filter: 'env',
$default: [
{ plugin: '@hapi/inert' },
{ plugin: '@hapi/vision' },
{ plugin: 'blipp' },
{
plugin: '@hapi/good',
options: {
ops: {
interval: 1000
},
reporters: {
console: [
{
module: '@hapi/good-squeeze',
name: 'Squeeze',
args: [
{
// log: '*',
error: '*',
response: '*'
// ops: '*'
}
]
},
{
module: '@hapi/good-console',
args: [
{
log: '*',
error: '*',
response: '*',
ops: '*'
}
]
},
'stdout'
]
}
}
},
{
plugin: 'hapi-swagger',
options: {
// title: 'Doare Payments API Documentation',
basePath: '/',
// version: Config.get('api.version')
info: {
title: 'Test API Documentation',
description: 'This is a sample example of API documentation.'
title: 'Tractor Generated API Documentation',
description: 'This doc is given to you by Tractor.'
// version: Pack.version,
// termsOfService: 'https://github.com/glennjones/hapi-swagger/',
// contact: {
Expand All @@ -81,29 +90,11 @@ const manifest: any = {
}
}
}
}
],
production: [
{ plugin: 'blipp' }
// production plugins here
]
},
server: {
debug: {
$filter: 'debug',
$default: { log: ['debug', 'error', 'uncaught'], request: ['debug', 'error', 'uncaught'] },
off: { log: false, request: false }
},
connections: {
router: {
isCaseSensitive: false,
stripTrailingSlash: true
},
routes: {
cors: {
origin: ['*']
}
}
],
production: [
{ plugin: 'blipp' }
// production plugins here
]
}
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/decorators/controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// import { decorate } from 'inversify';
import { provide } from 'inversify-binding-decorators';
import { provide } from '@cashfarm/plow';

import { ConcreteType, Exception } from '@cashfarm/lang';
import { container } from '@cashfarm/plow';
Expand Down
6 changes: 5 additions & 1 deletion src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
export const IController = Symbol.for('@cashfarm/tractor.IController');
// tslint:disable-next-line:no-empty-interface
/**
* This interface exists so you can mark classes as controllers
* It's an empty interface, so any class will comply, but you can
* use this group all your controllers when generating documentation
*/
export interface IController {}
19 changes: 10 additions & 9 deletions src/router.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
import { Server } from '@hapi/hapi';
import { inject, multiInject } from 'inversify';

import { IController } from './interfaces';
import { EndpointMetadata, EndpointMetadataKey } from './decorators/endpoint';
import { injectable } from 'inversify';
import { ConcreteType } from '@cashfarm/lang';
import { Controllers } from './decorators';

const debug = require('debug')('tractor');

export const IRouter = Symbol.for('@cashfarm/tractor.IRouter');

export interface IRouter {
addControllers(ctrls: IController[]): void;
addController(ctrl: IController): void;
addControllers(ctrls: ConcreteType[]): void;
addController(ctrl: ConcreteType): void;
}

@injectable()
export class Router implements IRouter {
@inject('ApiPrefix')
public prefix = '';

private controllers: IController[];
private controllers: ConcreteType[];

constructor(
@inject(Server) private server: Server,
@multiInject(IController) controllers: IController[]) {
@multiInject(Controllers) controllers: ConcreteType[]) {
this.controllers = [];

if (Array.isArray(controllers) && controllers.length)
Expand All @@ -35,16 +36,16 @@ export class Router implements IRouter {
*
* @memberof Router
*/
public addControllers(ctrls: IController[]): void {
public addControllers(ctrls: ConcreteType[]): void {
if (!Array.isArray(ctrls))
throw new Error(`Router.addControllers() expects an array of IController objects, but received ${JSON.stringify(ctrls)}`);
throw new Error(`Router.addControllers() expects an array of classes, but received ${JSON.stringify(ctrls)}`);

this.controllers = this.controllers.concat(this.controllers, ctrls);

ctrls.forEach(c => this.addController(c));
}

public addController(ctrl: IController): void {
public addController(ctrl: ConcreteType): void {
debug(`Adding controller ${ctrl.constructor.name}`);

const edpts: { [k: string]: EndpointMetadata } = Reflect.getMetadata(EndpointMetadataKey, ctrl.constructor);
Expand All @@ -54,7 +55,7 @@ export class Router implements IRouter {
});
}

private registerEndpoint(ctrl: IController, methodKey: PropertyKey, meta: EndpointMetadata) {
private registerEndpoint(ctrl: ConcreteType, methodKey: PropertyKey, meta: EndpointMetadata) {
const path = (this.prefix + meta.path).trim().length === 0 ? '/' : (this.prefix + meta.path);

this.server.log('debug', `Mapping route ${path} to ${ctrl.constructor.name}.${String(methodKey)}`);
Expand Down
67 changes: 28 additions & 39 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import 'reflect-metadata';
import { betterErrors } from './ext/betterErrors';
import { Server } from '@hapi/hapi';
import * as Glue from '@hapi/glue';

import Config from './config';
import { interfaces as IoC, decorate, inject, injectable, multiInject } from 'inversify';
Expand All @@ -15,9 +16,9 @@ import { ITractorConfig } from './iTractorConfig';
import { setupContainer } from './container.config';
import { Controllers } from './decorators';
import { listContainerBindings } from './util';
import { ConcreteType } from '@cashfarm/lang';

const debug = require('debug')('tractor');
const Glue = require('glue');

const composeOptions = {
relativeTo: __dirname
Expand All @@ -37,61 +38,49 @@ export async function createServer(
override?: ITractorConfig|((server: ITractorServer) => void),
customContainer?: Container):
Promise<Server> {
return new Promise<Server>( (resolve, reject) => {

const container = customContainer || plowContainer;

const options: ITractorConfig = {
debug: true,
debug: process.env.NODE_ENV !== 'production',
enableCors: true,
port: 3000
port: 3210
};

if (typeof override === 'object') {
Object.assign(options, override);
}

const criteria = {
const criteria = Object.assign({
env: process.env.NODE_ENV || 'development',
debug: 'on'
};

const manifest = Config.get('/', criteria);
cors: options.enableCors ? 'on' : 'off'
}, options);

// @todo Find a better way to configure the port
manifest.connections[0].port = options.port;
const manifest = Config.get('/', criteria) as Glue.Manifest;

Glue.compose(manifest, composeOptions, (err?: any, server?: ITractorServer) => {
if (err) {
return reject(err);
}
return Glue.compose(manifest, composeOptions)
.then((server?: ITractorServer) => {
setupContainer(container, serviceName, server, options);
server.decorate('server', 'getContainer', () => container);

setupContainer(container, serviceName, server, options);
server.decorate('server', 'getContainer', () => container);
if (options.debug) {
server.settings.debug = { log: ['error', 'uncaught'], request: ['error', 'uncaught'] };
server.ext('onPreResponse', betterErrors);
}

if (options.enableCors) {
const addCorsHeaders = require('hapi-cors-headers');
server.ext('onPreResponse', addCorsHeaders);
}
if (typeof override === 'function') {
override(server);
}

if (options.debug) {
server.settings.debug = { log: ['error', 'uncaught'], request: ['error', 'uncaught'] };
server.ext('onPreResponse', betterErrors);
}
server.events.on('start', () => {
const ctrls = container.getAll<ConcreteType>(Controllers);
debug('Controllers:', ctrls);
server.getRouter().addControllers(ctrls);

if (typeof override === 'function') {
override(server);
}
debug(`Container (${container.guid}) bindings so far`);
listContainerBindings(container).map( (b: string, i: number) => debug(i, b));
});

server.events.on('start', () => {
const ctrls = container.getAll(Controllers);
debug('Controllers:', ctrls);
server.getRouter().addControllers(ctrls);

debug(`Container (${container.guid}) bindings so far`);
listContainerBindings(container).map( (b: string, i: number) => debug(i, b));
return server;
});

resolve(server);
});
});
}
Loading

0 comments on commit 11a9287

Please sign in to comment.