Commit dd70590a authored by Hirusha's avatar Hirusha

all

parent c8433938
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
This diff is collapsed.
{
"name": "node1",
"version": "1.0.0",
"description": "",
"main": "src/server.ts",
"scripts": {
"start": "nodemon src/server.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@tsconfig/node18": "^1.0.1",
"@types/compression": "^1.7.2",
"@types/cookie-parser": "^1.4.3",
"@types/cors": "^2.8.13",
"@types/hpp": "^0.2.2",
"@types/swagger-jsdoc": "^6.0.1",
"@types/swagger-ui-express": "^4.1.3"
},
"dependencies": {
"@types/express": "^4.17.14",
"@types/node": "^18.11.13",
"body-parser": "^1.20.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"cloudinary": "^1.33.0",
"compression": "^1.7.4",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"helmet": "^6.0.1",
"hpp": "^0.2.3",
"mongoose": "^6.8.0",
"morgan": "^1.10.0",
"multer": "^1.4.5-lts.1",
"multer-storage-cloudinary": "^4.0.0",
"nodemon": "^2.0.20",
"swagger-jsdoc": "^6.2.5",
"swagger-ui-express": "^4.6.0"
}
}
File added
import express from 'express';
import compression from 'compression';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import helmet from 'helmet';
import hpp from 'hpp';
import { connect, set } from 'mongoose';
import swaggerJSDoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import { Routes } from './interfaces/routes.interface';
class App {
public app: express.Application;
public hostName: string;
public port: number;
private url: string;
constructor(routes: Routes[]) {
this.app = express();
this.port = 8500;
this.hostName = '127.0.0.1';
this.url = "mongodb+srv://hirusha2577:ksxyQfIqw8RzH6Jh@speakezy.6ge9gev.mongodb.net/SpeakEzy?retryWrites=true&w=majority&appName=SpeakEzy"
this.connectToDatabase();
this.initializeMiddlewares();
this.initializeRoutes(routes);
this.initializeSwagger();
}
public listen() {
this.app.listen(this.port, this.hostName, () => {
console.log(`-----------------------------------------------`);
console.log(`-----------------------------------------------`);
console.log(`🚀 Server is started at http://${this.hostName}:${this.port}`);
console.log(`-----------------------------------------------`);
});
}
public getServer() {
return this.app;
}
private connectToDatabase() {
set('strictQuery', true);
connect(this.url,()=>{
console.log(`-----------------------------------------------`);
console.log(`🚀 Mongo_db connection success!`);
console.log(`-----------------------------------------------`);
console.log(`-----------------------------------------------`);
});
}
private initializeMiddlewares() {
this.app.use(cors());
this.app.use(hpp());
this.app.use(helmet());
this.app.use(compression());
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(cookieParser());
}
private initializeRoutes(routes: Routes[]) {
routes.forEach(route => {
this.app.use('/', route.router);
});
}
private initializeSwagger() {
const options = {
swaggerDefinition: {
info: {
title: 'REST API',
version: '1.0.0',
description: 'Example docs',
},
},
apis: ['swagger.yaml'],
};
const specs = swaggerJSDoc(options);
this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
}
}
export default App;
\ No newline at end of file
import { v2 as cloudinary } from 'cloudinary'
import { CloudinaryStorage } from 'multer-storage-cloudinary';
cloudinary.config({
cloud_name: 'dlynw1irw',
api_key: '795461795315199',
api_secret: 'mQr1JUqFBcHOvDjFeIBfVpOvDeQ'
});
export const storage = new CloudinaryStorage({
cloudinary,
params: {
folder: 'SpeakEzy',
allowedFormats: ['jpeg', 'png', 'jpg', 'mp4']
}
});
import { NextFunction, Request, Response } from 'express';
import { Games } from '../interfaces/games.interface';
import gamesService from '../services/games.service';
import gamesModel from '../models/games.model';
interface MulterRequest extends Request {
file: any;
}
class GamesController {
public gamesService = new gamesService();
public getUnlockGamesByLevel = async (req: Request, res: Response, next: NextFunction) => {
try {
const level: string = req.params.level;
const findAllGamesData: Games[] = await this.gamesService.getUnlockGamesByLevel(level);
res.status(200).json({ data: findAllGamesData, message: 'findAll' });
} catch (error) {
next(error);
}
};
public getLockGamesByLevel = async (req: Request, res: Response, next: NextFunction) => {
try {
const level: string = req.params.level;
const findAllGamesData: Games[] = await this.gamesService.getLockGamesByLevel(level);
res.status(200).json({ data: findAllGamesData, message: 'findAll' });
} catch (error) {
next(error);
}
};
public getGameById = async (req: Request, res: Response, next: NextFunction) => {
try {
const id: string = req.params.id;
const findOneGameData: Games = await this.gamesService.getGameById(id);
res.status(200).json({ data: findOneGameData, message: 'findOne' });
} catch (error) {
next(error);
}
};
public createGame = async (req: MulterRequest, res: Response, next: NextFunction) => {
try {
const level = req.body.level;
const number = req.body.number;
const question = req.body.question;
const a1 = req.body.a1;
const a2 = req.body.a2;
const a3 = req.body.a3;
const a4 = req.body.a4;
const correct = req.body.correct;
const status = req.body.status;
let video = "https://res.cloudinary.com/dlynw1irw/video/upload/v1710757723/SpeakEzyVideos/09_v5g9hy.mov";
// if (req.file !== undefined) {
// video = req.file.path
// }
let newProduct = new gamesModel({
level, number, question, a1, a2, a3, a4, correct,video, status
})
const createGameData: Games = await this.gamesService.createGame(newProduct);
res.status(201).json({ data: createGameData, message: 'created' });
} catch (error) {
next(error);
}
};
public deleteGame = async (req: Request, res: Response, next: NextFunction) => {
try {
const id: string = req.params.id;
const deleteGameData: Games = await this.gamesService.deleteGame(id);
res.status(200).json({ data: deleteGameData, message: 'deleted' });
} catch (error) {
next(error);
}
};
}
export default GamesController;
import { NextFunction, Request, Response } from 'express';
import { CreateItemsDto } from '../dtos/items.dto';
import { Items } from '../interfaces/items.interface';
import itemsService from '../services/items.service';
import itemsModel from '../models/item.model';
interface MulterRequest extends Request {
file: any;
}
class ItemsController {
public itemsService = new itemsService();
public findAllItems = async (req: Request, res: Response, next: NextFunction) => {
try {
const findAllItemsData: Items[] = await this.itemsService.findAllItems();
res.status(200).json({ data: findAllItemsData, message: 'findAll' });
} catch (error) {
next(error);
}
};
public findItemsById = async (req: Request, res: Response, next: NextFunction) => {
try {
const itemsId: string = req.params.id;
const findOneItemsData: Items = await this.itemsService.findItemsById(itemsId);
res.status(200).json({ data: findOneItemsData, message: 'findOne' });
} catch (error) {
next(error);
}
};
public findItemsByResourcesId = async (req: Request, res: Response, next: NextFunction) => {
try {
const resourcesId: string = req.params.resourcesId;
const findItemsData: Items[] = await this.itemsService.findItemsByResourcesId(resourcesId);
res.status(200).json({ data: findItemsData, message: 'findOne' });
} catch (error) {
next(error);
}
};
public createItems = async (req: MulterRequest, res: Response, next: NextFunction) => {
try {
const resourcesId = req.body.resourcesId;
const topic = req.body.topic;
const details = req.body.details;
const label = req.body.label;
let image = "";
if (req.file !== undefined) {
image = req.file.path
}
let newItems = new itemsModel({
resourcesId, topic, details, label, image
})
const createItemsData: Items = await this.itemsService.createItems(newItems);
res.status(201).json({ data: createItemsData, message: 'created' });
} catch (error) {
next(error);
}
};
public updateItems = async (req: Request, res: Response, next: NextFunction) => {
try {
const itemsId: string = req.params.id;
const itemsData: CreateItemsDto = req.body;
const updateItemsData: Items = await this.itemsService.updateItems(itemsId, itemsData);
res.status(200).json({ data: updateItemsData, message: 'updated' });
} catch (error) {
next(error);
}
};
public deleteItems = async (req: Request, res: Response, next: NextFunction) => {
try {
const itemsId: string = req.params.id;
const deleteItemsData: Items = await this.itemsService.deleteItems(itemsId);
res.status(200).json({ data: deleteItemsData, message: 'deleted' });
} catch (error) {
next(error);
}
};
}
export default ItemsController;
import { NextFunction, Request, Response } from 'express';
import { CreateResourcesDto } from '../dtos/resources.dto';
import { Resources } from '../interfaces/resources.interface';
import resourcesService from '../services/resources.service';
import resourcesModel from '../models/resources.model';
class ResourcesController {
public resourcesService = new resourcesService();
public findAllResources = async (req: Request, res: Response, next: NextFunction) => {
try {
const findAllResourcesData: Resources[] = await this.resourcesService.findAllResources();
res.status(200).json({ data: findAllResourcesData, message: 'findAll' });
} catch (error) {
next(error);
}
};
public findResourcesById = async (req: Request, res: Response, next: NextFunction) => {
try {
const resourcesId: string = req.params.id;
const findOneResourcesData: Resources = await this.resourcesService.findResourcesById(resourcesId);
res.status(200).json({ data: findOneResourcesData, message: 'findOne' });
} catch (error) {
next(error);
}
};
public findResourcesByLevel = async (req: Request, res: Response, next: NextFunction) => {
try {
const level: string = req.params.level;
const findResourcesData: Resources[] = await this.resourcesService.findResourcesByLevel(level);
res.status(200).json({ data: findResourcesData, message: 'findOne' });
} catch (error) {
next(error);
}
};
public createResources = async (req: Request, res: Response, next: NextFunction) => {
try {
const topic = req.body.topic;
const details = req.body.details;
const level = req.body.level;
let newResources = new resourcesModel({
topic, details, level
})
const createResourcesData: Resources = await this.resourcesService.createResources(newResources);
res.status(201).json({ data: createResourcesData, message: 'created' });
} catch (error) {
next(error);
}
};
public updateResources = async (req: Request, res: Response, next: NextFunction) => {
try {
const id: string = req.params.id;
const resourcesData: CreateResourcesDto = req.body;
const updateResourcesData: Resources = await this.resourcesService.updateResources(id, resourcesData);
res.status(200).json({ data: updateResourcesData, message: 'updated' });
} catch (error) {
next(error);
}
};
public deleteResources = async (req: Request, res: Response, next: NextFunction) => {
try {
const id: string = req.params.id;
const deleteResourcesData: Resources = await this.resourcesService.deleteResources(id);
res.status(200).json({ data: deleteResourcesData, message: 'deleted' });
} catch (error) {
next(error);
}
};
}
export default ResourcesController;
import { NextFunction, Request, Response } from 'express';
import { Users } from '../interfaces/users.interface';
import usersService from '../services/users.service';
import usersModel from '../models/users.model';
class UsersController {
public usersService = new usersService();
public findUsersById = async (req: Request, res: Response, next: NextFunction) => {
try {
const userId: string = req.params.id;
const findOneUserData: Users = await this.usersService.findUsersById(userId);
res.status(200).json({ data: findOneUserData, message: 'findOne' });
} catch (error) {
next(error);
}
};
public findUsersByEmailAndPassword = async (req: Request, res: Response, next: NextFunction) => {
try {
const email: string = req.body.email;
const password: string = req.body.password;
console.log(email)
console.log(password)
const findUserData: Users = await this.usersService.findUsersByEmailAndPassword(email,password);
if(findUserData){
res.status(200).json({ data: findUserData, message: 'true' });
}else{
res.status(200).json({ data: findUserData, message: 'false' });
}
} catch (error) {
next(error);
}
};
public createUsers = async (req: Request, res: Response, next: NextFunction) => {
try {
const name = req.body.name;
const email = req.body.email;
const dob = req.body.dob;
const gender = req.body.gender;
const phone = req.body.phone;
const password = req.body.password;
const intermediateGameLevel = 1;
const advancedGameLevel = 1;
const gameScore = 0;
const learnScore = 0;
const status = "A";
let newUser = new usersModel({
name, email, dob, gender, phone, password, intermediateGameLevel, advancedGameLevel, gameScore, learnScore, status
})
const createUserData: Users = await this.usersService.createUsers(newUser);
res.status(201).json({ data: createUserData, message: 'created' });
} catch (error) {
next(error);
}
};
}
export default UsersController;
import { IsArray, IsEmpty, IsNotEmpty, IsObject, IsString } from 'class-validator';
export class CreateGamesDto {
// @IsString()
public level: string;
// @IsString()
public number: string;
/// @IsString()
public question: string;
// @IsString()
public a1: string;
// @IsString()
public a2: string;
// @IsString()
public a3: string;
// @IsString()
public a4: string;
// @IsString()
public correct: string;
// @IsString()
public video: string;
// @IsString()
public status: string;
}
import { IsArray, IsEmpty, IsNotEmpty, IsObject, IsString } from 'class-validator';
export class CreateItemsDto {
// @IsArray()
public resourcesId: string;
// @IsArray()
public topic: string;
// @IsString()
public details: string;
// @IsString()
public image: string;
// @IsString()
public label: string;
}
import { IsArray, IsEmpty, IsNotEmpty, IsObject, IsString } from 'class-validator';
export class CreateResourcesDto {
@IsString()
public topic: string;
@IsString()
public details: string;
@IsString()
public level: string;
}
import { IsArray, IsEmpty, IsNotEmpty, IsObject, IsString } from 'class-validator';
export class CreateUsersDto {
// @IsString()
public name: string;
// @IsString()
public email: string;
/// @IsString()
public dob: string;
// @IsString()
public gender: string;
// @IsString()
public password: string;
// @IsString()
public phone: string;
// @IsString()
public intermediateGameLevel: number;
// @IsString()
public advancedGameLevel: number;
// @IsString()
public gameScore: number;
// @IsString()
public learnScore: number;
// @IsString()
public status: string;
}
export class HttpException extends Error {
public status: number;
public message: string;
constructor(status: number, message: string) {
super(message);
this.status = status;
this.message = message;
}
}
export interface Games {
_id: string;
level: string;
number: string;
question: string;
a1: string;
a2: string;
a3: string;
a4: string;
correct: string;
video: string;
status: string;
}
\ No newline at end of file
export interface Items {
_id: string;
resourcesId: string;
topic: string
details: string;
image: string;
label: string;
}
\ No newline at end of file
export interface Resources {
_id: string;
topic: string
details: string;
level: string;
}
\ No newline at end of file
import { Router } from 'express';
export interface Routes {
path?: string;
router: Router;
}
export interface Users {
_id: string;
name: string;
email: string;
dob: string;
gender: string;
password: string;
phone: string;
intermediateGameLevel: number;
advancedGameLevel: number;
gameScore: number;
learnScore: number;
status: string;
}
\ No newline at end of file
import { NextFunction, Request, Response } from 'express';
import { HttpException } from '../exceptions/HttpException';
const errorMiddleware = (error: HttpException, req: Request, res: Response, next: NextFunction) => {
try {
const status: number = error.status || 500;
const message: string = error.message || 'Something went wrong';
console.log(`[${req.method}] ${req.path} >> StatusCode:: ${status}, Message:: ${message}`);
res.status(status).json({ message });
} catch (error) {
next(error);
}
};
export default errorMiddleware;
import { plainToClass } from 'class-transformer';
import { validate, ValidationError } from 'class-validator';
import { RequestHandler } from 'express';
import { HttpException } from '../exceptions/HttpException';
const validationMiddleware = (
type: any,
value: string | 'body' | 'query' | 'params' = 'body',
skipMissingProperties = false,
whitelist = true,
forbidNonWhitelisted = true,
): RequestHandler => {
return (req, res, next) => {
validate(plainToClass(type, req[value]), { skipMissingProperties, whitelist, forbidNonWhitelisted }).then((errors: ValidationError[]) => {
if (errors.length > 0) {
const message = errors.map((error: ValidationError) => Object.values(error.constraints)).join(', ');
next(new HttpException(400, message));
} else {
next();
}
});
};
};
export default validationMiddleware;
import { model, Schema, Document } from 'mongoose';
import { Games } from '../interfaces/games.interface';
const gamesSchema: Schema = new Schema({
level: {
type: String,
required: true,
unique: false
},
number: {
type: String,
required: true,
unique: false
},
question: {
type: String,
required: true,
unique: false
},
a1: {
type: String,
required: true,
unique: false
},
a2: {
type: String,
required: true,
unique: false
},
a3: {
type: String,
required: true,
unique: false
},
a4: {
type: String,
required: true,
unique: false
},
correct: {
type: String,
required: true,
unique: false
},
video: {
type: String,
required: true,
unique: false
},
status: {
type: String,
required: true,
unique: false
}
});
const gamesModel = model<Games & Document>('Games', gamesSchema);
export default gamesModel;
import { model, Schema, Document } from 'mongoose';
import { Items } from '../interfaces/items.interface';
const itemsSchema: Schema = new Schema({
resourcesId: {
type: String,
required: true,
unique: false
},
topic: {
type: String,
required: true,
unique: false
},
details: {
type: String,
required: true,
unique: false
},
image: {
type: String,
required: false,
unique: false
},
label: {
type: String,
required: true,
unique: false
}
});
const itemsModel = model<Items & Document>('Items', itemsSchema);
export default itemsModel;
import { model, Schema, Document } from 'mongoose';
import { Resources } from '../interfaces/resources.interface';
const resourcesSchema: Schema = new Schema({
topic: {
type: String,
required: true,
unique: false
},
details: {
type: String,
required: true,
unique: false
},
level: {
type: String,
required: true,
unique: false
}
});
const resourcesModel = model<Resources & Document>('Resources', resourcesSchema);
export default resourcesModel;
import { model, Schema, Document } from 'mongoose';
import { Users } from '../interfaces/users.interface';
const usersSchema: Schema = new Schema({
name: {
type: String,
required: true,
unique: false
},
email: {
type: String,
required: true,
unique: false
},
dob: {
type: String,
required: true,
unique: false
},
gender: {
type: String,
required: true,
unique: false
},
password: {
type: String,
required: true,
unique: false
},
phone: {
type: String,
required: true,
unique: false
},
intermediateGameLevel: {
type: Number,
required: true,
unique: false
},
advancedGameLevel: {
type: Number,
required: true,
unique: false
},
gameScore: {
type: Number,
required: true,
unique: false
},
learnScore: {
type: Number,
required: true,
unique: false
},
status: {
type: String,
required: true,
unique: false
}
});
const usersModel = model<Users & Document>('Users', usersSchema);
export default usersModel;
import { Router } from 'express';
import gamesController from '../controllers/games.controller';
import { Routes } from '../interfaces/routes.interface';
class GamesRoute implements Routes {
public path = '/games';
public router = Router();
public gamesController = new gamesController();
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.get(`${this.path}//:level`, this.gamesController.getUnlockGamesByLevel);
this.router.get(`${this.path}///:level`, this.gamesController.getLockGamesByLevel);
this.router.get(`${this.path}/:id`, this.gamesController.getGameById);
this.router.post(`${this.path}`, this.gamesController.createGame);
this.router.delete(`${this.path}/:id`, this.gamesController.deleteGame);
}
}
export default GamesRoute;
import { Router } from 'express';
import itemsController from '../controllers/items.controller';
import { CreateItemsDto } from '../dtos/items.dto';
import { Routes } from '../interfaces/routes.interface';
import validationMiddleware from '../middlewares/validation.middleware';
import multer from 'multer';
import { storage } from '../cloudinary/index.js';
const upload = multer({ storage });
class ItemsRoute implements Routes {
public path = '/items';
public router = Router();
public itemsController = new itemsController();
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.get(`${this.path}`, this.itemsController.findAllItems);
this.router.get(`${this.path}/:id`, this.itemsController.findItemsById);
this.router.get(`${this.path}//:resourcesId`, this.itemsController.findItemsByResourcesId);
this.router.post(`${this.path}`, upload.single("image"), this.itemsController.createItems);
this.router.put(`${this.path}/:id`, validationMiddleware(CreateItemsDto, 'body', true), this.itemsController.updateItems);
this.router.delete(`${this.path}/:id`, this.itemsController.deleteItems);
}
}
export default ItemsRoute;
import { Router } from 'express';
import resourcesController from '../controllers/Resources.controller';
import { CreateResourcesDto } from '../dtos/resources.dto';
import { Routes } from '../interfaces/routes.interface';
import validationMiddleware from '../middlewares/validation.middleware';
class ResourcesRouteRoute implements Routes {
public path = '/resources';
public router = Router();
public resourcesController = new resourcesController();
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.get(`${this.path}`, this.resourcesController.findAllResources);
this.router.get(`${this.path}/:id`, this.resourcesController.findResourcesById);
this.router.get(`${this.path}//:level`, this.resourcesController.findResourcesByLevel);
this.router.post(`${this.path}`, validationMiddleware(CreateResourcesDto, 'body'), this.resourcesController.createResources);
this.router.put(`${this.path}/:id`, validationMiddleware(CreateResourcesDto, 'body', true), this.resourcesController.updateResources);
this.router.delete(`${this.path}/:id`, this.resourcesController.deleteResources);
}
}
export default ResourcesRouteRoute;
import { Router } from 'express';
import usersController from '../controllers/users.controller';
import { CreateUsersDto } from '../dtos/users.dto';
import { Routes } from '../interfaces/routes.interface';
import validationMiddleware from '../middlewares/validation.middleware';
class CategoryRoute implements Routes {
public path = '/users';
public router = Router();
public usersController = new usersController();
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.get(`${this.path}`, this.usersController.findUsersById);
this.router.post(`${this.path}/login`, this.usersController.findUsersByEmailAndPassword);
this.router.post(`${this.path}`, this.usersController.createUsers);
}
}
export default CategoryRoute;
import App from './app';
import ResourcesRoute from './routes/resources.route';
import ItemsRoute from './routes/items.routes';
import UsersRoute from './routes/users.route';
import GamesRoute from './routes/game.route';
const app = new App([ new ResourcesRoute(), new ItemsRoute(), new UsersRoute(), new GamesRoute()]);
app.listen();
\ No newline at end of file
import { HttpException } from '../exceptions/HttpException';
import { Games } from '@/interfaces/games.interface';
import gamesModel from '../models/games.model';
import { isEmpty } from '../utils/util';
class GamesService {
public games = gamesModel;
public async getUnlockGamesByLevel(level: string): Promise<Games[]> {
if (isEmpty(level)) throw new HttpException(400, "expenseId is empty");
const findGames: Games[] = await this.games.find({ level: level, status: 'U' });
if (!findGames) throw new HttpException(409, "Expense doesn't exist");
return findGames;
}
public async getLockGamesByLevel(level: string): Promise<Games[]> {
if (isEmpty(level)) throw new HttpException(400, "expenseId is empty");
const findGames: Games[] = await this.games.find({ level: level, status: 'L' });
if (!findGames) throw new HttpException(409, "Expense doesn't exist");
return findGames;
}
public async getGameById(id: string): Promise<Games> {
const findGame: Games = await this.games.findOne({ _id: id});
if (!findGame) throw new HttpException(409, "Expense doesn't exist");
return findGame;
}
public async createGame(gameData: Games): Promise<Games> {
if (isEmpty(gameData)) throw new HttpException(400, "expenseData is empty");
const createGameData: Games = await this.games.create(gameData);
return createGameData;
}
public async deleteGame(id: string): Promise<Games> {
const deleteGameById: Games = await this.games.findByIdAndDelete(id);
if (!deleteGameById) throw new HttpException(409, "Expense doesn't exist");
return deleteGameById;
}
}
export default GamesService;
import { CreateItemsDto } from '../dtos/items.dto';
import { HttpException } from '../exceptions/HttpException';
import { Items } from '@/interfaces/items.interface';
import itemsModel from '../models/item.model';
import { isEmpty } from '../utils/util';
class ItemsService {
public items = itemsModel;
public async findAllItems(): Promise<Items[]> {
const items: Items[] = await this.items.find();
return items;
}
public async findItemsById(itemsId: string): Promise<Items> {
if (isEmpty(itemsId)) throw new HttpException(400, "expenseId is empty");
const findItem: Items = await this.items.findOne({ _id: itemsId });
if (!findItem) throw new HttpException(409, "Expense doesn't exist");
return findItem;
}
public async findItemsByResourcesId(resourcesId: string): Promise<Items[]> {
const findItems: Items[] = await this.items.find({ resourcesId: resourcesId});
if (!findItems) throw new HttpException(409, "Expense doesn't exist");
return findItems;
}
public async createItems(ItemsData: Items): Promise<Items> {
if (isEmpty(ItemsData)) throw new HttpException(400, "expenseData is empty");
const createItemsData: Items = await this.items.create(ItemsData);
return createItemsData;
}
public async updateItems(itemsId: string, itemsData: CreateItemsDto): Promise<Items> {
if (isEmpty(itemsData)) throw new HttpException(400, "expenseData is empty");
const updateItemsById: Items = await this.items.findByIdAndUpdate(itemsId,itemsData);
if (!updateItemsById) throw new HttpException(409, "Expense doesn't exist");
return updateItemsById;
}
public async deleteItems(itemsId: string): Promise<Items> {
const deleteItemsById: Items = await this.items.findByIdAndDelete(itemsId);
if (!deleteItemsById) throw new HttpException(409, "Expense doesn't exist");
return deleteItemsById;
}
}
export default ItemsService;
import { CreateResourcesDto } from '../dtos/resources.dto';
import { HttpException } from '../exceptions/HttpException';
import { Resources } from '@/interfaces/resources.interface';
import resourcesModel from '../models/resources.model';
import { isEmpty } from '../utils/util';
class ResourcesService {
public resources = resourcesModel;
public async findAllResources(): Promise<Resources[]> {
const resources: Resources[] = await this.resources.find();
return resources;
}
public async findResourcesById(resourcesId: string): Promise<Resources> {
if (isEmpty(resourcesId)) throw new HttpException(400, "expenseId is empty");
const findResources: Resources = await this.resources.findOne({ _id: resourcesId });
if (!findResources) throw new HttpException(409, "Expense doesn't exist");
return findResources;
}
public async findResourcesByLevel(level: string): Promise<Resources[]> {
const findResources: Resources[] = await this.resources.find({ level: level});
if (!findResources) throw new HttpException(409, "Expense doesn't exist");
return findResources;
}
public async createResources(resourcesData: Resources): Promise<Resources> {
if (isEmpty(resourcesData)) throw new HttpException(400, "expenseData is empty");
const createResourcesData: Resources = await this.resources.create(resourcesData);
return createResourcesData;
}
public async updateResources(resourcesId: string, resourcesData: CreateResourcesDto): Promise<Resources> {
if (isEmpty(resourcesData)) throw new HttpException(400, "expenseData is empty");
const updateResourcesById: Resources = await this.resources.findByIdAndUpdate(resourcesId,resourcesData);
if (!updateResourcesById) throw new HttpException(409, "Expense doesn't exist");
return updateResourcesById;
}
public async deleteResources(resourcesId: string): Promise<Resources> {
const deleteResourcesById: Resources = await this.resources.findByIdAndDelete(resourcesId);
if (!deleteResourcesById) throw new HttpException(409, "Expense doesn't exist");
return deleteResourcesById;
}
}
export default ResourcesService;
import { HttpException } from '../exceptions/HttpException';
import { Users } from '@/interfaces/users.interface';
import usersModel from '../models/users.model';
import { isEmpty } from '../utils/util';
class UsersService {
public users = usersModel;
public async findUsersById(userId: string): Promise<Users> {
if (isEmpty(userId)) throw new HttpException(400, "expenseId is empty");
const findUser: Users = await this.users.findOne({ _id: userId });
if (!findUser) throw new HttpException(409, "Expense doesn't exist");
return findUser;
}
public async findUsersByEmailAndPassword(email: string, password: string): Promise<Users> {
console.log(email)
console.log(password)
const findUser: Users = await this.users.findOne({ email: email, password:password});
return findUser;
}
public async createUsers(usersData: Users): Promise<Users> {
if (isEmpty(usersData)) throw new HttpException(400, "expenseData is empty");
const createUsersData: Users = await this.users.create(usersData);
return createUsersData;
}
}
export default UsersService;
/**
* @method isEmpty
* @param {String | Number | Object} value
* @returns {Boolean} true & false
* @description this value is Empty Check
*/
export const isEmpty = (value: string | number | object): boolean => {
if (value === null) {
return true;
} else if (typeof value !== 'number' && value === '') {
return true;
} else if (typeof value === 'undefined' || value === undefined) {
return true;
} else if (value !== null && typeof value === 'object' && !Object.keys(value).length) {
return true;
} else {
return false;
}
};
{
"compileOnSave": false,
"compilerOptions": {
"target": "es2022",
"lib": ["es2022", "esnext.asynciterable"],
"typeRoots": ["node_modules/@types"],
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"module": "commonjs",
"pretty": true,
"sourceMap": true,
"declaration": true,
"outDir": "dist",
"allowJs": true,
"noEmit": false,
"esModuleInterop": true,
"resolveJsonModule": true,
"importHelpers": true,
"baseUrl": "src",
"paths": {
"@/*": ["*"],
"@config": ["config"],
"@controllers/*": ["controllers/*"],
"@databases": ["databases"],
"@dtos/*": ["dtos/*"],
"@exceptions/*": ["exceptions/*"],
"@interfaces/*": ["interfaces/*"],
"@middlewares/*": ["middlewares/*"],
"@models/*": ["models/*"],
"@routes/*": ["routes/*"],
"@services/*": ["services/*"],
"@utils/*": ["utils/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.json", ".env"],
"exclude": ["node_modules", "src/http", "src/logs", "src/tests"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment