Commit 9e0f689f authored by Cezar Rodrigues's avatar Cezar Rodrigues

Project struct

parents
Pipeline #305 canceled with stages
node_modules
.git
.vscode
volumes
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
DATABASE_URL="postgresql://esqueci:esqueci@localhost:2354/db_pedagoogando?schema=public"
\ No newline at end of file
node_modules
dist
{
"env": {
"es2020": true,
"node": true,
"jest": true
},
"extends": [
"airbnb-base",
"airbnb-typescript/base"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 13,
"sourceType": "module"
},
"plugins": [
"prettier",
"@typescript-eslint",
"eslint-plugin-import-helpers"
],
"rules": {
"@typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "_"
}
],
"prettier/prettier": "error",
"camelcase": "off",
"import/no-unresolved": "off",
"@typescript-eslint/naming-convention": [
"error",
{
"selector": "interface",
"format": [
"PascalCase"
],
"custom": {
"regex": "^I[A-Z]",
"match": true
}
}
],
"class-methods-use-this": "off",
"import/prefer-default-export": "off",
"no-shadow": "off",
"no-console": "off",
"no-useless-constructor": "off",
"no-empty-function": "off",
"lines-between-class-members": "off",
"import/extensions": [
"error",
"ignorePackages",
{
"ts": "never"
}
],
"import-helpers/order-imports": [
"warn",
{
"newlinesBetween": "always",
"groups": [
"module",
"/^@/",
[
"parent",
"sibling",
"index"
]
],
"alphabetize": {
"order": "asc",
"ignoreCase": true
}
}
],
"import/no-extraneous-dependencies": [
"error",
{
"devDependencies": [
"**/*.spec.js"
]
}
]
},
"settings": {
"import/resolver": {
"typescript": {}
}
}
}
node_modules
dist
volumes
coverage
# Files
.yarn-error.log
.env
.vscode
.git
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
#npm lint
{
"trailingComma": "all",
"tabWidth": 4,
"semi": true,
"singleQuote": true,
"arrowParens": "avoid"
}
FROM node:16-alpine
WORKDIR /usr/app
COPY package.json ./
COPY ./scripts/script.mjs ./
EXPOSE 4000
**How to run**
Execute esse comando no diretório raiz do projeto
docker-compose up
[OK] - CALENDAR
[OK] - USERS
[OK] - CURSES
[Ok] - INSTITUITIONS
[OK] - AUTH
[OK] - MESSAGES
[Ok] - FORUM
\ No newline at end of file
version: "3"
services:
db:
image: postgres
container_name: database_peda
restart: always
ports:
- 2354:5432
environment:
- POSTGRES_USER=esqueci
- POSTGRES_PASSWORD=esqueci
- POSTGRES_DB=db_pedagoogando
volumes:
- "./volumes/pg:/var/lib/postgresql/data"
db_pedagoogando:
build: .
container_name: db_pedagoogando
ports:
- 4000:4000
volumes:
- .:/usr/app
depends_on:
- db
environment:
- DATABASE_URL=postgresql://esqueci:esqueci@db:5432/db_db_pedagoogando
command: node ./scripts/script.mjs
\ No newline at end of file
import { pathsToModuleNameMapper } from 'ts-jest/utils';
import { compilerOptions } from './tsconfig.json';
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
bail: true,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/tmp/jest_rs",
// Automatically clear mock calls, instances and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: ['<rootDir>/src/modules/**/useCases/**/*.ts'],
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: ['text-summary', 'lcov'],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
prefix: '<rootDir>/src/',
}),
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
preset: 'ts-jest',
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
setupFiles: ['dotenv/config', 'reflect-metadata'],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: 'node',
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
testMatch: ['**/*.spec.ts'],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
testPathIgnorePatterns: ['/node_modules/'],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "pedagoogando",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored",
"dev": "ts-node-dev -r tsconfig-paths/register --inspect --transpile-only --ignore-watch node_modules --respawn src/shared/infra/http/server.ts",
"prepare": "husky install",
"lint": "eslint src/**/*.ts --fix"
},
"dependencies": {
"@prisma/client": "^3.12.0",
"@types/bcryptjs": "^2.4.2",
"@types/express": "^4.17.13",
"@types/node": "^17.0.23",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"express-async-errors": "^3.1.1",
"prisma": "^3.12.0",
"reflect-metadata": "^0.1.13",
"ts-node": "^10.7.0",
"ts-node-dev": "^1.1.8",
"tsyringe": "^4.6.0",
"typescript": "^4.6.3"
},
"devDependencies": {
"@types/cors": "^2.8.12",
"eslint": "^8.12.0",
"husky": "^7.0.4",
"prettier": "^2.6.2",
"tsconfig-paths": "^3.14.1"
}
}
-- CreateTable
CREATE TABLE "users" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"cpf" TEXT NOT NULL,
"curriculo" TEXT NOT NULL,
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "cursers" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"information" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "cursers_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "foruns" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"description" TEXT NOT NULL,
"isPublished" BOOLEAN NOT NULL DEFAULT true,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "foruns_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "institutions" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
CONSTRAINT "institutions_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "users_id_key" ON "users"("id");
-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
-- CreateIndex
CREATE UNIQUE INDEX "cursers_id_key" ON "cursers"("id");
-- CreateIndex
CREATE UNIQUE INDEX "foruns_id_key" ON "foruns"("id");
-- CreateIndex
CREATE UNIQUE INDEX "institutions_id_key" ON "institutions"("id");
-- CreateTable
CREATE TABLE "calendar" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"information" TEXT NOT NULL,
"date" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "calendar_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "message" (
"id" TEXT NOT NULL,
"message" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"forum_id" TEXT NOT NULL,
CONSTRAINT "message_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "calendar_id_key" ON "calendar"("id");
-- CreateIndex
CREATE UNIQUE INDEX "message_id_key" ON "message"("id");
-- AddForeignKey
ALTER TABLE "message" ADD CONSTRAINT "message_forum_id_fkey" FOREIGN KEY ("forum_id") REFERENCES "foruns"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
\ No newline at end of file
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @unique @default(uuid())
name String
email String @unique
password String
created_at DateTime @default(now())
cpf String
curriculo String
@@map("users")
}
model Curser {
id String @id @unique @default(uuid())
title String
information String
created_at DateTime @default(now())
@@map("cursers")
}
model Forum {
id String @id @unique @default(uuid())
title String
description String
messages Message[]
isPublished Boolean @default(true)
created_at DateTime @default(now())
@@map("foruns")
}
model Institutions {
id String @id @unique @default(uuid())
name String
@@map("institutions")
}
model Calendar {
id String @id @unique @default(uuid())
title String
information String
date String
created_at DateTime @default(now())
@@map("calendar")
}
model Message {
id String @id @unique @default(uuid())
message String
created_at DateTime @default(now())
forum_id String
forum Forum @relation(fields: [forum_id], references: [id])
@@map("message")
}
import child_process from 'child_process';
import util from 'util';
const execFile = util.promisify(child_process.execFile);
async function main() {
console.log((await execFile('yarn')).stdout);
console.log((await execFile('yarn', ['prisma', 'generate'])).stdout);
console.log((await execFile('yarn', ['prisma', 'migrate', 'dev'])).stdout);
console.log((await execFile('yarn', ['dev'])).stdout);
}
main();
interface ILoginDTO {
cpf: string,
password: string
}
export {ILoginDTO}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { LoginAuthenticationUseCase } from './LoginAuthenticationUseCase';
class LoginAuthenticationController {
async handle(request: Request, response: Response) {
const { cpf, password } = request.body
const loginAuthenticationUseCase = container.resolve(LoginAuthenticationUseCase)
const user = await loginAuthenticationUseCase.execute({
cpf,
password
})
return response.status(200).json(user)
}
}
export { LoginAuthenticationController }
\ No newline at end of file
import 'reflect-metadata';
import bcrypt from 'bcryptjs';
import { IUsersRepository } from '@modules/users/repositories/IUsersRepostory';
import { injectable, inject } from 'tsyringe';
import { AppError } from '@shared/error/AppError';
interface IRequest{
cpf: string,
password: string
}
@injectable()
class LoginAuthenticationUseCase {
constructor(
@inject('UsersRepository')
private usersRepository: IUsersRepository
) { }
async execute({cpf, password}: IRequest) {
const user = await this.usersRepository.findByCPF(cpf)
if (!user) {
throw new AppError('Not authorized', 404);
}
const passwordMatch = await bcrypt.compare(password, user.password)
if(!passwordMatch) {
throw new AppError('Not authorized', 404);
}
return user
}
}
export {LoginAuthenticationUseCase}
\ No newline at end of file
interface ICreateCalendarDTO {
id?: string,
title: string,
information: string,
date: string,
created_at?: Date;
}
export {ICreateCalendarDTO}
\ No newline at end of file
import { ICreateCalendarDTO } from "@modules/calendar/dtos/ICreateCalendarDTO"
import { Calendar } from "@prisma/client"
interface ICalendarsRepository {
create({title, information, date}: ICreateCalendarDTO): Promise<Calendar>
findById(id:string): Promise<Calendar>
findByTitle(title: string): Promise<Calendar>
findAllCalendar(): Promise<Calendar[]>
deleteCalendar(id: string): Promise<Boolean>
}
export {ICalendarsRepository}
\ No newline at end of file
import { ICreateCalendarDTO } from "@modules/calendar/dtos/ICreateCalendarDTO";
import { Calendar, prisma } from "@prisma/client";
import prismaClient from "@shared/infra/prisma";
import { ICalendarsRepository } from "../ICalendarsRepository";
class CalendarRepository implements ICalendarsRepository {
async create({ title, information, date }: ICreateCalendarDTO): Promise<Calendar> {
const calendar = await prismaClient.calendar.create({
data: {
title,
information,
date
}
})
return calendar
}
async findById(id: string): Promise<Calendar> {
const calendar = await prismaClient.calendar.findUnique({
where: { id }
})
return calendar as Calendar
}
async findAllCalendar(): Promise<Calendar[]> {
const calendars = await prismaClient.calendar.findMany()
return calendars
}
async findByTitle(title: string): Promise<Calendar> {
const calendar = await prismaClient.calendar.findFirst({
where: { title }
})
return calendar as Calendar
}
async deleteCalendar(id: string): Promise<Boolean> {
await prismaClient.calendar.delete({
where: { id }
})
return true
}
}
export { CalendarRepository }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { CreateCalendarUseCase } from './CreateCalendarUseCase';
class CreateCalendarController {
async handle(request: Request, response: Response) {
const {title, information, date} = request.body;
const createCalendarUseCase = container.resolve(CreateCalendarUseCase)
const calendar = await createCalendarUseCase.execute({
title,
information,
date
})
return response.status(200).json(calendar)
}
}
export {CreateCalendarController}
\ No newline at end of file
import { ICalendarsRepository } from '@modules/calendar/repositories/ICalendarsRepository';
import { AppError } from '@shared/error/AppError';
import 'reflect-metadata';
import { inject, injectable } from 'tsyringe';
interface IRequest {
title: string,
information: string,
date: string
}
@injectable()
class CreateCalendarUseCase {
constructor(
@inject('CalendarsRepository')
private calendarsRepository: ICalendarsRepository
) {}
async execute({title, information, date}: IRequest) {
const calendarAlreadyExists = await this.calendarsRepository.findByTitle(title)
if(calendarAlreadyExists) {
throw new AppError('Calendar Already Exists', 400)
}
const calendar = await this.calendarsRepository.create({
title,
information,
date
})
return calendar
}
}
export {CreateCalendarUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { DeleteCalendarUseCase } from './deleteCalendarUseCase';
class deleteCalendarController {
async handle(request: Request, response: Response) {
const {id} = request.params
const deleteCalendarUseCase = container.resolve(DeleteCalendarUseCase)
await deleteCalendarUseCase.execute(id)
return response.status(200).json({ "message": "Deleted" })
}
}
export {deleteCalendarController}
\ No newline at end of file
import { ICalendarsRepository } from "@modules/calendar/repositories/ICalendarsRepository";
import { AppError } from "@shared/error/AppError";
import { inject, injectable } from "tsyringe";
@injectable()
class DeleteCalendarUseCase {
constructor(
@inject('CalendarsRepository')
private calendarsRepository: ICalendarsRepository
) {}
async execute(id: string) {
const calendarAlreadyExists = await this.calendarsRepository.findById(id)
if(!calendarAlreadyExists) {
throw new AppError('Calendar doesnt Exists', 400)
}
await this.calendarsRepository.deleteCalendar(id)
return true
}
}
export {DeleteCalendarUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindManyCalendarUseCase } from './findManyCalendarUseCase';
class FindManyCalendarController {
async handle(request: Request, response: Response) {
const findManyCalendarController = container.resolve(FindManyCalendarUseCase)
const calendars = await findManyCalendarController.execute()
return response.status(200).json(calendars)
}
}
export {FindManyCalendarController}
\ No newline at end of file
import { ICalendarsRepository } from "@modules/calendar/repositories/ICalendarsRepository";
import { inject, injectable } from "tsyringe";
@injectable()
class FindManyCalendarUseCase {
constructor(
@inject('CalendarsRepository')
private calendarsRepository: ICalendarsRepository
) {}
async execute() {
const calendars = await this.calendarsRepository.findAllCalendar()
return calendars
}
}
export {FindManyCalendarUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindOneCalendarUseCase } from './FindOneCalendarUseCase';
class FindOneCalendarController {
async handle(request: Request, response: Response) {
const {id} = request.params;
const findOneCalendarUseCase = container.resolve(FindOneCalendarUseCase)
const calendar = await findOneCalendarUseCase.execute(id)
return response.status(200).json(calendar)
}
}
export {FindOneCalendarController}
\ No newline at end of file
import { ICalendarsRepository } from "@modules/calendar/repositories/ICalendarsRepository";
import { AppError } from "@shared/error/AppError";
import { inject, injectable } from "tsyringe";
@injectable()
class FindOneCalendarUseCase {
constructor(
@inject('CalendarsRepository')
private calendarsRepository: ICalendarsRepository
) {}
async execute(id: string) {
const calendarAlreadyExists = await this.calendarsRepository.findById(id)
if(!calendarAlreadyExists) {
throw new AppError('Calendar doesnt Exists', 400)
}
const calendar = await this.calendarsRepository.findById(id)
return calendar
}
}
export {FindOneCalendarUseCase}
\ No newline at end of file
interface ICreateCurserDTO {
id?: string,
title: string,
information: string,
created_at?: Date;
}
export {ICreateCurserDTO}
\ No newline at end of file
import { Curser } from "@prisma/client";
import { ICreateCurserDTO } from "../dtos/ICreateCurserDTO";
interface ICursersRepository {
create({title, information}: ICreateCurserDTO): Promise<Curser>
findById(id: string): Promise<Curser>
findByTitle(title: string): Promise<Curser>
findAllCursers(): Promise<Curser[]>
deleteCurser(id: string): Promise<Boolean>
}
export {ICursersRepository}
\ No newline at end of file
import { ICreateCurserDTO } from "@modules/curses/dtos/ICreateCurserDTO";
import { Curser } from "@prisma/client";
import { ICursersRepository } from "../ICursersRepository";
import prismaClient from "@shared/infra/prisma";
class CurserRepository implements ICursersRepository {
async create({ title, information }: ICreateCurserDTO): Promise<Curser> {
const curser = await prismaClient.curser.create({
data: {
title,
information
}
})
return curser;
}
async findById(id: string): Promise<Curser> {
const curser = await prismaClient.curser.findUnique({
where: { id }
})
return curser as Curser
}
async findByTitle(title: string): Promise<Curser> {
const curser = await prismaClient.curser.findFirst({
where: { title }
})
return curser as Curser
}
async findAllCursers(): Promise<Curser[]> {
const cursers = await prismaClient.curser.findMany()
return cursers
}
async deleteCurser(id: string): Promise<Boolean> {
await prismaClient.curser.delete({
where: { id }
})
return true
}
}
export { CurserRepository }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { CreateCurserUseCase } from './CreateCurserUseCase';
class CreateCurserController {
async handle(request: Request, response: Response) {
const { title, information } = request.body;
const createCurserUseCase = container.resolve(CreateCurserUseCase)
const curser = await createCurserUseCase.execute({
title,
information
})
return response.status(200).json(curser)
}
}
export { CreateCurserController }
\ No newline at end of file
import { ICursersRepository } from "@modules/curses/repositories/ICursersRepository";
import { AppError } from "@shared/error/AppError";
import { inject, injectable } from "tsyringe";
interface IRequest {
title: string,
information: string,
}
@injectable()
class CreateCurserUseCase {
constructor(
@inject('CursersRepository')
private cursersRepository: ICursersRepository
) {}
async execute({title, information}: IRequest) {
const curserAlreadyExists = await this.cursersRepository.findByTitle(title)
if(curserAlreadyExists) {
throw new AppError('Curser Already Exists', 400)
}
const curser = await this.cursersRepository.create({
title,
information
})
return curser
}
}
export {CreateCurserUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { DeleteCurserUseCase } from './DeleteCurserUseCase';
class DeleteCurserController {
async handle(request: Request, response: Response) {
const { id } = request.params;
const deleteCurserUseCase = container.resolve(DeleteCurserUseCase)
await deleteCurserUseCase.execute(id)
return response.status(200).json({ "message": "Deleted" })
}
}
export { DeleteCurserController }
\ No newline at end of file
import { inject, injectable } from "tsyringe";
import { ICursersRepository } from "@modules/curses/repositories/ICursersRepository";
import { AppError } from "@shared/error/AppError";
@injectable()
class DeleteCurserUseCase {
constructor(
@inject('CursersRepository')
private cursersRepository: ICursersRepository
) {}
async execute(id: string) {
const curserAlreadyExists = await this.cursersRepository.findById(id)
if(!curserAlreadyExists) {
throw new AppError('Curser doesnt Exists', 400)
}
await this.cursersRepository.deleteCurser(id)
return true
}
}
export { DeleteCurserUseCase }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindManyCurserUseCase } from './FindManyCurserUseCase';
class FindManyCurserController {
async handle(request: Request, response: Response) {
const findManyCurserUseCase = container.resolve(FindManyCurserUseCase)
const cursers = await findManyCurserUseCase.execute()
return response.status(200).json(cursers)
}
}
export {FindManyCurserController}
\ No newline at end of file
import { ICursersRepository } from "@modules/curses/repositories/ICursersRepository";
import { injectable, inject } from "tsyringe";
@injectable()
class FindManyCurserUseCase {
constructor(
@inject('CursersRepository')
private cursersRepository: ICursersRepository
) {}
async execute() {
const cursers = await this.cursersRepository.findAllCursers()
return cursers
}
}
export {FindManyCurserUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindOneCurserUseCase } from './FindOneCurserUseCase';
class FindOneCurserController {
async handle(request: Request, response: Response) {
const { id } = request.params;
const findOneCurserUseCase = container.resolve(FindOneCurserUseCase)
const curser = await findOneCurserUseCase.execute(id)
return response.status(200).json(curser)
}
}
export { FindOneCurserController }
\ No newline at end of file
import { ICursersRepository } from "@modules/curses/repositories/ICursersRepository";
import { AppError } from "@shared/error/AppError";
import { inject, injectable } from "tsyringe";
@injectable()
class FindOneCurserUseCase {
constructor(
@inject('CursersRepository')
private cursersRepository: ICursersRepository
) {}
async execute(id: string) {
const curserAlreadyExists = await this.cursersRepository.findById(id)
if(!curserAlreadyExists) {
throw new AppError('Curser Already Exists', 400)
}
const curser = await this.cursersRepository.findById(id)
return curser
}
}
export {FindOneCurserUseCase}
\ No newline at end of file
interface ICreateForumsDTO {
id?: string;
title: string;
description: string,
created_at?: Date;
}
export { ICreateForumsDTO };
import { Forum } from "@prisma/client";
import { ICreateForumsDTO } from "../dtos/ICreateForumDTO";
interface IForumRepository {
create({ title, description }: ICreateForumsDTO): Promise<Forum>
findById(id: string): Promise<Forum>
findByTitle(title: string): Promise<Forum>
deleteForum(id: string): Promise<Boolean>
findAllForuns(): Promise<Forum[]>
}
export { IForumRepository }
\ No newline at end of file
import { ICreateForumsDTO } from "@modules/foruns/dtos/ICreateForumDTO";
import { Forum } from "@prisma/client";
import prismaClient from "@shared/infra/prisma";
import { IForumRepository } from "../IForumRepository";
class ForumRepository implements IForumRepository {
async create({ title, description }: ICreateForumsDTO): Promise<Forum> {
const forum = await prismaClient.forum.create({
data: {
title,
description
}
})
return forum
}
async findById(id: string): Promise<Forum> {
const forum = await prismaClient.forum.findUnique({
where: { id }
})
return forum as Forum
}
async findByTitle(title: string): Promise<Forum> {
const forum = await prismaClient.forum.findFirst({
where: { title }
})
return forum as Forum
}
async deleteForum(id: string): Promise<Boolean> {
await prismaClient.forum.delete({
where: { id }
})
return true
}
async findAllForuns(): Promise<Forum[]> {
const foruns = await prismaClient.forum.findMany()
return foruns
}
}
export { ForumRepository }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { CreateForumUseCase } from './CreateForumUseCase';
class CreateForumController {
async handle(request: Request, response: Response) {
const { title, description } = request.body;
const createForumUseCase = container.resolve(CreateForumUseCase)
const forum = await createForumUseCase.execute({
title,
description
})
return response.status(200).json(forum)
}
}
export { CreateForumController }
\ No newline at end of file
import { IForumRepository } from '@modules/foruns/repositories/IForumRepository';
import { AppError } from '@shared/error/AppError';
import 'reflect-metadata';
import { injectable, inject } from 'tsyringe';
interface IRequest {
title: string,
description: string
}
@injectable()
class CreateForumUseCase {
constructor(
@inject('ForumRepository')
private forunsRepository: IForumRepository
) { }
async execute({ title, description }: IRequest) {
const forumAlreadyExists = await this.forunsRepository.findByTitle(title)
if (forumAlreadyExists) {
throw new AppError('Forum already exists', 404);
}
const forum = await this.forunsRepository.create({
title,
description
})
return forum
}
}
export { CreateForumUseCase }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { DeleteForumUseCase } from './DeleteForumUseCase';
class DeleteForumController {
async handle(request: Request, response: Response) {
const {id} = request.params
const deleteForumUseCase = container.resolve(DeleteForumUseCase)
await deleteForumUseCase.execute(id)
return response.status(200).json({"message": "Deleted"})
}
}
export {DeleteForumController}
\ No newline at end of file
import { IForumRepository } from "@modules/foruns/repositories/IForumRepository";
import { AppError } from "@shared/error/AppError";
import { injectable, inject } from "tsyringe";
@injectable()
class DeleteForumUseCase {
constructor(
@inject('ForumRepository')
private forunsRepository: IForumRepository
) { }
async execute(id: string) {
const forumAlreadyExists = await this.forunsRepository.findById(id)
if (!forumAlreadyExists) {
throw new AppError('Forum doesnt exists', 404);
}
await this.forunsRepository.deleteForum(id)
return true
}
}
export {DeleteForumUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindManyForumUseCase } from './FindManyForumUseCase';
class FindManyForumController {
async handle(request: Request, response: Response) {
const findManyForumUseCase = container.resolve(FindManyForumUseCase)
const foruns = await findManyForumUseCase.execute()
return response.status(200).json(foruns)
}
}
export {FindManyForumController}
\ No newline at end of file
import { IForumRepository } from "@modules/foruns/repositories/IForumRepository";
import { injectable, inject } from "tsyringe";
@injectable()
class FindManyForumUseCase {
constructor(
@inject('ForumRepository')
private forunsRepository: IForumRepository
) { }
async execute() {
const foruns = await this.forunsRepository.findAllForuns()
return foruns
}
}
export {FindManyForumUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindOneForumUseCase } from './FindOneForumUseCase';
class FindOneForumController {
async handle(request: Request, response: Response) {
const {id} = request.params;
const findOneForumUseCase = container.resolve(FindOneForumUseCase)
const forum = await findOneForumUseCase.execute(id)
return response.status(200).json(forum)
}
}
export {FindOneForumController}
\ No newline at end of file
import { IForumRepository } from "@modules/foruns/repositories/IForumRepository";
import { AppError } from "@shared/error/AppError";
import { injectable, inject } from "tsyringe";
@injectable()
class FindOneForumUseCase {
constructor(
@inject('ForumRepository')
private forunsRepository: IForumRepository
) { }
async execute(id: string) {
const forumAlreadyExists = await this.forunsRepository.findById(id)
if (!forumAlreadyExists) {
throw new AppError('Forum already exists', 404);
}
return forumAlreadyExists;
}
}
export {FindOneForumUseCase}
\ No newline at end of file
interface ICreateInstitutionsDTO {
id?: string,
name: string
}
export {ICreateInstitutionsDTO}
\ No newline at end of file
import { Institutions } from "@prisma/client"
import { ICreateInstitutionsDTO } from "../dtos/ICreateInstitutionsDTO"
interface IInstitutionsRepository {
create({name} : ICreateInstitutionsDTO): Promise<Institutions>
findById(id: string): Promise<Institutions>
findByName(name: string): Promise<Institutions>
findAllInstitutions(): Promise<Institutions[]>
deleteInstitutions(id: string): Promise<Boolean>
}
export {IInstitutionsRepository}
\ No newline at end of file
import { ICreateInstitutionsDTO } from "@modules/institutions/dtos/ICreateInstitutionsDTO";
import { Institutions } from "@prisma/client";
import prismaClient from "@shared/infra/prisma";
import { IInstitutionsRepository } from "../IInstitutionsRepository";
class InstitutionsRepository implements IInstitutionsRepository {
async create({ name }: ICreateInstitutionsDTO): Promise<Institutions> {
const institution = await prismaClient.institutions.create({
data: {
name
}
})
return institution;
}
async findById(id: string): Promise<Institutions> {
const institution = await prismaClient.institutions.findUnique({
where: {id}
})
return institution as Institutions
}
async findByName(name: string): Promise<Institutions> {
const institution = await prismaClient.institutions.findFirst({
where: {name}
})
return institution as Institutions
}
async findAllInstitutions(): Promise<Institutions[]> {
const institutions = await prismaClient.institutions.findMany()
return institutions
}
async deleteInstitutions(id: string): Promise<Boolean> {
await prismaClient.institutions.delete({
where: {id}
})
return true;
}
}
export {InstitutionsRepository}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { CreateInstitutionUseCase } from './CreateInstitutionUseCase';
class CreateInstitutionController {
async handle(request: Request, response: Response) {
const { name } = request.body;
const createInstitutionUseCase = container.resolve(CreateInstitutionUseCase)
const institution = await createInstitutionUseCase.execute({
name
})
return response.status(200).json(institution)
}
}
export { CreateInstitutionController }
\ No newline at end of file
import { IInstitutionsRepository } from '@modules/institutions/repositories/IInstitutionsRepository';
import { AppError } from '@shared/error/AppError';
import 'reflect-metadata';
import { inject, injectable } from 'tsyringe';
interface IRequest {
name: string,
}
@injectable()
class CreateInstitutionUseCase {
constructor(
@inject('InstitutionsRepository')
private institutionsRepository: IInstitutionsRepository
) { }
async execute({ name }: IRequest) {
const institutionAlreadyExists = await this.institutionsRepository.findByName(name);
if (institutionAlreadyExists) {
throw new AppError('Institution already exists', 404);
}
const institution = await this.institutionsRepository.create({
name
})
return institution
}
}
export { CreateInstitutionUseCase }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { DeleteInstitutionUseCase } from './DeleteInstitutionUseCase';
class DeleteInstitutionController {
async handle(request: Request, response: Response) {
const {id } = request.params;
const deleteInstitutionUseCase = container.resolve(DeleteInstitutionUseCase)
await deleteInstitutionUseCase.execute(id)
return response.status(200).json({ "message": "Deleted" })
}
}
export {DeleteInstitutionController}
\ No newline at end of file
import { IInstitutionsRepository } from "@modules/institutions/repositories/IInstitutionsRepository";
import { AppError } from "@shared/error/AppError";
import { inject, injectable } from "tsyringe";
@injectable()
class DeleteInstitutionUseCase {
constructor(
@inject('InstitutionsRepository')
private institutionsRepository: IInstitutionsRepository
) { }
async execute(id: string) {
const institutionAlreadyExists = await this.institutionsRepository.findById(id);
if (!institutionAlreadyExists) {
throw new AppError('Institution doesnt exists', 404);
}
await this.institutionsRepository.deleteInstitutions(id)
return true
}
}
export { DeleteInstitutionUseCase }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindManyInstitutionUseCase } from './FindManyInstitutionUseCase';
class FindManyInstitutionController {
async handle(request: Request, response: Response) {
const findManyInstitutionUseCase = container.resolve(FindManyInstitutionUseCase)
const institutions = await findManyInstitutionUseCase.execute()
return response.status(200).json(institutions)
}
}
export { FindManyInstitutionController }
\ No newline at end of file
import { IInstitutionsRepository } from "@modules/institutions/repositories/IInstitutionsRepository";
import { injectable, inject } from "tsyringe";
@injectable()
class FindManyInstitutionUseCase {
constructor(
@inject('InstitutionsRepository')
private institutionsRepository: IInstitutionsRepository
) { }
async execute() {
const institutions = await this.institutionsRepository.findAllInstitutions()
return institutions
}
}
export { FindManyInstitutionUseCase }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindOneInstitutionUseCase } from './findOneInstitutionUseCase';
class FindOneInstitutionController {
async handle(request: Request, response: Response) {
const {id} = request.params
const findOneInstitutionUseCase = container.resolve(FindOneInstitutionUseCase)
const institution = await findOneInstitutionUseCase.execute(id)
return response.status(200).json(institution)
}
}
export {FindOneInstitutionController}
\ No newline at end of file
import { IInstitutionsRepository } from "@modules/institutions/repositories/IInstitutionsRepository";
import { AppError } from "@shared/error/AppError";
import { inject, injectable } from "tsyringe";
@injectable()
class FindOneInstitutionUseCase {
constructor(
@inject('InstitutionsRepository')
private institutionsRepository: IInstitutionsRepository
) { }
async execute(id: string) {
const institution = await this.institutionsRepository.findById(id);
if (!institution) {
throw new AppError('Institution doesnt exists', 404);
}
return institution;
}
}
export { FindOneInstitutionUseCase }
\ No newline at end of file
interface ICreateMessageDTO {
id?: string
message: string
forum_id: string
}
export {ICreateMessageDTO}
\ No newline at end of file
import { ICreateMessageDTO } from "@modules/messages/dtos/ICreateMessageDTO";
import { Message } from "@prisma/client";
interface IMessagesRepository {
create({message, forum_id}: ICreateMessageDTO): Promise<Message>
findById(id: string): Promise<Message | null>
delete(id: string): Promise<void>
findByForum(forum_id: string): Promise<Message[]>
}
export {IMessagesRepository}
\ No newline at end of file
import { ICreateMessageDTO } from "@modules/messages/dtos/ICreateMessageDTO";
import { Message } from "@prisma/client";
import prismaClient from "@shared/infra/prisma";
import { IMessagesRepository } from "../IMessagesRepository";
class MessageRepository implements IMessagesRepository {
async create({ message, forum_id }: ICreateMessageDTO): Promise<Message> {
const messagem = await prismaClient.message.create({
data: {
message,
forum_id
}
})
return messagem
}
async findById(id: string): Promise<Message | null> {
const messagem = await prismaClient.message.findFirst({
where: { id }
})
return messagem as Message
}
async delete(id: string): Promise<void> {
await prismaClient.message.delete({
where: { id }
})
}
async findByForum(forum_id: string): Promise<Message[]> {
const messages = await prismaClient.message.findMany({
where: { forum_id }
})
return messages
}
}
export { MessageRepository }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { CreateMessageUseCase } from './CreateMessageUseCase';
class CreateMessageController {
async handle(request: Request, response: Response) {
const { message, forum_id } = request.body;
const createMessageUseCase = container.resolve(CreateMessageUseCase)
const messagem = await createMessageUseCase.execute({
message,
forum_id
})
return response.status(200).json(messagem)
}
}
export { CreateMessageController }
\ No newline at end of file
import { IMessagesRepository } from '@modules/messages/repositories/IMessagesRepository';
import { AppError } from '@shared/error/AppError';
import 'reflect-metadata';
import { inject, injectable } from 'tsyringe';
interface IRequest {
message: string,
forum_id: string
}
@injectable()
class CreateMessageUseCase {
constructor(
@inject('MessageRepository')
private messagesRepository: IMessagesRepository
) { }
async execute({ message, forum_id }: IRequest) {
const forumDoesntExist = await this.messagesRepository.findByForum(forum_id)
if (!forumDoesntExist) {
throw new AppError('Forum doesnt exists', 404);
}
const messagem = await this.messagesRepository.create({
message,
forum_id
})
return messagem
}
}
export { CreateMessageUseCase }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { DeleteMessageUseCase } from './DeleteMessageUseCase';
class DeleteMessageController {
async handle(request: Request, response: Response) {
const { id } = request.params
const deleteMessageUseCase = container.resolve(DeleteMessageUseCase)
await deleteMessageUseCase.execute(id)
return response.status(200).json({ "message": "Deleted" })
}
}
export { DeleteMessageController }
\ No newline at end of file
import { IMessagesRepository } from "@modules/messages/repositories/IMessagesRepository";
import { AppError } from "@shared/error/AppError";
import { injectable, inject } from "tsyringe";
@injectable()
class DeleteMessageUseCase {
constructor(
@inject('MessageRepository')
private messagesRepository: IMessagesRepository
) { }
async execute(id: string): Promise<void> {
const forumDoesntExist = await this.messagesRepository.findById(id)
if (!forumDoesntExist) {
throw new AppError('Forum doesnt exists', 404);
}
await this.messagesRepository.delete(id)
}
}
export { DeleteMessageUseCase }
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { ListByForumIdUseCase } from './ListByForumIdUseCase';
class ListByForumIdController {
async handle(request: Request, response: Response) {
const{forum_id} = request.params;
const listByForumIdUseCase = container.resolve(ListByForumIdUseCase)
const messages = await listByForumIdUseCase.execute(forum_id)
return response.status(200).json(messages)
}
}
export {ListByForumIdController}
\ No newline at end of file
import { IMessagesRepository } from "@modules/messages/repositories/IMessagesRepository";
import { injectable, inject } from "tsyringe";
@injectable()
class ListByForumIdUseCase {
constructor(
@inject('MessageRepository')
private messagesRepository: IMessagesRepository
) { }
async execute(forum_id: string) {
const messages = await this.messagesRepository.findByForum(forum_id)
return messages
}
}
export {ListByForumIdUseCase}
\ No newline at end of file
interface ICreateUsersDTO {
id?: string;
name: string;
email: string;
password: string;
cpf: string,
curriculo: string,
created_at?: Date;
}
export { ICreateUsersDTO };
interface IUpdateUsersDTO {
id: string;
name?: string;
email?: string;
password?: string;
cpf?: string,
curriculo?: string,
created_at?: Date;
}
export { IUpdateUsersDTO };
import { ICreateUsersDTO } from "../dtos/ICreateUserDTO";
import { User } from '@prisma/client';
import { IUpdateUsersDTO } from "../dtos/IUpdateUserDTO";
interface IUsersRepository {
create({ name, email, password, cpf, curriculo }: ICreateUsersDTO): Promise<User>
findByEmail(email: string): Promise<User>
findAllUser(): Promise<User[]>
deleteUser(id: string): Promise<Boolean>
findById(id: string): Promise<User>
findByCPF(cpf: string): Promise<User>
update({id,name,email,password,cpf,curriculo}: IUpdateUsersDTO): Promise<User>
}
export { IUsersRepository };
\ No newline at end of file
import { ICreateUsersDTO } from "@modules/users/dtos/ICreateUserDTO";
import { IUpdateUsersDTO } from "@modules/users/dtos/IUpdateUserDTO";
import { User } from "@prisma/client";
import prismaClient from "@shared/infra/prisma";
import { IUsersRepository } from "../IUsersRepostory";
class UserRepository implements IUsersRepository {
async create({ name, email, password, cpf, curriculo }: ICreateUsersDTO): Promise<User> {
const user = await prismaClient.user.create({
data: {
name,
email,
password,
cpf,
curriculo
}
})
return user
}
async findByEmail(email: string): Promise<User> {
const user = await prismaClient.user.findUnique({
where: {email}
})
return user as User
}
async findAllUser(): Promise<User[]> {
const users = await prismaClient.user.findMany()
return users;
}
async deleteUser(id: string): Promise<Boolean> {
await prismaClient.user.delete({
where: {id}
})
return true
}
async findById(id: string): Promise<User> {
const user = await prismaClient.user.findUnique({
where: {id}
})
return user as User;
}
async findByCPF(cpf: string): Promise<User> {
const user = await prismaClient.user.findFirst({
where: {cpf}
})
return user as User
}
async update({ id, name, email, password, cpf, curriculo }: IUpdateUsersDTO): Promise<User> {
const user = await prismaClient.user.update({
where: {id},
data: {
name,
email,
password,
cpf,
curriculo
}
})
return user
}
}
export { UserRepository };
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { CreateUserUseCase } from './CreateUserUseCase';
class CreateUserController {
async handle(request: Request, response: Response) {
const { name, email, password, cpf, curriculo } = request.body;
const createUserUseCase = container.resolve(CreateUserUseCase);
const user = await createUserUseCase.execute({
name,
email,
password,
cpf,
curriculo,
});
return response.status(200).json(user);
}
}
export { CreateUserController };
import 'reflect-metadata';
import bcrypt from 'bcryptjs';
import { inject, injectable } from 'tsyringe';
import { IUsersRepository } from '@modules/users/repositories/IUsersRepostory';
import { AppError } from '@shared/error/AppError';
interface IRequest {
name: string,
email: string,
password: string
cpf: string,
curriculo: string
}
@injectable()
class CreateUserUseCase {
constructor(
@inject('UsersRepository')
private usersRepository: IUsersRepository
) { }
async execute({ name, email, password, cpf, curriculo }: IRequest) {
const userAlreadyExists = await this.usersRepository.findByEmail(email);
if (userAlreadyExists) {
throw new AppError('User already exists', 404);
}
const passwordHashed = await bcrypt.hash(password, 10);
const user = await this.usersRepository.create({
name,
email,
password: passwordHashed,
cpf,
curriculo,
});
return user;
}
}
export { CreateUserUseCase };
\ No newline at end of file
import { Request, response, Response } from 'express';
import { container } from 'tsyringe';
import { DeleteUserUseCase } from './deleteUserUseCase';
class DeleteUserController {
async handle(request: Request, response: Response) {
const { id } = request.params;
const deleteUserUseCase = container.resolve(DeleteUserUseCase)
await deleteUserUseCase.execute(id)
return response.status(200).json({ "message": "Deleted" })
}
}
export {DeleteUserController}
\ No newline at end of file
import { IUsersRepository } from "@modules/users/repositories/IUsersRepostory";
import { AppError } from "@shared/error/AppError";
import { inject, injectable } from "tsyringe";
@injectable()
class DeleteUserUseCase {
constructor(
@inject('UsersRepository')
private usersRepository: IUsersRepository
) {}
async execute(id: string) {
const userAlreadyExists = await this.usersRepository.findById(id);
if (!userAlreadyExists) {
throw new AppError('User doesnt exists', 404);
}
await this.usersRepository.deleteUser(id)
return true;
}
}
export {DeleteUserUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindManyUsersUseCase } from './FindManyUsersUseCase';
class FindManyUsersController {
async handle(request: Request, response: Response) {
const findManyUsersUseCase = container.resolve(FindManyUsersUseCase)
const users = await findManyUsersUseCase.execute()
return response.status(200).json(users)
}
}
export {FindManyUsersController}
\ No newline at end of file
import { IUsersRepository } from "@modules/users/repositories/IUsersRepostory";
import { inject, injectable } from "tsyringe";
@injectable()
class FindManyUsersUseCase {
constructor (
@inject('UsersRepository')
private usersRepository: IUsersRepository
) {}
async execute() {
const users = await this.usersRepository.findAllUser()
return users
}
}
export {FindManyUsersUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { FindOneUserUseCase } from './FindOneUserUseCase';
class FindOneUserController {
async handle(request: Request, response: Response) {
const {email} = request.body;
const findOneUserUseCase = container.resolve(FindOneUserUseCase)
const user = await findOneUserUseCase.execute(email)
return response.status(200).json(user)
}
}
export {FindOneUserController}
\ No newline at end of file
import { IUsersRepository } from '@modules/users/repositories/IUsersRepostory';
import { AppError } from '@shared/error/AppError';
import 'reflect-metadata';
import { inject, injectable } from 'tsyringe';
@injectable()
class FindOneUserUseCase {
constructor (
@inject('UsersRepository')
private usersRepository: IUsersRepository
) {}
async execute(email: string) {
const userAlreadyExists = await this.usersRepository.findByEmail(email)
if(!userAlreadyExists) {
throw new AppError('User doesnt Exists', 404);
}
const user = await this.usersRepository.findByEmail(email)
return user
}
}
export {FindOneUserUseCase}
\ No newline at end of file
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import { UpdateUserUseCase } from './UpdateUserUseCase';
class UpdateUserController {
async handle(request: Request, response: Response) {
const { id } = request.params;
const { name, email, password, cpf, curriculo } = request.body;
const updateUserUseCase = container.resolve(UpdateUserUseCase);
const user = await updateUserUseCase.execute({
id,
name,
email,
password,
cpf,
curriculo
});
return response.status(200).json(user);
}
}
export { UpdateUserController };
import 'reflect-metadata';
import bcrypt from 'bcryptjs';
import { IUsersRepository } from '@modules/users/repositories/IUsersRepostory';
import { AppError } from '@shared/error/AppError';
import { inject, injectable } from 'tsyringe';
@injectable()
class UpdateUserUseCase {
constructor(
@inject('UsersRepository')
private usersRepository: IUsersRepository
) { }
async execute({ id, name, email, password, cpf, curriculo }) {
const userDoesntxists = await this.usersRepository.findById(id);
if (!userDoesntxists) {
throw new AppError('User already exists', 404);
}
const passwordHashed = await bcrypt.hash(password, 10);
const user = await this.usersRepository.update({
id,
name,
email,
password: passwordHashed,
cpf,
curriculo
});
}
}
export { UpdateUserUseCase }
\ No newline at end of file
import { ICalendarsRepository } from '@modules/calendar/repositories/ICalendarsRepository';
import { CalendarRepository } from '@modules/calendar/repositories/implementations/CalendarRepository';
import { ICursersRepository } from '@modules/curses/repositories/ICursersRepository';
import { CurserRepository } from '@modules/curses/repositories/implementations/CursersRepository';
import { IForumRepository } from '@modules/foruns/repositories/IForumRepository';
import { ForumRepository } from '@modules/foruns/repositories/implementation/ForumRepository';
import { IInstitutionsRepository } from '@modules/institutions/repositories/IInstitutionsRepository';
import { InstitutionsRepository } from '@modules/institutions/repositories/implementation/InstitutionsRepository';
import { IMessagesRepository } from '@modules/messages/repositories/IMessagesRepository';
import { MessageRepository } from '@modules/messages/repositories/implementation/MessagesRepository';
import { UserRepository } from '@modules/users/repositories/implementations/UsersRepository';
import { IUsersRepository } from '@modules/users/repositories/IUsersRepostory';
import { container } from 'tsyringe';
container.registerSingleton<IUsersRepository>(
'UsersRepository',
UserRepository,
)
container.registerSingleton<ICalendarsRepository>(
'CalendarsRepository',
CalendarRepository,
)
container.registerSingleton<ICursersRepository>(
'CursersRepository',
CurserRepository,
)
container.registerSingleton<IInstitutionsRepository>(
'InstitutionsRepository',
InstitutionsRepository,
)
container.registerSingleton<IForumRepository>(
'ForumRepository',
ForumRepository,
)
container.registerSingleton<IMessagesRepository>(
'MessageRepository',
MessageRepository,
)
\ No newline at end of file
export class AppError {
public readonly message: string;
public readonly statusCode: number;
constructor(message: string, statusCode = 400) {
this.message = message;
this.statusCode = statusCode;
}
}
import 'reflect-metadata';
import 'dotenv/config';
import cors from 'cors';
import 'express-async-errors';
import express, { Application, NextFunction, Request, Response } from 'express';
import { AppError } from '../../error/AppError';
import { router } from './routes';
import '../../container';
const app: Application = express();
app.use(express.json());
app.use(cors());
app.use(router);
app.use((err: Error, request: Request, response: Response, _: NextFunction) => {
if (err instanceof AppError) {
return response.status(err.statusCode).json({
message: err.message,
});
}
return response.status(500).json({
status: 'error',
message: `Internal server error - ${err.message}`,
});
});
export { app };
\ No newline at end of file
import { LoginAuthenticationController } from "@modules/auth/useCases/LoginAuthentication/LoginAuthenticationController";
import { Router } from "express";
const authRoutes = Router();
const loginAuthenticationController = new LoginAuthenticationController();
authRoutes.post('/login', loginAuthenticationController.handle)
export {authRoutes}
\ No newline at end of file
import { CreateCalendarController } from '@modules/calendar/useCases/createCalendar/CreateCalendarController';
import { deleteCalendarController } from '@modules/calendar/useCases/deleteCalendar/deleteCalendarController';
import { FindManyCalendarController } from '@modules/calendar/useCases/findCalendars/findManyCalendarController';
import { FindOneCalendarController } from '@modules/calendar/useCases/findOneCalendar/FindOneCalendarController';
import { Router } from 'express';
const calendarRoutes = Router();
const createCalendarController = new CreateCalendarController()
const findOneCalendarController = new FindOneCalendarController();
const findManyCalendarController = new FindManyCalendarController();
const DeleteCalendarController = new deleteCalendarController()
calendarRoutes.post('/', createCalendarController.handle)
calendarRoutes.get('/all', findManyCalendarController.handle)
calendarRoutes.get('/:id', findOneCalendarController.handle)
calendarRoutes.delete('/:id', DeleteCalendarController.handle)
export { calendarRoutes };
\ No newline at end of file
import { CreateCurserController } from '@modules/curses/useCases/createCurser/CreateCurserController';
import { DeleteCurserController } from '@modules/curses/useCases/deleteCurser/DeleteCurserController';
import { FindManyCurserController } from '@modules/curses/useCases/findAllCursers/FindManyCurserController';
import { FindOneCurserController } from '@modules/curses/useCases/findOneCurser/FindOneCurserController';
import { Router } from 'express';
const cursersRouter = Router();
const createCurserController = new CreateCurserController();
const findManyCurserController = new FindManyCurserController();
const findOneCurserController = new FindOneCurserController();
const deleteCurserController = new DeleteCurserController();
cursersRouter.post('/', createCurserController.handle)
cursersRouter.get('/all', findManyCurserController.handle)
cursersRouter.get('/:id', findOneCurserController.handle)
cursersRouter.delete('/:id', deleteCurserController.handle)
export {cursersRouter}
\ No newline at end of file
import { CreateForumController } from '@modules/foruns/useCases/createForum/CreateForumController';
import { DeleteForumController } from '@modules/foruns/useCases/deleteForum/DeleteForumController';
import { FindManyForumController } from '@modules/foruns/useCases/findAllForum/FindManyForumController';
import { FindOneForumController } from '@modules/foruns/useCases/findOneForum/FindOneForumController';
import { Router } from 'express';
const forunsRouter = Router();
const createForumController = new CreateForumController();
const findOneForumController = new FindOneForumController();
const findManyForumController = new FindManyForumController();
const deleteForumController = new DeleteForumController();
forunsRouter.post('/', createForumController.handle)
forunsRouter.get('/all', findManyForumController.handle)
forunsRouter.get('/:id', findOneForumController.handle)
forunsRouter.delete('/:id', deleteForumController.handle)
export {forunsRouter}
\ No newline at end of file
import { Router } from 'express';
import { authRoutes } from './auth.router';
import { calendarRoutes } from './calendar.router';
import { cursersRouter } from './curser.router';
import { forunsRouter } from './forum.router';
import { institutionRouter } from './institution.router';
import { messagesRouter } from './message.router';
import { userRoutes } from './users.router';
const router = Router();
router.use('/users', userRoutes);
router.use('/calendars', calendarRoutes)
router.use('/cursers', cursersRouter)
router.use('/institutions', institutionRouter)
router.use('/foruns', forunsRouter)
router.use('/messages', messagesRouter)
router.use(authRoutes)
export { router };
\ No newline at end of file
import { CreateInstitutionController } from '@modules/institutions/useCases/createInstitution/CreateInstitutionController';
import { DeleteInstitutionController } from '@modules/institutions/useCases/deleteInstitution/DeleteInstitutionController';
import { FindManyInstitutionController } from '@modules/institutions/useCases/findManyInstitution/FindManyInstitutionController';
import { FindOneInstitutionController } from '@modules/institutions/useCases/findOneInstitution/findOneInstitutionController';
import { Router } from 'express';
const institutionRouter = Router();
const createInstitutionController = new CreateInstitutionController();
const findOneInstitutionController = new FindOneInstitutionController();
const findManyInstitutionController = new FindManyInstitutionController();
const deleteInstitutionController = new DeleteInstitutionController();
institutionRouter.post('/', createInstitutionController.handle)
institutionRouter.get('/all', findManyInstitutionController.handle)
institutionRouter.get('/:id', findOneInstitutionController.handle)
institutionRouter.delete('/:id', deleteInstitutionController.handle)
export {institutionRouter}
\ No newline at end of file
import { CreateMessageController } from '@modules/messages/useCases/createMessage/CreateMessageController';
import { DeleteMessageController } from '@modules/messages/useCases/deleteMessage/DeleteMessageController';
import { ListByForumIdController } from '@modules/messages/useCases/listByForumId/ListByForumIdController';
import { Router } from 'express';
const messagesRouter = Router();
const createMessageController = new CreateMessageController();
const deleteMessageController = new DeleteMessageController();
const listByForumIdController = new ListByForumIdController();
messagesRouter.post('/', createMessageController.handle)
messagesRouter.delete('/:id', deleteMessageController.handle)
messagesRouter.get('/:forum_id', listByForumIdController.handle)
export {messagesRouter}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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