Skip to content
This repository has been archived by the owner on Jan 24, 2022. It is now read-only.

Commit

Permalink
Improve typings and imports
Browse files Browse the repository at this point in the history
  • Loading branch information
onechiporenko committed Dec 3, 2018
1 parent 57cf577 commit 272dcff
Show file tree
Hide file tree
Showing 13 changed files with 625 additions and 837 deletions.
10 changes: 5 additions & 5 deletions lib/cron.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {ScheduledTask} from 'node-cron';

export default class Cron {
public static getCron() {
public static getCron(): Cron {
if (!Cron.instance) {
Cron.instance = new Cron();
}
Expand All @@ -20,29 +20,29 @@ export default class Cron {
this.tasks = {};
}

public add(id: string, job: ScheduledTask) {
public add(id: string, job: ScheduledTask): void {
this.tasks[id] = job;
}

public has(id: string): boolean {
return this.tasks.hasOwnProperty(id);
}

public start(id: string) {
public start(id: string): void {
const task = this.tasks[id];
if (task) {
task.start();
}
}

public stop(id: string) {
public stop(id: string): void {
const job = this.tasks[id];
if (job) {
job.stop();
}
}

public destroy(id: string) {
public destroy(id: string): void {
const job = this.tasks[id];
if (job) {
job.destroy();
Expand Down
4 changes: 2 additions & 2 deletions lib/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const logger = winston.createLogger({
});

// from https://github.com/expressjs/express/issues/3308#issuecomment-300957572
export function printRoutesMap(path, layer) {
export function printRoutesMap(path: string[], layer: any): void {
if (layer.route) {
layer.route.stack.forEach(printRoutesMap.bind(null, path.concat(split(layer.route.path))));
} else if (layer.name === 'router' && layer.handle.stack) {
Expand All @@ -19,7 +19,7 @@ export function printRoutesMap(path, layer) {
}
}

function split(thing) {
function split(thing: any): string[]|string {
if (typeof thing === 'string') {
return thing.split('/');
} else if (thing.fast_slash) {
Expand Down
46 changes: 42 additions & 4 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,45 @@
import {Factory, Lair} from 'lair-db';
import {
CRUDOptions,
DevInfo,
DevInfoItem,
Factory,
FactoryData,
FieldMetaAttr,
Lair,
Meta,
MetaAttr,
MetaAttrType,
Record,
RelationshipMetaAttr,
Relationships,
SequenceMetaAttr,
} from 'lair-db';
import Cron from './cron';
import Job from './job';
import Route from './route';
import Job, { JobOptions, tickCallback } from './job';
import Route, { CustomNext, Handler } from './route';
import Server from './server';

export {Factory, Lair, Route, Server, Cron, Job};
export {
CRUDOptions,
DevInfoItem,
DevInfo,
Lair,
Factory,
MetaAttrType,
FactoryData,
Meta,
Record,
Relationships,
MetaAttr,
FieldMetaAttr,
SequenceMetaAttr,
RelationshipMetaAttr,
Route,
Server,
Cron,
Job,
JobOptions,
tickCallback,
Handler,
CustomNext,
};
15 changes: 8 additions & 7 deletions lib/job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import cron = require('node-cron');
import Cron from './cron';
import {assert} from './utils';

function noop() {
function noop(): void {
return null;
}

// tslint:disable-next-line:no-any
export type tickCallback = (val: any, indx?: number) => any;

export interface JobOptions {
Expand Down Expand Up @@ -61,7 +62,7 @@ export interface JobOptions {
* `tick` is called `ticksCount` times
*/
export default class Job {
public static createJob(options: JobOptions) {
public static createJob(options: JobOptions): Job {
assert('"options.ticksCount" must be greater than 0', options.ticksCount > 0);
const job = new Job();
const cronInstance = Cron.getCron();
Expand Down Expand Up @@ -96,26 +97,26 @@ export default class Job {
return job;
}

private internalId: any;
private internalId: string;
private firstTick: tickCallback;
private tick: tickCallback;
private lastTick: tickCallback;
private internalJob: ScheduledTask;
private constructor() {}

get id() {
get id(): string {
return this.internalId;
}

public start() {
public start(): void {
Cron.getCron().start(this.id);
}

public stop() {
public stop(): void {
Cron.getCron().stop(this.id);
}

public destroy() {
public destroy(): void {
Cron.getCron().destroy(this.id);
}
}
14 changes: 7 additions & 7 deletions lib/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@ import { CRUDOptions } from 'lair-db/dist/lair';
import methods = require('methods');
import { assert } from './utils';

function defaultNext(req: express.Request, res: express.Response, data: any) {
function defaultNext(req: express.Request, res: express.Response, data: object|void): express.Response {
return res.json(data);
}

function defaultHandler(req: express.Request, res: express.Response, next: express.NextFunction, lair: Lair) {
function defaultHandler(req: express.Request, res: express.Response, next: express.NextFunction, lair: Lair): express.Response {
return res.json({});
}

export type Handler = (req: express.Request, res: express.Response, next: express.NextFunction, lair: Lair) => any;
export type CustomNext = (req: express.Request, res: express.Response, data: any, lair: Lair) => any;
export type CustomNext = (req: express.Request, res: express.Response, data: object|void, lair: Lair) => any;

export default class Route {
public static createRoute(method = 'get', path = '/', handler: Handler = defaultHandler): Route {
public static createRoute(method: string = 'get', path: string = '/', handler: Handler = defaultHandler): Route {
const route = new Route();
route.handler = handler;
route.method = method;
Expand Down Expand Up @@ -74,11 +74,11 @@ export default class Route {
}

public handler: Handler;
public method;
public method: string;
/**
* Used to override `server.namespace` for current Route
* @type {string?}
*/
public namespace = null;
public path;
public namespace: string = null;
public path: string;
}
44 changes: 22 additions & 22 deletions lib/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ export default class Server {
private static instance: Server;

public expressApp: express.Application;
public namespace = '';
public port = 54321;
public verbose = true;
public delay = 0;
public lairNamespace = '/lair';
public namespace: string = '';
public port: number = 54321;
public verbose: boolean = true;
public delay: number = 0;
public lairNamespace: string = '/lair';

public get server(): http.Server {
return this.internalServer;
Expand All @@ -82,7 +82,7 @@ export default class Server {
});
}

public addRoute(route: Route) {
public addRoute(route: Route): void {
let source;
let path;
if (route.namespace === null) {
Expand All @@ -99,39 +99,39 @@ export default class Server {
route.handler.call(this.expressRouter, req, res, next, this.lair));
}

public addRoutes(routes: Route[]) {
public addRoutes(routes: Route[]): void {
routes.map(route => this.addRoute(route));
}

public addRoutesFromDir(path: string) {
public addRoutesFromDir(path: string): void {
read(path).forEach(routePath => this.add('route', path, routePath));
}

public addFactory(factory: Factory, name?: string) {
public addFactory(factory: Factory, name?: string): void {
this.lair.registerFactory(factory, name);
}

public addFactories(factories: Array<[Factory, string]>) {
public addFactories(factories: Array<[Factory, string]>): void {
factories.map(args => this.addFactory.apply(this, args));
}

public addFactoriesFromDir(path: string) {
public addFactoriesFromDir(path: string): void {
read(path).forEach(factoryPath => this.add('factory', path, factoryPath));
}

public createRecords(factoryName: string, count: number) {
public createRecords(factoryName: string, count: number): void {
this.createRecordsQueue.push([factoryName, count]);
}

public addMiddleware(clb: express.RequestHandler) {
public addMiddleware(clb: express.RequestHandler): void {
this.middlewaresQueue.push(clb);
}

public addMiddlewares(clbs: express.RequestHandler[]) {
public addMiddlewares(clbs: express.RequestHandler[]): void {
clbs.map(clb => this.addMiddleware(clb));
}

public startServer(clb?: () => any) {
public startServer(clb?: () => void): void {
this.lair.verbose = this.verbose;
this.fillLair();
this.useMiddlewares();
Expand All @@ -141,11 +141,11 @@ export default class Server {
this.internalServer = this.expressApp.listen(this.port, () => clb ? clb() : null);
}

public stopServer(clb?: () => any) {
public stopServer(clb?: () => void): void {
this.internalServer.close(() => clb ? clb() : null);
}

private addLairMetaRoutes() {
private addLairMetaRoutes(): void {
this.expressLairRouter.get('/meta', (req, res) => res.json(this.lair.getDevInfo()));
const path = `/factories/:factoryName`;
const singlePath = `${path}/:id`;
Expand All @@ -158,16 +158,16 @@ export default class Server {
this.expressApp.use(this.lairNamespace, this.expressLairRouter);
}

private addAppRoutes() {
private addAppRoutes(): void {
this.expressApp.use(this.namespace, this.expressRouter);
}

private fillLair() {
private fillLair(): void {
this.createRecordsQueue.map(crArgs => this.lair.createRecords.apply(this.lair, crArgs));
this.createRecordsQueue = [];
}

private useMiddlewares() {
private useMiddlewares(): void {
const app = this.expressApp;
app.use(bodyParser.json());
app.use((req, res, next) => {
Expand All @@ -187,14 +187,14 @@ export default class Server {
});
}

private printRoutesMap() {
private printRoutesMap(): void {
if (this.verbose) {
this.logger.info({level: 'info', message: 'Defined route-handlers'});
this.expressApp._router.stack.forEach(printRoutesMap.bind(null, []));
}
}

private add(type: string, parent: string, path: string) {
private add(type: string, parent: string, path: string): void {
if ((path.match(/\.ts$/) !== null || path.match(/\.js$/) !== null) && path.match(/\.d\.ts$/) === null) {
const instance = require(`${parent}/${path}`).default;
if (instance) {
Expand Down
2 changes: 1 addition & 1 deletion lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import winston = require('winston');

export function assert(msg: string, condition: boolean) {
export function assert(msg: string, condition: boolean): void {
if (!condition) {
throw new Error(msg);
}
Expand Down

0 comments on commit 272dcff

Please sign in to comment.