Skip to content

Commit

Permalink
Merge pull request #12 from deveshsangwan/migrate-to-prisma
Browse files Browse the repository at this point in the history
Migrate to prisma
  • Loading branch information
deveshsangwan authored Mar 26, 2024
2 parents 9ae2ace + 780b03b commit 9b25982
Show file tree
Hide file tree
Showing 22 changed files with 176 additions and 372 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/Codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
- name: Run Tests
run: npm run test:coverage
env:
MONGO_URL: ${{ secrets.MONGO_URL }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
CLIENT_ID: ${{ secrets.CLIENT_ID }}
CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
- name: Run Tests
run: npm run test:coverage
env:
MONGO_URL: ${{ secrets.MONGO_URL }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
CLIENT_ID: ${{ secrets.CLIENT_ID }}
CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
Expand Down
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-93.1%25-brightgreen.svg?style=flat)
![Lines](https://img.shields.io/badge/lines-89.66%25-yellow.svg?style=flat)
![Functions](https://img.shields.io/badge/functions-92.72%25-brightgreen.svg?style=flat)
![Lines](https://img.shields.io/badge/lines-85.88%25-yellow.svg?style=flat)

## 🚀 Getting Started

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

Expand Down
132 changes: 24 additions & 108 deletions app/core/BaseModel.ts
Original file line number Diff line number Diff line change
@@ -1,154 +1,70 @@
import Mongoose, { Model, Schema } from 'mongoose';
import { ILiveMatches, IMatchStats } from './BaseModelInterfaces';
import { PrismaClient } from '@prisma/client';
import { writeLogInfo, writeLogError } from './Logger';

Check failure on line 2 in app/core/BaseModel.ts

View workflow job for this annotation

GitHub Actions / test

'writeLogInfo' is declared but its value is never read.

enum MODEL_NAMES {
LIVE_MATCHES = 'liveMatches',
MATCH_STATS = 'matchStats'
}
const prisma = new PrismaClient();

// define model
const liveMatches: Schema<ILiveMatches> = new Schema({
_id: {
type: String,
required: true
},
matchUrl: {
type: String,
required: true
},
matchName: {
type: String,
required: true
},
});

const matchStats: Schema<IMatchStats> = new Schema({
createdAt: {
type: Date,
default: Date.now
},
_id: {
type: String,
required: true
},
team1: {
type: Object,
required: true
},
team2: {
type: Object,
required: true
},
onBatting: {
type: Object,
required: true
},
summary: {
type: Object,
required: true
},
tournamentName: {
type: String,
required: true
},
matchName: {
type: String,
required: true
},
});

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: string) => {
try {
const response = await Mongoose.model(modelName).find({});
const response = await prisma[modelName].findMany();
return response;
} catch (err) {
const collectionName = modelName === 'matchStats' ? 'MATCH_STATS' : 'LIVE_MATCHES';
writeLogError([`findAll ${collectionName} error: `, err]);
writeLogError([`findAll ${modelName} error: `, err]);
throw err;
}
};

/**
* Find a match by its ID from a specified model
* @param {String} matchId - The ID of the match to find
* @param {String} modelName - The name of the model to query
* @returns {Object} - The match object if found, null otherwise
*/
const findById = async (matchId: string, modelName: string) => {
try {
const response = await Mongoose.model(modelName).find({ _id: matchId });
const response = await prisma[modelName].findUnique({ where: { id: matchId } });
return response;
} catch (err) {
const collectionName = modelName === 'matchStats' ? 'MATCH_STATS' : 'LIVE_MATCHES';
writeLogError([`findById ${collectionName} error: `, err]);
writeLogError([`findById ${modelName} error: `, err]);
throw err;
}
};

/**
* Find a match ID by its URL
* @param {String} matchUrl - The URL of the match to find
* @returns {Object} - The match object if found, null otherwise
*/
const findIdByMatchUrl = async (matchUrl: string) => {
try {
return await Mongoose.model(MODEL_NAMES.LIVE_MATCHES).find({ matchUrl: matchUrl });
return await prisma.livematches.findUnique({ where: { matchUrl: matchUrl } });
} catch (err) {
writeLogError(['findIdByMatchUrl error: ', err]);
throw err;
}
};

/**
* Insert a new match or update if already exists
* @param {Object} data - match data
* @param {String} modelName - model name
* @returns {Object} - response
*/
const insert = async (data: object, modelName: string) => {
try {
const Model = Mongoose.model(modelName);
const response = await Model.findOneAndUpdate(
{ _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
);
const { id, ...restData } = data as any;
const response = await prisma[modelName].upsert({
where: { id: id },
update: restData,
create: {
id,
...restData,
createdAt: new Date(),
}
});
return response;
} catch (err) {
const collectionName = modelName === 'matchStats' ? 'MATCH_STATS' : 'LIVE_MATCHES';
writeLogError([`insert ${collectionName} error: `, err]);
writeLogError([`insert ${modelName} error: `, err]);
throw err;
}
};


/**
* Insert multiple matches into a specified model
* @param {Array} matches - An array of match data to insert
* @param {String} modelName - The name of the model to insert into
* @returns {Array} - An array of the inserted match objects
*/
const insertMany = async (matches: object[], modelName: string) => {
try {
const response = await Mongoose.model(modelName).insertMany(matches);
if (!matches.length) {
return;
}

const response = await prisma[modelName].createMany({ data: matches });
return response;
} catch (err) {
const collectionName = modelName === 'matchStats' ? 'MATCH_STATS' : 'LIVE_MATCHES';
writeLogError([`insertMany ${collectionName} error: `, err]);
writeLogError([`insertMany ${modelName} error: `, err]);
throw err;
}
};


export {
findAll,
findById,
Expand Down
18 changes: 0 additions & 18 deletions app/core/BaseModelInterfaces.ts

This file was deleted.

29 changes: 0 additions & 29 deletions app/core/Mongo.ts

This file was deleted.

Loading

0 comments on commit 9b25982

Please sign in to comment.