Skip to content

Commit

Permalink
fix(build): add tslint, fix issues
Browse files Browse the repository at this point in the history
  • Loading branch information
ssube committed Sep 12, 2019
1 parent d8f2985 commit 44ae78c
Show file tree
Hide file tree
Showing 21 changed files with 83 additions and 47 deletions.
6 changes: 6 additions & 0 deletions config/rollup.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import json from 'rollup-plugin-json';
import multiEntry from 'rollup-plugin-multi-entry';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import tslint from 'rollup-plugin-tslint';
import typescript from 'rollup-plugin-typescript2';
import yaml from 'rollup-plugin-yaml';

Expand Down Expand Up @@ -199,6 +200,11 @@ const bundle = {
],
},
}),
tslint({
configuration: './config/tslint.json',
throwOnError: true,
include: ['**/*.ts'],
}),
typescript({
cacheRoot: 'out/cache/rts2',
rollupCommonJSResolveHack: true,
Expand Down
4 changes: 2 additions & 2 deletions config/tslint.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"no-banned-terms": true,
"no-delete-expression": true,
"no-for-in": true,
"no-relative-imports": true,
"no-relative-imports": false,
"no-small-switch": false
}
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"rollup-plugin-node-externals": "2.0.0",
"rollup-plugin-node-resolve": "5.2.0",
"rollup-plugin-replace": "2.2.0",
"rollup-plugin-tslint": "^0.2.2",
"rollup-plugin-typescript2": "0.24.1",
"rollup-plugin-yaml": "1.1.0",
"rxjs": "6.5.3",
Expand Down
1 change: 1 addition & 0 deletions src/controller/CompletionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export class CompletionController extends BaseController<CompletionControllerDat
const results = await this.fragmentRepository.find({
order: {
createdAt: 'DESC',
/* tslint:disable-next-line:no-any */
} as any,
take: 1,
where: {
Expand Down
6 changes: 3 additions & 3 deletions src/controller/EchoController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Command, CommandVerb } from '../entity/Command';
import { ChannelData, Context } from '../entity/Context';
import { Listener } from '../listener';
import { ServiceMetadata } from '../Service';
import { mustCoalesce } from '../utils';
import { doesExist, mustCoalesce } from '../utils';
import { BaseController, BaseControllerOptions } from './BaseController';

export const NOUN_ECHO = 'echo';
Expand All @@ -26,7 +26,7 @@ export class EchoController extends BaseController<EchoControllerData> implement
public async start() {
await super.start();

this.defaultTarget = await this.services.getService<Listener>(this.data.defaultTarget);
this.defaultTarget = this.services.getService<Listener>(this.data.defaultTarget);
}

@Handler(NOUN_ECHO, CommandVerb.Create)
Expand All @@ -47,7 +47,7 @@ export class EchoController extends BaseController<EchoControllerData> implement
protected ensureTarget(ctx: Context) {
const channel = mustCoalesce(this.data.forceChannel, ctx.channel);

if (ctx.target) {
if (doesExist(ctx.target)) {
return new Context({
...ctx,
channel,
Expand Down
2 changes: 1 addition & 1 deletion src/controller/SearchController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export class SearchController extends BaseController<SearchControllerData> imple
const requestUrl = this.url.render({ data });
this.logger.debug({ requestUrl }, 'searching at url');

const response: any = await this.request.create({
const response: object = await this.request.create({
json: true,
method: this.data.request.method,
uri: requestUrl,
Expand Down
3 changes: 2 additions & 1 deletion src/controller/WeatherController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export class WeatherController extends BaseController<WeatherControllerData> imp

public async requestWeather(location: string): Promise<WeatherReply> {
const query = this.getQuery(location);
this.logger.debug({ location, query, root: this.data.api.root }, 'requesting weather data from API');
this.logger.debug({ location, query, root: this.data.api.root }, 'requesting data from weather API');

try {
const reply = await this.request.create<WeatherReply>({
Expand All @@ -58,6 +58,7 @@ export class WeatherController extends BaseController<WeatherControllerData> imp
qs: query,
uri: `${this.data.api.root}/weather`,
});
this.logger.debug({ reply }, 'response from weather API');
return reply;
} catch (err) {
if (err.name === 'StatusCodeError') {
Expand Down
2 changes: 2 additions & 0 deletions src/controller/github/PRController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export class GithubPRController extends BaseController<GithubPRControllerData> i
constructor(options: BaseControllerOptions<GithubPRControllerData>) {
super(options, 'isolex#/definitions/service-controller-github-pr', [NOUN_PULL_REQUEST]);

// this is a total hack because octokit crashes otherwise
/* tslint:disable-next-line:no-any */
(global as any).navigator = {};
this.client = new Octokit({
auth: `token ${options.data.client.token}`,
Expand Down
15 changes: 14 additions & 1 deletion src/endpoint/BaseEndpoint.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Router } from 'express';
import { NextFunction, Request, Response, Router } from 'express';
import { Inject } from 'noicejs';
import { Repository } from 'typeorm';

Expand All @@ -17,13 +17,15 @@ export type BaseEndpointOptions<TData extends EndpointData> = BotServiceOptions<
@Inject(INJECT_STORAGE)
export abstract class BaseEndpoint<TData extends EndpointData> extends BotService<TData> implements Endpoint {
protected readonly contextRepository: Repository<Context>;
protected readonly router: Router;
protected readonly services: ServiceModule;
protected readonly transforms: Array<Transform>;

constructor(options: BaseListenerOptions<TData>, schemaPath: string) {
super(options, schemaPath);

this.contextRepository = mustExist(options[INJECT_STORAGE]).getRepository(Context);
this.router = Router();
this.services = mustExist(options[INJECT_SERVICES]);
this.transforms = [];
}
Expand Down Expand Up @@ -55,4 +57,15 @@ export abstract class BaseEndpoint<TData extends EndpointData> extends BotServic
this.logger.debug({ ctx }, 'endpoint saved new context');
return ctx;
}

protected nextRoute(fn: (req: Request, res: Response) => Promise<void>) {
return (req: Request, res: Response, next: NextFunction) => {
fn(req, res).then(() => {
next();
}).catch((err: Error) => {
this.logger.error(err, 'error invoking route');
next();
});
};
}
}
9 changes: 4 additions & 5 deletions src/endpoint/DebugEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,12 @@ export class DebugEndpoint extends BaseEndpoint<EndpointData> implements Endpoin
];
}

public createRouter(): Promise<Router> {
const router = Router();
router.route('/').get((req: Request, res: Response) => this.getIndex(req, res));
return Promise.resolve(router);
public async createRouter(): Promise<Router> {
this.router.route('/').get(this.nextRoute(this.getIndex.bind(this)));
return this.router;
}

public getIndex(req: Request, res: Response) {
public async getIndex(req: Request, res: Response): Promise<void> {
const svcs = [];
for (const [key, svc] of this.services.listServices()) {
svcs.push({
Expand Down
12 changes: 6 additions & 6 deletions src/endpoint/EchoEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Request, Response, Router } from 'express';
import { Endpoint, EndpointData } from '.';
import { BotServiceOptions } from '../BotService';
import { User } from '../entity/auth/User';
import { doesExist } from '../utils';
import { BaseEndpoint } from './BaseEndpoint';

export class EchoEndpoint extends BaseEndpoint<EndpointData> implements Endpoint {
Expand All @@ -17,15 +18,14 @@ export class EchoEndpoint extends BaseEndpoint<EndpointData> implements Endpoint
];
}

public createRouter(): Promise<Router> {
const router = Router();
router.route('/').get((req: Request, res: Response) => this.getIndex(req, res));
return Promise.resolve(router);
public async createRouter(): Promise<Router> {
this.router.route('/').get(this.nextRoute(this.getIndex.bind(this)));
return this.router;
}

public getIndex(req: Request, res: Response) {
public async getIndex(req: Request, res: Response): Promise<void> {
this.logger.debug('echo endpoint get index');
if (req.user) {
if (doesExist(req.user)) {
const user = req.user as User;
res.send(`Hello ${user.name}!`);
} else {
Expand Down
29 changes: 15 additions & 14 deletions src/endpoint/GitlabEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,20 +108,20 @@ export class GitlabEndpoint extends BaseEndpoint<GitlabEndpointData> implements
}

public createRouter(): Promise<Router> {
const router = Router();
router.use(expressJSON());
router.route('/hook').post((req: Request, res: Response) => {
this.logger.debug({
req,
res,
}, 'gitlab endpoint got webhook');

// authenticate & authorize

const hook: GitlabBaseWebhook = req.body;
return this.hookKind(req, res, hook);
});
return Promise.resolve(router);
this.router.use(expressJSON());
this.router.route('/hook').post(this.nextRoute(this.hookSwitch.bind(this)));
return Promise.resolve(this.router);
}

public async hookSwitch(req: Request, res: Response) {
this.logger.debug({
req,
res,
}, 'gitlab endpoint got webhook');

// authenticate & authorize
const hook: GitlabBaseWebhook = req.body;
return this.hookKind(req, res, hook);
}

public async hookKind(req: Request, res: Response, data: GitlabBaseWebhook) {
Expand Down Expand Up @@ -209,6 +209,7 @@ export class GitlabEndpoint extends BaseEndpoint<GitlabEndpointData> implements
}

protected async createHookMessage(req: Request, res: Response, data: GitlabBaseWebhook): Promise<Message> {
/* tslint:disable-next-line:no-any */
const msgCtx = mustExist<Context>(req.user as any);
// fake message for the transforms to check and filter
return new Message({
Expand Down
1 change: 1 addition & 0 deletions src/interval/BaseInterval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export abstract class BaseInterval<TData extends IntervalData> extends BotServic
// typeorm requires an order for toString, which is not a column
order: {
updatedAt: 'DESC',
/* tslint:disable-next-line:no-any */
} as any,
take: 1,
where: {
Expand Down
1 change: 1 addition & 0 deletions src/listener/GithubListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export class GithubListener extends SessionListener<GithubListenerData> {
const lastTick = await this.tickRepository.findOne({
order: {
createdAt: 'DESC',
/* tslint:disable-next-line:no-any */
} as any,
where: {
intervalId: this.id,
Expand Down
4 changes: 2 additions & 2 deletions src/parser/SplitParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export class SplitParser extends BaseParser<SplitParserData> implements Parser {
}

const ctx = mustExist(msg.context);
const data = await this.split(msg.body);
const data = this.split(msg.body);
this.logger.debug({ data }, 'splitting string');
const mapped = this.mapper.map(data);
return [await this.createCommand(ctx, mapped)];
Expand All @@ -58,7 +58,7 @@ export class SplitParser extends BaseParser<SplitParserData> implements Parser {
};
}

public split(msg: string) {
public split(msg: string): Array<string> {
return this.splitBody(msg).map(trim).filter((it) => !isEmpty(it));
}

Expand Down
2 changes: 1 addition & 1 deletion src/utils/Map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export function dictValuesToArrays<TVal>(map: MapLike<TVal>): Dict<Array<TVal>>
return data;
}

export function normalizeMap(map: MapLike<any>): Dict<Array<string>> {
export function normalizeMap(map: MapLike<unknown>): Dict<Array<string>> {
const data: Dict<Array<string>> = {};
for (const [key, value] of makeMap(map)) {
if (Array.isArray(value)) {
Expand Down
8 changes: 5 additions & 3 deletions src/utils/PidFile.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { open, unlink, write } from 'fs';
import { pid } from 'process';

import { doesExist } from '.';

export async function writePid(path: string): Promise<void> {
return new Promise((res, rej) => {
open(path, 'wx', (openErr: Error, fd: number) => {
if (openErr) {
if (doesExist(openErr)) {
rej(openErr);
} else {
write(fd, pid.toString(), 0, 'utf8', (writeErr: Error) => {
if (writeErr) {
if (doesExist(writeErr)) {
rej(writeErr);
} else {
res();
Expand All @@ -22,7 +24,7 @@ export async function writePid(path: string): Promise<void> {
export async function removePid(path: string): Promise<void> {
return new Promise((res, rej) => {
unlink(path, (err: Error) => {
if (err) {
if (doesExist(err)) {
rej(err);
} else {
res();
Expand Down
5 changes: 1 addition & 4 deletions src/utils/match/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,8 @@ export class Match {
return results;
}

// TODO: remove this conversion (#327)
const data = makeDict<unknown>(val as any);

for (const rule of this.rules) {
const value = get(data, rule.key);
const value = get(val, rule.key);
if (!isString(value)) {
results.errors.push(rule.key);
results.matched = false;
Expand Down
2 changes: 1 addition & 1 deletion test/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ chai.use(chaiAsPromised);
chai.use(sinonChai);

// TODO: replace ineeda with sinon mocks (#327)
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-any no-null-keyword */
ineeda.intercept({
then: null as any,
unsubscribe: null as any,
Expand Down
4 changes: 3 additions & 1 deletion test/transform/TestFlattenTransform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { TYPE_JSON } from '../../src/utils/Mime';
import { describeAsync, itAsync } from '../helpers/async';
import { createService, createServiceContainer } from '../helpers/container';

const OUTPUT_FIELD = 'body';

describeAsync('flatten transform', async () => {
itAsync('should transform data', async () => {
const { container } = await createServiceContainer();
Expand Down Expand Up @@ -38,6 +40,6 @@ describeAsync('flatten transform', async () => {
verb: CommandVerb.Create,
});
const output = await transform.transform(cmd, TYPE_JSON, data);
expect(output['body']).to.deep.equal(['hello-world']);
expect(output[OUTPUT_FIELD]).to.deep.equal(['hello-world']);
});
});
13 changes: 11 additions & 2 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4219,6 +4219,15 @@ rollup-plugin-replace@2.2.0:
magic-string "^0.25.2"
rollup-pluginutils "^2.6.0"

rollup-plugin-tslint@^0.2.2:
version "0.2.2"
resolved "https://artifacts.apextoaster.com/repository/group-npm/rollup-plugin-tslint/-/rollup-plugin-tslint-0.2.2.tgz#be440f020bffcb6622e3dd8d1b15a5234df833a5"
integrity sha512-1yF7bnDALlqgReMIsNDCNXOYqzCw9A8Ur5AS4RzlY7IsRBKB0yb+wx8ZCh0zBcXCeJP5tx36oqec4aX2Pzzttw==
dependencies:
rollup-pluginutils "^2.0.1"
tslint "^5.9.1"
typescript "^3.0.0"

rollup-plugin-typescript2@0.24.1:
version "0.24.1"
resolved "https://registry.yarnpkg.com/rollup-plugin-typescript2/-/rollup-plugin-typescript2-0.24.1.tgz#6b6bd4c4dcfc7575af68b16f921a13ad32f68f47"
Expand Down Expand Up @@ -4824,7 +4833,7 @@ tslint-sonarts@1.9.0:
dependencies:
immutable "^3.8.2"

tslint@5.20.0:
tslint@5.20.0, tslint@^5.9.1:
version "5.20.0"
resolved "https://registry.yarnpkg.com/tslint/-/tslint-5.20.0.tgz#fac93bfa79568a5a24e7be9cdde5e02b02d00ec1"
integrity sha512-2vqIvkMHbnx8acMogAERQ/IuINOq6DFqgF8/VDvhEkBqQh/x6SP0Y+OHnKth9/ZcHQSroOZwUQSN18v8KKF0/g==
Expand Down Expand Up @@ -4937,7 +4946,7 @@ typeorm@0.2.18:
yargonaut "^1.1.2"
yargs "^13.2.1"

typescript@3.6.3:
typescript@3.6.3, typescript@^3.0.0:
version "3.6.3"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.6.3.tgz#fea942fabb20f7e1ca7164ff626f1a9f3f70b4da"
integrity sha512-N7bceJL1CtRQ2RiG0AQME13ksR7DiuQh/QehubYcghzv20tnh+MQnQIuJddTmsbqYj+dztchykemz0zFzlvdQw==
Expand Down

0 comments on commit 44ae78c

Please sign in to comment.