Skip to content

Commit

Permalink
added eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
deveshsangwan committed Mar 10, 2024
1 parent 96702ff commit c227fa0
Show file tree
Hide file tree
Showing 23 changed files with 160 additions and 132 deletions.
24 changes: 24 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"env": {
"node": true
},
"parser": "@typescript-eslint/parser",
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"rules": {
"no-console": "warn",
"indent": ["error", 4],
"linebreak-style": ["error", "unix"],
"quotes": ["error", "single"],
"semi": ["error", "always"],
"no-unused-vars": ["warn"],
"eqeqeq": ["error", "always"],
"curly": ["error"]
}
}
17 changes: 13 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
# Use multi-stage build
FROM node:alpine

ENV NODE_VERSION 18.16.0

WORKDIR /usr/app
COPY ./ /usr/app

RUN apk --no-cache add bash
RUN apk --no-cache --virtual build-dependencies add
# Copy package.json and package-lock.json first
COPY package*.json ./

# Set NODE_ENV to production before running npm install
ENV NODE_ENV production

# Install bash
RUN apk add --no-cache bash

RUN npm cache clean --force
RUN npm install
RUN apk del build-dependencies

# Copy the rest of the application code
COPY ./ .

ENV NODE_PORT 3000
ENV NODE_ENV production
Expand Down
46 changes: 23 additions & 23 deletions app/app.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
const app = require('express')();
const bodyParser = require('body-parser');
const httpContext = require('express-http-context');
const Mongo = require('./core/mongo');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(httpContext.middleware);

app.use((req, res, next) => {
httpContext.set('req', req);
next();
});

require(__basedir + 'app/route')(app);

app.use(function (req, res) {
return res.status(404).json({
status: false,
statusMessage: '404 - Page not found'
});
});

const app = require('express')();
const bodyParser = require('body-parser');
const httpContext = require('express-http-context');
const Mongo = require('./core/mongo');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(httpContext.middleware);

app.use((req, res, next) => {
httpContext.set('req', req);
next();
});

require(__basedir + 'app/route')(app);

app.use(function (req, res) {
return res.status(404).json({
status: false,
statusMessage: '404 - Page not found'
});
});

module.exports = app;
4 changes: 2 additions & 2 deletions app/core/baseModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const findIdByMatchUrl = async (matchUrl) => {
try {
return await Mongoose.model(MODEL_NAMES.LIVE_MATCHES).find({ matchUrl: matchUrl });
} catch (err) {
writeLogError(["findIdByMatchUrl error: ", err]);
writeLogError(['findIdByMatchUrl error: ', err]);
throw err;
}
};
Expand Down Expand Up @@ -126,4 +126,4 @@ module.exports = {
findIdByMatchUrl,
insert,
insertMany
}
};
24 changes: 12 additions & 12 deletions app/core/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ const logger = winston.createLogger({
format: winston.format.combine(
winston.format.label({label:config.get('logging:label')}),
winston.format.errors({stack: true}),
winston.format.timestamp({format: "YYYY-MM-DD hh:mm:ss"}),
winston.format.timestamp({format: 'YYYY-MM-DD hh:mm:ss'}),
winston.format.printf(({ timestamp, label, level, message, meta, stack }) => {
const text = "[" + timestamp + "] " +
label + "." + level.toUpperCase() + ": " + (message ? message :
const text = '[' + timestamp + '] ' +
label + '.' + level.toUpperCase() + ': ' + (message ? message :
'') +(meta && Object.keys(meta).length ?
'\n' + JSON.stringify(meta, null, 4) :
'');
return stack ? text + '\n' + stack : text;
}),
return stack ? text + '\n' + stack : text;
}),
winston.format.colorize({ all: true }),
),
transports: [
Expand All @@ -25,16 +25,16 @@ const logger = winston.createLogger({
});

const writeLogInfo = (arr) => {
return logger.info(
return logger.info(
arr
);
}
);
};

const writeLogError = (arr) => {
return logger.error (
arr
);
}
return logger.error (
arr
);
};

/** Return Logger instances */
module.exports = {
Expand Down
2 changes: 1 addition & 1 deletion app/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ module.exports = function (app) {
router.get('/liveMatches', errorHandler(controller.live));
router.get('/matchStats/:matchId', errorHandler(controller.matchStats));
router.get('/matchStats', errorHandler(controller.getMatchStats));
}
};
4 changes: 2 additions & 2 deletions app/src/LiveMatches/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions app/src/MatchStats/MatchUtils.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 12 additions & 11 deletions app/src/MatchStats/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion app/src/controller.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 0 additions & 10 deletions app/src/errors/CustomErro.js

This file was deleted.

6 changes: 3 additions & 3 deletions app/ts_src/LiveMatches/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { MatchData } from './LiveMatchesInterfaces';
import { insertDataToLiveMatchesTable } from './LiveMatchesUtility';
import { CustomError } from '../errors';
import * as mongo from '../../core/baseModel';
import randomstring from "randomstring";
import randomstring from 'randomstring';
import _ from 'underscore';

const MATCH_URL = 'https://www.cricbuzz.com/cricket-match/live-scores';
Expand All @@ -23,8 +23,8 @@ export class LiveMatches {
return Promise.reject(new CustomError(error.message));
}

public async getMatches(matchId = "0"): Promise<{}> {
if (matchId !== "0") {
public async getMatches(matchId = '0'): Promise<{}> {
if (matchId !== '0') {
return this.getMatchById(matchId);
}
return this.getAllMatches();
Expand Down
4 changes: 2 additions & 2 deletions app/ts_src/MatchStats/MatchUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { writeLogInfo } from '../../core/logger';
import { ITeamData } from './MatchStatsInterfaces';

export function getTeamScoreString($, isLive: boolean, isCurrentTeam: boolean): string {
let element = isLive
const element = isLive
? (isCurrentTeam ? $('span.cb-font-20.text-bold') : $('div.cb-text-gray.cb-font-16'))
: $('div.cb-col.cb-col-100.cb-min-tm').eq(isCurrentTeam ? 1 : 0);
return element.text().trim();
Expand All @@ -16,7 +16,7 @@ export function getTeamData(input: string, isBatting: boolean = false): ITeamDat
return {};
}

const [, name, score1, wickets1 = "10", score2, wickets2 = "10", overs] = match;
const [, name, score1, wickets1 = '10', score2, wickets2 = '10', overs] = match;
const hasTwoInnings = score2 !== undefined;
const score = hasTwoInnings ? score2 : score1;
const wickets = hasTwoInnings ? wickets2 : wickets1;
Expand Down
24 changes: 12 additions & 12 deletions app/ts_src/MatchStats/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as mongo from '../../core/baseModel';
import { writeLogError } from '../../core/logger';
import { InvalidMatchIdError, MatchIdRequriedError, NoMatchesFoundError } from '../errors';
import { LiveMatchesResponse, MatchData } from './MatchStatsInterfaces';
import { getTeamScoreString, getTeamData, getBatsmanData } from './MatchUtils'
import { getTeamScoreString, getTeamData, getBatsmanData } from './MatchUtils';
const _ = require('underscore');


Expand All @@ -26,15 +26,15 @@ export class MatchStats {
}

// matchId should be 0 or alphanumeric string of length 16
if (matchId !== "0" && !matchId.match(/^[a-zA-Z0-9]{16}$/)) {
if (matchId !== '0' && !matchId.match(/^[a-zA-Z0-9]{16}$/)) {
throw new InvalidMatchIdError(matchId);
}

const liveMatchesResponse = await this.liveMatchesObj.getMatches(matchId);

// If matchId is not "0", get stats for the single match
// If matchId is not '0', get stats for the single match
// Otherwise, get stats for all matches
if (matchId !== "0") {
if (matchId !== '0') {
return this.getStatsForSingleMatch(liveMatchesResponse, matchId);
}

Expand Down Expand Up @@ -72,7 +72,7 @@ export class MatchStats {
}

private async getStatsForSingleMatch(liveMatchesResponse: LiveMatchesResponse, matchId: string): Promise<{} | 'Match Id is invalid'> {
let mongoData = await mongo.findById(matchId, this.tableName);
const mongoData = await mongo.findById(matchId, this.tableName);
if (mongoData.length) {
// Only add the properties you need
const returnObj = {
Expand Down Expand Up @@ -100,14 +100,14 @@ export class MatchStats {

private async scrapeData(url, matchId: string): Promise<{}> {
try {
if (!matchId) return Promise.resolve('Match Id is required');
if (!matchId) {return Promise.resolve('Match Id is required');}

url = 'https://www.cricbuzz.com' + url;
const response = await this.utilsObj.fetchData(url);

let tournamentName = await this.getTournamentName(response);
const tournamentName = await this.getTournamentName(response);

let finalResponse = await this.getMatchStatsByMatchId(response, matchId);
const finalResponse = await this.getMatchStatsByMatchId(response, matchId);
finalResponse['tournamentName'] = tournamentName;

return Promise.resolve(finalResponse);
Expand All @@ -133,11 +133,11 @@ export class MatchStats {
private getMatchStatsByMatchId($, matchId: string): Promise<MatchData> {
return new Promise((resolve, reject) => {
try {
let isLive = $('div.cb-text-complete').length === 0;
let currentTeamScoreString = getTeamScoreString($, isLive, true);
let otherTeamScoreString = getTeamScoreString($, isLive, false);
const isLive = $('div.cb-text-complete').length === 0;
const currentTeamScoreString = getTeamScoreString($, isLive, true);
const otherTeamScoreString = getTeamScoreString($, isLive, false);

let matchData: MatchData = {
const matchData: MatchData = {
matchId: matchId,
team1: getTeamData(currentTeamScoreString, true),
team2: getTeamData(otherTeamScoreString),
Expand Down
Loading

0 comments on commit c227fa0

Please sign in to comment.