Skip to content

Commit

Permalink
Merge pull request #9 from deveshsangwan/migrate-js-to-ts
Browse files Browse the repository at this point in the history
Migrate js to ts
  • Loading branch information
deveshsangwan authored Mar 25, 2024
2 parents 648d78f + c544a9d commit 5ccc5ab
Show file tree
Hide file tree
Showing 49 changed files with 415 additions and 114 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ Welcome to the Cricket Score API! This project is designed to provide real-time
Our aim is to maintain high code coverage to ensure the quality of the project. Here are our current stats:

[![codecov](https://codecov.io/gh/deveshsangwan/cricketScoreApi/graph/badge.svg?token=A3JMLLNTG4)](https://codecov.io/gh/deveshsangwan/cricketScoreApi)
![Functions](https://img.shields.io/badge/functions-92.98%25-brightgreen.svg?style=flat)
![Lines](https://img.shields.io/badge/lines-89.33%25-yellow.svg?style=flat)
![Functions](https://img.shields.io/badge/functions-91.37%25-brightgreen.svg?style=flat)
![Lines](https://img.shields.io/badge/lines-89.01%25-yellow.svg?style=flat)

## 🚀 Getting Started

Expand Down
2 changes: 1 addition & 1 deletion app/app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const express = require('express');
const bodyParser = require('body-parser');
const httpContext = require('express-http-context');
const Mongo = require('./core/mongo');
const Mongo = require('./dist/core/mongo');
const { expressjwt, UnauthorizedError } = require('express-jwt');
require('dotenv').config();

Expand Down
18 changes: 18 additions & 0 deletions app/core/BaseModelInterfaces.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Document } from 'mongoose';

export interface ILiveMatches extends Document {
_id: string;
matchUrl: string;
matchName: string;
}

export interface IMatchStats extends Document {
createdAt: Date;
_id: string;
team1: object;
team2: object;
onBatting: object;
summary: object;
tournamentName: string;
matchName: string;
}
35 changes: 18 additions & 17 deletions app/core/baseModel.js → app/core/baseModel.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
const Mongoose = require('mongoose');
const { writeLogInfo, writeLogError } = require('../core/logger');
import Mongoose, { Model, Schema } from 'mongoose';
import { ILiveMatches, IMatchStats } from './BaseModelInterfaces';
import { writeLogInfo, writeLogError } from './Logger';

const MODEL_NAMES = {
LIVE_MATCHES: 'liveMatches',
MATCH_STATS: 'matchStats'
};
enum MODEL_NAMES {
LIVE_MATCHES = 'liveMatches',
MATCH_STATS = 'matchStats'
}

// define model
const liveMatches = new Mongoose.Schema({
const liveMatches: Schema<ILiveMatches> = new Schema({
_id: {
type: String,
required: true
Expand All @@ -22,7 +23,7 @@ const liveMatches = new Mongoose.Schema({
},
});

const matchStats = new Mongoose.Schema({
const matchStats: Schema<IMatchStats> = new Schema({
createdAt: {
type: Date,
default: Date.now
Expand Down Expand Up @@ -57,15 +58,15 @@ const matchStats = new Mongoose.Schema({
},
});

const LiveMatches = Mongoose.model(MODEL_NAMES.LIVE_MATCHES, liveMatches);
const MatchStats = Mongoose.model(MODEL_NAMES.MATCH_STATS, matchStats);
const LiveMatches: Model<ILiveMatches> = Mongoose.model(MODEL_NAMES.LIVE_MATCHES, liveMatches);
const MatchStats: Model<IMatchStats> = Mongoose.model(MODEL_NAMES.MATCH_STATS, matchStats);

/**
* Find all matches from a specified model
* @param {String} modelName - The name of the model to query
* @returns {Array} - An array of matches
*/
const findAll = async (modelName) => {
const findAll = async (modelName: string) => {
try {
const response = await Mongoose.model(modelName).find({});
return response;
Expand All @@ -82,7 +83,7 @@ const findAll = async (modelName) => {
* @param {String} modelName - The name of the model to query
* @returns {Object} - The match object if found, null otherwise
*/
const findById = async (matchId, modelName) => {
const findById = async (matchId: string, modelName: string) => {
try {
const response = await Mongoose.model(modelName).find({ _id: matchId });
return response;
Expand All @@ -98,7 +99,7 @@ const findById = async (matchId, modelName) => {
* @param {String} matchUrl - The URL of the match to find
* @returns {Object} - The match object if found, null otherwise
*/
const findIdByMatchUrl = async (matchUrl) => {
const findIdByMatchUrl = async (matchUrl: string) => {
try {
return await Mongoose.model(MODEL_NAMES.LIVE_MATCHES).find({ matchUrl: matchUrl });
} catch (err) {
Expand All @@ -113,11 +114,11 @@ const findIdByMatchUrl = async (matchUrl) => {
* @param {String} modelName - model name
* @returns {Object} - response
*/
const insert = async (data, modelName) => {
const insert = async (data: object, modelName: string) => {
try {
const Model = Mongoose.model(modelName);
const response = await Model.findOneAndUpdate(
{ _id: data._id }, // find a document with `_id` same as `data._id`
{ _id: (data as any)._id }, // find a document with `_id` same as `data._id`
data, // document to insert when nothing was found
{ upsert: true, new: true, runValidators: true } // options
);
Expand All @@ -136,7 +137,7 @@ const insert = async (data, modelName) => {
* @param {String} modelName - The name of the model to insert into
* @returns {Array} - An array of the inserted match objects
*/
const insertMany = async (matches, modelName) => {
const insertMany = async (matches: object[], modelName: string) => {
try {
const response = await Mongoose.model(modelName).insertMany(matches);
return response;
Expand All @@ -148,7 +149,7 @@ const insertMany = async (matches, modelName) => {
};


module.exports = {
export {
findAll,
findById,
findIdByMatchUrl,
Expand Down
9 changes: 0 additions & 9 deletions app/core/configuration.js

This file was deleted.

12 changes: 12 additions & 0 deletions app/core/configuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import nconf from 'nconf';
import * as path from 'path';

const nodeEnv: string = process.env.NODE_ENV || 'development';
const __basedir: string = path.resolve();

nconf.argv().env();
nconf.file('config', path.join(__basedir, `app/config/config.${nodeEnv}.json`));
nconf.file('responseMessage', path.join(__basedir, 'app/config/responseMessage.json'));
nconf.file('partners', path.join(__basedir, 'app/config/partners.json'));

export default nconf;
43 changes: 0 additions & 43 deletions app/core/logger.js

This file was deleted.

37 changes: 37 additions & 0 deletions app/core/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import config from './configuration';
import winston from 'winston';

const logger = winston.createLogger({
format: winston.format.combine(
winston.format.label({ label: config.get('logging:label') as string }),
winston.format.errors({ stack: true }),
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 ??
'') + (meta && Object.keys(meta).length ?
'\n' + JSON.stringify(meta, null, 4) :
'');
return stack ? text + '\n' + stack : text;
}),
winston.format.colorize({ all: true }),
),
transports: [
new winston.transports.Console({
level: config.get('logging:consoleLevel') as string,
handleExceptions: true,
}),
]
});

export const writeLogInfo = (arr: unknown[]): void => {
logger.info(
arr
);
};

export const writeLogError = (arr: unknown[]): void => {
logger.error(
arr
);
};
16 changes: 10 additions & 6 deletions app/core/mongo.js → app/core/mongo.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
require('dotenv').config();
const Mongoose = require('mongoose');
const { writeLogInfo, writeLogError } = require(__basedir + 'app/core/logger');
import dotenv from 'dotenv';
import Mongoose, { Mongoose as MongooseType } from 'mongoose';
import { writeLogInfo, writeLogError } from './Logger';

dotenv.config();

class Mongo {
private connection: MongooseType | undefined;

constructor() {
this._connect();
}

async _connect() {
private async _connect(): Promise<MongooseType | undefined> {
if (this.connection) {
return this.connection;
}

let mongoUrl = process.env.MONGO_URL;
const mongoUrl: string = process.env.MONGO_URL || '';
try {
this.connection = await Mongoose.connect(mongoUrl);
writeLogInfo(['Database connection successful']);
Expand All @@ -22,4 +26,4 @@ class Mongo {
}
}

module.exports = new Mongo();
export default new Mongo();
3 changes: 3 additions & 0 deletions app/dist/core/BaseModelInterfaces.js

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

Loading

0 comments on commit 5ccc5ab

Please sign in to comment.