Skip to content

Commit

Permalink
Merge pull request #2 from CajaCodes/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
DanielDDHM authored Jun 6, 2022
2 parents 762f81d + e7e9558 commit 69c2ce5
Show file tree
Hide file tree
Showing 62 changed files with 2,312 additions and 1,672 deletions.
6 changes: 3 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
FROM node:lts-alpine
ENV NODE_ENV=development
WORKDIR /usr/src/app
WORKDIR /usr/src
COPY ["package.json", "package-lock.json*", "npm-shrinkwrap.json*", "./"]
RUN npm install --development --silent && mv node_modules ../
COPY . .
EXPOSE 3000
RUN chown -R node /usr/src/app
RUN chown -R node /usr/src
USER node
CMD ["npm", "run", "start"]
CMD ["npm", "run", "start:container"]
7 changes: 7 additions & 0 deletions envs/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
DATABASE_URL =
NAME =
PORT =
REDIS_PORT =
AUTH_SECRET =
STORAGE_DRIVER =

20 changes: 13 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
"author": "DanielDDHM <[email protected]>",
"license": "MIT",
"dependencies": {
"bcrypt": "^5.0.1",
"@prisma/client": "^3.14.0",
"axios": "^0.27.2",
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.0",
"bullmq": "^1.83.0",
"chalk": "^5.0.1",
Expand All @@ -15,13 +17,16 @@
"docker": "^1.0.0",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"express-async-errors": "^3.1.1",
"fs": "^0.0.1-security",
"helmet": "^5.1.0",
"https": "^1.0.0",
"ioredis": "^5.0.5",
"jest": "^28.1.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"mongoose": "^6.3.4",
"morgan": "^1.10.0",
"path": "^0.12.7",
"prettier": "^2.6.2",
"prisma": "^3.14.0",
"promise": "^8.1.0",
Expand All @@ -33,21 +38,22 @@
"zod": "^3.17.3"
},
"devDependencies": {
"@types/bcrypt": "^5.0.0",
"@types/bcryptjs": "^2.4.2",
"@types/chalk": "^2.2.0",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/mongoose": "^5.11.97",
"@types/jsonwebtoken": "^8.5.8",
"@types/morgan": "^1.9.3",
"@typescript-eslint/eslint-plugin": "^5.25.0",
"@typescript-eslint/parser": "^5.25.0",
"cross-env": "^7.0.3",
"eslint": "^8.16.0",
"husky": "^8.0.1",
"nodemon": "^2.0.16"
"husky": "^8.0.1"
},
"scripts": {
"start": "npm run lint:fix && npm run dev",
"dev": "nodemon ts-node-dev --inspect --transpile-only src/app.ts",
"dev": "ts-node-dev --exit-child --transpile-only --ignore-watch node_modules src/app.ts",
"start:container": "npm run lint:fix && prisma generate && npm run dev",
"lint": "eslint --ext js,ts src",
"lint:fix": "eslint --ext js,ts src --fix",
"docker:up": "docker-compose -f docker-compose.test.yml up -d",
Expand Down
83 changes: 83 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "linux-musl"]
previewFeatures = ["mongodb"]
}

model users {
id String @id @default(auto()) @map("_id") @db.ObjectId
nick String @unique
name String
email String @unique
phone String
password String
photo String?
isActive Boolean? @default(false)
isConfirmed Boolean? @default(false)
isStaff Boolean? @default(false)
address address? @relation(fields: [addressId], references: [id])
addressId String? @db.ObjectId
bets bets[]
gameOwn game[]
createdAt DateTime @default(now())
updatedAt DateTime? @default(now())
token token?
}

model address {
id String @id @default(auto()) @map("_id") @db.ObjectId
streetNumber Int
zipCode String
street String?
neighborhood String?
city String?
state String?
users users[]
createdAt DateTime @default(now())
updatedAt DateTime? @default(now())
}

model bets {
id String @id @default(auto()) @map("_id") @db.ObjectId
value String
winner Boolean? @default(false)
createdAt DateTime @default(now())
updatedAt DateTime? @default(now())
users users? @relation(fields: [usersId], references: [id])
usersId String? @db.ObjectId
game game? @relation(fields: [gameId], references: [id])
gameId String? @db.ObjectId
}

model game {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
owner users? @relation(fields: [ownerId], references: [id])
winner String?
sortDate DateTime
bets bets[]
prize String
prizePhoto String?
isActive Boolean? @default(false)
createdAt DateTime @default(now())
updatedAt DateTime? @default(now())
ownerId String? @db.ObjectId
}

model token {
id String @id @default(auto()) @map("_id") @db.ObjectId
token String @unique
user users? @relation(fields: [usersId], references: [id])
usersId String? @unique @db.ObjectId
expDate DateTime?
createdAt DateTime @default(now())
updatedAt DateTime? @default(now())
}
6 changes: 6 additions & 0 deletions src/@types/express/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare namespace Express {
export interface Request {
nick: string
}
}

38 changes: 22 additions & 16 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import express, { Request, Response, NextFunction } from 'express';
import { AppError } from './helpers';
import "express-async-errors";
import 'dotenv/config';

import rootRoutes from './routes';

const { DATABASE_URL, PORT, NAME } = process.env
const { PORT, NAME } = process.env

const app = express();

Expand All @@ -14,26 +15,31 @@ app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());

app.use(
(error: Error, request: Request, response: Response, next: NextFunction) => {
if (error instanceof AppError) {
return response.status(500).json({ error: error });
}
return response.status(500).json({
status: "error",
message: `Internal server error - ${error.message}`,
});
}
);

// app use routes
app.use('/v1', rootRoutes)

// one call for test
app.get('/', (request, response) => {
const user = String(process.env.NAME) || "User";
const user = String(NAME) || "User";
return response.send({
message: `Hello ${user}`,
status: 'UP'
});
});

mongoose.connect(String(DATABASE_URL))
.then(() => {
console.log(`connecting to database successful, Dear ${NAME || "USER"}`)
app.listen(PORT, () => {
console.log(`App started on http://localhost:${PORT || 3000}`);
});
})
.catch(e => console.error('could not connect to DB', e))

mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));

app.listen(PORT, () => {
console.log(`App started on http://localhost:${PORT || 3000}, welcome ${NAME}`);
});

1 change: 1 addition & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as prisma } from '../config/prisma'
6 changes: 6 additions & 0 deletions src/config/prisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { PrismaClient } from '@prisma/client';

const client = new PrismaClient();

export * from '@prisma/client';
export default client;
2 changes: 2 additions & 0 deletions src/config/redis.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import IOredis from 'ioredis';
import 'dotenv/config';
30 changes: 30 additions & 0 deletions src/controllers/address.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import {
StatusCode,
CreateAddressDTO,
GetAddressDTO
} from "../types";
import { AddressService } from "../services";
import { Request, Response } from 'express';

export default class AddressController {

async get(req: Request, res: Response) {
const { body } = req;
try {
const address = await new AddressService(body as GetAddressDTO).get()
return res.status(StatusCode.OK).send(address)
} catch (error: any) {
res.status(Number(StatusCode.INTERNAL_SERVER_ERROR)).json(error)
}
}

async create(req: Request, res: Response) {
const { body } = req;
try {
const addressCreated = await new AddressService(body as CreateAddressDTO).create()
return res.status(StatusCode.OK).send({ data: addressCreated, message: 'ADDRESS CREATED' })
} catch (error: any) {
res.status(Number(StatusCode.INTERNAL_SERVER_ERROR)).json(error)
}
}
}
59 changes: 59 additions & 0 deletions src/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@

import { NextFunction, Request, Response } from 'express';
import { Auth } from '../helpers';
import { StatusCode } from '../types';

export default class AuthController {

async login(req: Request, res: Response) {
const { body } = req;
try {
const userLogin = await new Auth(body).login()
return res.status(StatusCode.OK).send(userLogin)
} catch (error: any) {
res.status(Number(StatusCode.INTERNAL_SERVER_ERROR)).json(error)
}
}

async verifyLogin(req: Request, res: Response, next: NextFunction) {
try {
const token = req.headers['x-access-token'];
const nick = req.headers['x-access-nick'];

if (!token) return res.status(StatusCode.UNAUTHORIZED)
.send({ auth: false, message: 'NO TOKEN PROVIDED' });

const auth = await new Auth(null, { token }).verifyToken();

if (auth?.decodedToken?.data != nick) {
res.status(StatusCode.BAD_REQUEST).send({ message: 'THIS IS NOT YOUR CODE' })
}

return next()
} catch (error: any) {
res.status(Number(error.statusCode)).json(error)
}
}

async logout(req: Request, res: Response) {
try {
const token = req.headers['x-access-token'];
const userLogout = await new Auth().logout({ token })
res.status(StatusCode.OK).send(userLogout);
} catch (error: any) {
res.status(Number(StatusCode.INTERNAL_SERVER_ERROR)).json(error)
}
}

async checkRole(req: Request, res: Response, next: NextFunction) {
// TODO: AJUSTAR A FUNCAO CHECKROLE
try {
const nick = req.headers['x-access-nick'];
await new Auth(null, { nick }).checkRole()

return next()
} catch (error: any) {
res.status(Number(StatusCode.INTERNAL_SERVER_ERROR)).json(error)
}
}
}
44 changes: 36 additions & 8 deletions src/controllers/bets.controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,42 @@
import { StatusCode } from "../types";
import {
StatusCode,
BetsCreateDTO,
BetsGetDTO,
BetsDeleteDTO,
} from "../types";
import { Request, Response } from 'express';
import { AppError } from "../helpers";
import { BetService } from "../services";

export default class BetsController {

export const create = (req: Request, res: Response) => {
const { body } = req;
try {
return res.status(StatusCode.OK).send(body)
async get(req: Request, res: Response) {
const { body } = req;
try {
const bet = await new BetService(body as BetsGetDTO).get()
return res.status(StatusCode.OK).send({ data: bet, message: 'BETS' })
} catch (error: any) {
res.status(Number(StatusCode.INTERNAL_SERVER_ERROR)).json(error)
}
}

async create(req: Request, res: Response) {
const { body } = req;
try {
const betCreated = await new BetService(body as BetsCreateDTO).create()
return res.status(StatusCode.OK).send({ data: betCreated, message: 'BET CREATED' })
} catch (error: any) {
res.status(Number(StatusCode.INTERNAL_SERVER_ERROR)).json(error)
}
}

} catch (error: any) {
throw new AppError(String(error.message), StatusCode.INTERNAL_SERVER_ERROR)
async delete(req: Request, res: Response) {
const { id } = req.params
try {
const betDeleted = await new BetService(id as BetsDeleteDTO).delete
return res.status(StatusCode.OK).send({ data: betDeleted, message: 'BET DELETED' })
} catch (error: any) {
res.status(Number(StatusCode.INTERNAL_SERVER_ERROR)).json(error)
}
}

}
Loading

0 comments on commit 69c2ce5

Please sign in to comment.