Skip to content

Commit

Permalink
Merge pull request #22 from kitesjs/refactor
Browse files Browse the repository at this point in the history
Refactor express config events
  • Loading branch information
vunb authored Sep 10, 2019
2 parents 39d6117 + d26b414 commit bb7f52c
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 68 deletions.
8 changes: 4 additions & 4 deletions packages/core/engine/kites-instance.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ function removeKitesConfigFiles() {

describe('kites engine', () => {

it('should fire ready callback', async () => {
it(`should fire 'ready' event`, async () => {

await engine().ready((core) => {
core.logger.info('Kites is ready!');
expect(core).instanceOf(KitesInstance);
await engine().on('ready', (app) => {
app.logger.info('Kites is ready!');
expect(app).instanceOf(KitesInstance);
}).init();

});
Expand Down
24 changes: 2 additions & 22 deletions packages/core/engine/kites-instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,8 @@ export interface IKites {
logger: Logger;
container: Container;
afterConfigLoaded(fn: KitesReadyCallback): IKites;
ready(callback: KitesReadyCallback): IKites;
discover(option?: string | boolean): IKites;
use(extension: KitesExtension | ExtensionDefinition): IKites;
// useMany(extension: Array<KitesExtension | ExtensionDefinition>): IKites;
use(extension: KitesExtension | ExtensionDefinition | ExtensionDefinition[]): IKites;
init(): Promise<IKites>;
}

Expand All @@ -73,7 +71,6 @@ export class KitesInstance extends EventEmitter implements IKites {
logger: Logger;

private fnAfterConfigLoaded: KitesReadyCallback;
private isReady: Promise<KitesInstance>;
private initialized: boolean;
private iocContainer: Container;

Expand All @@ -94,9 +91,6 @@ export class KitesInstance extends EventEmitter implements IKites {
// properties
this.logger = createLogger(this.name, this.options.logger);
this.fnAfterConfigLoaded = () => this;
this.isReady = new Promise((resolve) => {
this.on('initialized', resolve);
});

}

Expand Down Expand Up @@ -189,15 +183,6 @@ export class KitesInstance extends EventEmitter implements IKites {
}
}

/**
* Kites fire on ready
* @param callback
*/
ready(callback: KitesReadyCallback) {
this.isReady.then((kites) => callback(kites));
return this;
}

/**
* Use a function as a kites extension
* @param extension
Expand All @@ -207,11 +192,6 @@ export class KitesInstance extends EventEmitter implements IKites {
return this;
}

// useMany(extensions: Array<KitesExtension | ExtensionDefinition>) {
// this.extensionsManager.useMany(extensions);
// return this;
// }

/**
* Enable auto discover extensions
*/
Expand Down Expand Up @@ -268,7 +248,7 @@ export class KitesInstance extends EventEmitter implements IKites {
await this.initializeListeners.fire();

this.logger.info('kites initialized!');
this.emit('initialized', this);
this.emit('ready', this);

this.initialized = true;
return this;
Expand Down
71 changes: 40 additions & 31 deletions packages/core/extensions/extensions-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,50 @@ export class ExtensionsManager extends EventEmitter {
}
}

useMany(extensions: KitesExtension[]) {
/**
* Initialize extensions manager
*/
async init() {
this.availableExtensions = [];
// auto discover extensions
if (this.kites.options.discover || (this.kites.options.discover !== false && this.usedExtensions.length === 0)) {
let extensions = await discover({
cacheAvailableExtensions: this.kites.options.cacheAvailableExtensions,
extensionsLocationCache: this.kites.options.extensionsLocationCache,
logger: this.kites.logger,
mode: this.kites.options.mode,
rootDirectory: this.kites.options.rootDirectory,
tempDirectory: this.kites.options.tempDirectory,
});
this.kites.logger.debug('Discovered ' + extensions.length + ' extensions');
this.availableExtensions = this.availableExtensions.concat(extensions);
}
// filter extensions will be loaded?
this.availableExtensions = this.availableExtensions.concat(this.usedExtensions);
if (this.kites.options.extensions) {
let allowedExtensions = this.kites.options.extensions as string[];
this.availableExtensions = this.availableExtensions.filter(e => allowedExtensions.indexOf(e.name) > -1);
}

this.availableExtensions.sort(sorter);
return this.useMany(this.availableExtensions);

}

/**
* Execute init extensions
* @param extensions
*/
private useMany(extensions: KitesExtension[]) {
var promises = extensions.map((e) => this.useOne(e));
return Promise.all(promises);
}

useOne(extension: KitesExtension) {
/**
* Execute init one extension
* @param extension
*/
private useOne(extension: KitesExtension) {
// extends options
// Review _.assign(), _.defaults(), or _.merge?
const options = _.assign<
Expand Down Expand Up @@ -102,33 +140,4 @@ export class ExtensionsManager extends EventEmitter {
});
}

/**
* Initialize extensions manager
*/
async init() {
this.availableExtensions = [];
// auto discover extensions
if (this.kites.options.discover || (this.kites.options.discover !== false && this.usedExtensions.length === 0)) {
let extensions = await discover({
cacheAvailableExtensions: this.kites.options.cacheAvailableExtensions,
extensionsLocationCache: this.kites.options.extensionsLocationCache,
logger: this.kites.logger,
mode: this.kites.options.mode,
rootDirectory: this.kites.options.rootDirectory,
tempDirectory: this.kites.options.tempDirectory,
});
this.kites.logger.debug('Discovered ' + extensions.length + ' extensions');
this.availableExtensions = this.availableExtensions.concat(extensions);
}
// filter extensions will be loaded?
this.availableExtensions = this.availableExtensions.concat(this.usedExtensions);
if (this.kites.options.extensions) {
let allowedExtensions = this.kites.options.extensions as string[];
this.availableExtensions = this.availableExtensions.filter(e => allowedExtensions.indexOf(e.name) > -1);
}

this.availableExtensions.sort(sorter);
return this.useMany(this.availableExtensions);

}
}
1 change: 1 addition & 0 deletions packages/core/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ function createLogger(name: string, options?: any): Logger {
exitOnError: false,
level: 'info',
format: format.combine(
format.splat(), // formats level.message based on Node's util.format().
format.label({ label: name }),
format.colorize(),
format.timestamp(),
Expand Down
23 changes: 13 additions & 10 deletions packages/express/express.extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export class ExpressExtension implements KitesExtension {
}

logStart() {
this.kites.emit('after:express:config');
if (this.kites.express.server) {
const port = this.kites.express.server.address().port;
this.kites.logger.info(
Expand Down Expand Up @@ -75,8 +76,7 @@ export class ExpressExtension implements KitesExtension {
}

configureViewEngine(app: Express, opts: any) {
var configView = this.kites.emit('express:config:view', app, opts);
if (configView) {
if (this.kites.emit('express:config:view', app, opts)) {
this.kites.logger.debug('Express view engine has customized by user!');
return;
}
Expand Down Expand Up @@ -145,11 +145,6 @@ export class ExpressExtension implements KitesExtension {
configureExpressApp(app: Express, kites: KitesInstance) {
kites.express.app = app;

app.options('*', cors({
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'MERGE'],
origin: true
}));

// show powered by
if (!this.options.poweredBy) {
app.disable('x-powered-by');
Expand All @@ -160,6 +155,11 @@ export class ExpressExtension implements KitesExtension {
});
}

// default config
app.options('*', cors({
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'MERGE'],
origin: true
}));
app.use(bodyParser.urlencoded({
extended: false,
limit: this.options.inputRequestLimit || '10mb'
Expand All @@ -170,19 +170,22 @@ export class ExpressExtension implements KitesExtension {
app.use(cookieParser());
app.use(cors());

kites.logger.debug('Express expanding ...');

// extend express mixin
app.use(mixinReq(kites));
app.use(mixinRes(kites));
app.use(mixinResView(kites));

kites.logger.debug('Express expanding ...');
kites.emit('before:express:config', app);

// default routes
app.use('/_kites', defaultRouter());

kites.logger.debug('Express starting configure ...');
kites.emit('express:config', app);

// config static file
// config static assets
kites.emit('express:config:static', app);
if (typeof this.options.static === 'string') {
kites.logger.debug('Express serve static files at: ' + this.options.static);
app.use(express.static(this.options.static));
Expand Down
2 changes: 1 addition & 1 deletion sample/01-todo-app/todo/todo.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class TodoController {
public svTodo: TodoService,
@Inject(KITES_INSTANCE) private kites: KitesInstance,
) {
kites.logger.info('Hello todo controller!!!');
kites.logger.info('Hello %s controller!!! (%s)', 'todo', 3);
kites.logger.info(svTodo.getAll());
}

Expand Down

0 comments on commit bb7f52c

Please sign in to comment.