From 2a72213efd1f24ca8784367bdd00c04b774bb715 Mon Sep 17 00:00:00 2001 From: ronald Date: Fri, 13 Aug 2021 18:10:30 -0300 Subject: [PATCH] =?UTF-8?q?Preparando=20revis=C3=A3o=20de=20c=C3=B3digo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- jest.config.js | 5 - ormconfig.js | 16 ---- package.json | 47 ---------- src/app.ts | 46 ---------- src/controllers/pokemonController.ts | 64 ------------- src/controllers/userController.ts | 28 ------ src/database.ts | 18 ---- src/entities/Pokemon.ts | 32 ------- src/entities/Session.ts | 17 ---- src/entities/User.ts | 17 ---- src/entities/UserPokemons.ts | 21 ----- src/joiSchemas/schemas.ts | 14 --- src/middlewares/authMiddleware.ts | 17 ---- .../1628209452187-CreateEntitiesTables.ts | 26 ------ ...13-DeleteIsMyPokemonColumOnPokemonTable.ts | 14 --- src/server.ts | 9 -- src/services/authService.ts | 21 ----- src/services/pokemonService.ts | 61 ------------ src/services/userService.ts | 34 ------- src/setup.ts | 5 - tests/factories/authFactory.ts | 27 ------ tests/factories/pokemonFactory.ts | 45 --------- tests/factories/sessionFactory.ts | 8 -- tests/factories/userFactory.ts | 30 ------ tests/factories/userPokemonsFactory.ts | 19 ---- tests/integration/pokemons.test.ts | 92 ------------------- tests/integration/users.test.ts | 89 ------------------ tests/utils/database.ts | 13 --- tsconfig.json | 9 -- 29 files changed, 844 deletions(-) delete mode 100644 jest.config.js delete mode 100644 ormconfig.js delete mode 100644 package.json delete mode 100644 src/app.ts delete mode 100644 src/controllers/pokemonController.ts delete mode 100644 src/controllers/userController.ts delete mode 100644 src/database.ts delete mode 100644 src/entities/Pokemon.ts delete mode 100644 src/entities/Session.ts delete mode 100644 src/entities/User.ts delete mode 100644 src/entities/UserPokemons.ts delete mode 100644 src/joiSchemas/schemas.ts delete mode 100644 src/middlewares/authMiddleware.ts delete mode 100644 src/migrations/1628209452187-CreateEntitiesTables.ts delete mode 100644 src/migrations/1628272062413-DeleteIsMyPokemonColumOnPokemonTable.ts delete mode 100644 src/server.ts delete mode 100644 src/services/authService.ts delete mode 100644 src/services/pokemonService.ts delete mode 100644 src/services/userService.ts delete mode 100644 src/setup.ts delete mode 100644 tests/factories/authFactory.ts delete mode 100644 tests/factories/pokemonFactory.ts delete mode 100644 tests/factories/sessionFactory.ts delete mode 100644 tests/factories/userFactory.ts delete mode 100644 tests/factories/userPokemonsFactory.ts delete mode 100644 tests/integration/pokemons.test.ts delete mode 100644 tests/integration/users.test.ts delete mode 100644 tests/utils/database.ts delete mode 100644 tsconfig.json diff --git a/jest.config.js b/jest.config.js deleted file mode 100644 index 8af46f3..0000000 --- a/jest.config.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = { - preset: "ts-jest", - testEnvironment: "node", - verbose: true, -}; diff --git a/ormconfig.js b/ormconfig.js deleted file mode 100644 index ecd4ceb..0000000 --- a/ormconfig.js +++ /dev/null @@ -1,16 +0,0 @@ -require("dotenv").config(); - -module.exports = { - type: "postgres", - url: process.env.DATABASE_URL, - migrationsTableName: "migrations", - entities: ["dist/entities/*.js"], - migrations: ["dist/migrations/*.js"], - ssl: { - rejectUnauthorized: false, - }, - cli: { - migrationsDir: "src/migrations", - entitiesDir: "dist/entities/*.js", - }, -}; diff --git a/package.json b/package.json deleted file mode 100644 index e163713..0000000 --- a/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "typescript-back-template", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "NODE_ENV=test JWT_SCRET=test npx jest -i", - "build": "NODE_ENV=production npx tsc --outDir dist && npm run migration:run", - "start": "NODE_ENV=production NODE_TLS_REJECT_UNAUTHORIZED=0 node dist/server.js", - "dev": "NODE_ENV=development npx nodemon --watch \"src/**\" --ext \"ts,json\" --exec \"ts-node src/server.ts\"", - "typeorm": "ts-node ./node_modules/typeorm/cli", - "migration:run": "npm run typeorm -- migration:run" - }, - "keywords": [], - "author": "", - "license": "ISC", - "devDependencies": { - "@types/bcrypt": "^5.0.0", - "@types/cors": "^2.8.12", - "@types/express": "^4.17.13", - "@types/faker": "^5.5.7", - "@types/jest": "^26.0.24", - "@types/jsonwebtoken": "^8.5.4", - "@types/node": "^16.3.3", - "@types/pg": "^8.6.1", - "@types/supertest": "^2.0.11", - "faker": "^5.5.3", - "jest": "^27.0.6", - "nodemon": "^2.0.12", - "supertest": "^6.1.3", - "ts-jest": "^27.0.3", - "ts-node": "^10.1.0", - "typescript": "^4.3.5" - }, - "dependencies": { - "axios": "^0.21.1", - "bcrypt": "^5.0.1", - "cors": "^2.8.5", - "dotenv": "^10.0.0", - "express": "^4.17.1", - "joi": "^17.4.2", - "jsonwebtoken": "^8.5.1", - "pg": "^8.6.0", - "reflect-metadata": "^0.1.13", - "typeorm": "^0.2.34" - } -} diff --git a/src/app.ts b/src/app.ts deleted file mode 100644 index 40a4891..0000000 --- a/src/app.ts +++ /dev/null @@ -1,46 +0,0 @@ -import "./setup"; - -import express from "express"; -import cors from "cors"; -import "reflect-metadata"; -import { Request, Response, NextFunction } from "express"; - -import connectDatabase from "./database"; - -import * as userController from "./controllers/userController"; -import * as pokemonController from "./controllers/pokemonController"; - -import { authMiddleware } from "./middlewares/authMiddleware"; - -const app = express(); -app.use(cors()); -app.use(express.json()); - -app.post("/sign-up", userController.signUp); -app.post("/sign-in", userController.signIn); - -app.get("/pokemons", authMiddleware, pokemonController.getPokemons); - -app.post( - "/my-pokemons/:id/add", - authMiddleware, - pokemonController.alterCatchedPokemonStatus -); -app.post( - "/my-pokemons/:id/remove", - authMiddleware, - pokemonController.alterCatchedPokemonStatus -); - -app.get("/populate", pokemonController.populateDatabase); - -app.use((err: any, req: Request, res: Response, next: NextFunction) => { - console.log(err); - return res.sendStatus(500); -}); - -export async function init() { - await connectDatabase(); -} - -export default app; diff --git a/src/controllers/pokemonController.ts b/src/controllers/pokemonController.ts deleted file mode 100644 index 7d7e6e5..0000000 --- a/src/controllers/pokemonController.ts +++ /dev/null @@ -1,64 +0,0 @@ -import axios from "axios"; -import { Request, Response } from "express"; -import { getRepository } from "typeorm"; -import Pokemon from "../entities/Pokemon"; - -import * as pokemonService from "../services/pokemonService"; - -export async function getPokemons(req: Request, res: Response) { - const userId = res.locals["user"]; - const pokemons = await pokemonService.getPokemons(userId); - return res.send(pokemons); -} - -export async function alterCatchedPokemonStatus(req: Request, res: Response) { - const userId = res.locals["user"]; - const { id } = req.params; - const addOrRemove = req.path.replace(`/my-pokemons/${id}/`, ""); - - await pokemonService.alterCatchedPokemonStatus( - userId, - parseInt(id), - addOrRemove - ); - - return res.sendStatus(200); -} - -export async function populateDatabase(req: Request, res: Response) { - console.log("Entrou"); - for (let i = 1; i <= 898; i++) { - const result = await axios.get( - `https://pokeapi.co/api/v2/pokemon/${i}` - ); - const newPokemon = { - name: result.data.name, - number: result.data.id, - image: result.data.sprites.front_default, - weight: result.data.weight, - height: result.data.height, - baseExp: result.data.base_experience, - description: "", - }; - const speciesResult = await axios.get( - `https://pokeapi.co/api/v2/pokemon-species/${i}` - ); - for ( - let j = 0; - j < speciesResult.data.flavor_text_entries.length; - j++ - ) { - if ( - speciesResult.data.flavor_text_entries[j].language.name === "en" - ) { - newPokemon.description = speciesResult.data.flavor_text_entries[ - j - ].flavor_text - .split("\n") - .join(" "); - } - } - await getRepository(Pokemon).insert(newPokemon); - } - res.send("OK"); -} diff --git a/src/controllers/userController.ts b/src/controllers/userController.ts deleted file mode 100644 index 6864add..0000000 --- a/src/controllers/userController.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Request, Response } from "express"; -import { signUpSchema, signInSchema } from "../joiSchemas/schemas"; - -import * as userService from "../services/userService"; - -export async function signUp(req: Request, res: Response) { - const validation = signUpSchema.validate(req.body); - if (validation.error) return res.sendStatus(400); - - const { email, password } = req.body as { email: string; password: string }; - const result = await userService.signUp(email, password); - const status = result ? 201 : 409; - res.sendStatus(status); -} - -export async function signIn(req: Request, res: Response) { - const validation = signInSchema.validate(req.body); - if (validation.error) return res.sendStatus(400); - - const { email, password } = req.body as { email: string; password: string }; - const token = await userService.signIn(email, password); - - if (token) { - res.send({ token }); - } else { - res.sendStatus(401); - } -} diff --git a/src/database.ts b/src/database.ts deleted file mode 100644 index dccd630..0000000 --- a/src/database.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { getConnectionManager } from "typeorm"; - -if (process.env.NODE_ENV === 'production' && process.env.DATABASE_URL.indexOf("sslmode=require") === -1) { - process.env.DATABASE_URL += "?sslmode=require"; -} - -export default async function connect () { - const connectionManager = await getConnectionManager(); - const connection = connectionManager.create({ - name: "default", - type: "postgres", - url: process.env.DATABASE_URL, - entities: [`${process.env.NODE_ENV === 'production' ? 'dist' : 'src'}/entities/*.*`], - ssl: process.env.NODE_ENV === 'production' - }); - await connection.connect(); - return connection; -} diff --git a/src/entities/Pokemon.ts b/src/entities/Pokemon.ts deleted file mode 100644 index 0995f09..0000000 --- a/src/entities/Pokemon.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"; -import UserPokemons from "./UserPokemons"; - -@Entity("pokemons") -export default class Pokemon { - @PrimaryGeneratedColumn() - id: number; - - @Column() - name: string; - - @Column() - number: number; - - @Column() - image: string; - - @Column() - weight: number; - - @Column() - height: number; - - @Column() - baseExp: number; - - @Column() - description: string; - - @OneToMany(() => UserPokemons, (userPokemons) => userPokemons.pokemon) - userPokemons: UserPokemons[]; -} diff --git a/src/entities/Session.ts b/src/entities/Session.ts deleted file mode 100644 index 1b42fa2..0000000 --- a/src/entities/Session.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"; -import User from "./User"; - -@Entity("sessions") -export default class Session { - @PrimaryGeneratedColumn() - id: number; - - @Column() - userId: number; - - @Column() - token: string; - - @ManyToOne(() => User) - user: User; -} diff --git a/src/entities/User.ts b/src/entities/User.ts deleted file mode 100644 index 79bc0f0..0000000 --- a/src/entities/User.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"; -import UserPokemons from "./UserPokemons"; - -@Entity("users") -export default class User { - @PrimaryGeneratedColumn() - id: number; - - @Column() - email: string; - - @Column() - password: string; - - @OneToMany(() => UserPokemons, (userPokemons) => userPokemons.user) - userPokemons: UserPokemons[]; -} diff --git a/src/entities/UserPokemons.ts b/src/entities/UserPokemons.ts deleted file mode 100644 index 4f17a8e..0000000 --- a/src/entities/UserPokemons.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"; -import Pokemon from "./Pokemon"; -import User from "./User"; - -@Entity("userPokemons") -export default class UserPokemons { - @PrimaryGeneratedColumn() - id: number; - - @Column() - userId: number; - - @Column() - pokemonId: number; - - @ManyToOne(() => User, (user) => user.userPokemons) - user: User; - - @ManyToOne(() => Pokemon, (pokemon) => pokemon.userPokemons) - pokemon: Pokemon; -} diff --git a/src/joiSchemas/schemas.ts b/src/joiSchemas/schemas.ts deleted file mode 100644 index 86a41e8..0000000 --- a/src/joiSchemas/schemas.ts +++ /dev/null @@ -1,14 +0,0 @@ -import joi from "joi"; - -const signUpSchema = joi.object({ - email: joi.string().email().required(), - password: joi.string().required(), - confirmPassword: joi.any().equal(joi.ref("password")).required(), -}); - -const signInSchema = joi.object({ - email: joi.string().email().required(), - password: joi.string().required(), -}); - -export { signUpSchema, signInSchema }; diff --git a/src/middlewares/authMiddleware.ts b/src/middlewares/authMiddleware.ts deleted file mode 100644 index 6c6a327..0000000 --- a/src/middlewares/authMiddleware.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Request, Response, NextFunction } from "express"; - -import * as authService from "../services/authService"; - -export async function authMiddleware( - req: Request, - res: Response, - next: NextFunction -) { - const header = req.header(`Authorization`); - const token = header.split(`Bearer `)[1]; - const user = await authService.authenticate(token); - if (!user) return res.sendStatus(401); - - res.locals.user = user.id; - next(); -} diff --git a/src/migrations/1628209452187-CreateEntitiesTables.ts b/src/migrations/1628209452187-CreateEntitiesTables.ts deleted file mode 100644 index f0b09fe..0000000 --- a/src/migrations/1628209452187-CreateEntitiesTables.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class CreateEntitiesTables1628209452187 implements MigrationInterface { - name = 'CreateEntitiesTables1628209452187' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`CREATE TABLE "users" ("id" SERIAL NOT NULL, "email" character varying NOT NULL, "password" character varying NOT NULL, CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "userPokemons" ("id" SERIAL NOT NULL, "userId" integer NOT NULL, "pokemonId" integer NOT NULL, CONSTRAINT "PK_e3dfc348f178e7a8c17b68734bd" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "pokemons" ("id" SERIAL NOT NULL, "name" character varying NOT NULL, "number" integer NOT NULL, "image" character varying NOT NULL, "weight" integer NOT NULL, "height" integer NOT NULL, "baseExp" integer NOT NULL, "description" character varying NOT NULL, "inMyPokemons" boolean NOT NULL, CONSTRAINT "PK_a3172290413af616d9cfa1fdc9a" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "sessions" ("id" SERIAL NOT NULL, "userId" integer NOT NULL, "token" character varying NOT NULL, CONSTRAINT "PK_3238ef96f18b355b671619111bc" PRIMARY KEY ("id"))`); - await queryRunner.query(`ALTER TABLE "userPokemons" ADD CONSTRAINT "FK_adba93fee6560e93ff084514b89" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "userPokemons" ADD CONSTRAINT "FK_7df3d612d515a0c8dd416337493" FOREIGN KEY ("pokemonId") REFERENCES "pokemons"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "sessions" ADD CONSTRAINT "FK_57de40bc620f456c7311aa3a1e6" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "sessions" DROP CONSTRAINT "FK_57de40bc620f456c7311aa3a1e6"`); - await queryRunner.query(`ALTER TABLE "userPokemons" DROP CONSTRAINT "FK_7df3d612d515a0c8dd416337493"`); - await queryRunner.query(`ALTER TABLE "userPokemons" DROP CONSTRAINT "FK_adba93fee6560e93ff084514b89"`); - await queryRunner.query(`DROP TABLE "sessions"`); - await queryRunner.query(`DROP TABLE "pokemons"`); - await queryRunner.query(`DROP TABLE "userPokemons"`); - await queryRunner.query(`DROP TABLE "users"`); - } - -} diff --git a/src/migrations/1628272062413-DeleteIsMyPokemonColumOnPokemonTable.ts b/src/migrations/1628272062413-DeleteIsMyPokemonColumOnPokemonTable.ts deleted file mode 100644 index cd35f2d..0000000 --- a/src/migrations/1628272062413-DeleteIsMyPokemonColumOnPokemonTable.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class DeleteIsMyPokemonColumOnPokemonTable1628272062413 implements MigrationInterface { - name = 'DeleteIsMyPokemonColumOnPokemonTable1628272062413' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "pokemons" DROP COLUMN "inMyPokemons"`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "pokemons" ADD "inMyPokemons" boolean NOT NULL`); - } - -} diff --git a/src/server.ts b/src/server.ts deleted file mode 100644 index fb00813..0000000 --- a/src/server.ts +++ /dev/null @@ -1,9 +0,0 @@ -import app, { init } from "./app"; - -const port = +process.env.PORT || 4000; - -init().then(() => { - app.listen(port, () => { - console.log(`Server is listening on port ${port}.`); - }); -}); diff --git a/src/services/authService.ts b/src/services/authService.ts deleted file mode 100644 index 9e67ecf..0000000 --- a/src/services/authService.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { getRepository } from "typeorm"; -import jwt from "jsonwebtoken"; - -import Session from "../entities/Session"; - -export async function authenticate(token: string) { - const sessionRepository = getRepository(Session); - const secretKey = process.env.JWT_SCRET; - const data = jwt.verify(token, secretKey) as { user: number }; - - const session = await sessionRepository.findOne({ - where: { - userId: data.user, - token, - }, - relations: ["user"], - }); - if (!session) return null; - - return session.user; -} diff --git a/src/services/pokemonService.ts b/src/services/pokemonService.ts deleted file mode 100644 index cd277fa..0000000 --- a/src/services/pokemonService.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { getRepository } from "typeorm"; -import Pokemon from "../entities/Pokemon"; -import User from "../entities/User"; -import UserPokemons from "../entities/UserPokemons"; - -interface UserPokemonsIds { - [key: number]: boolean; -} - -interface PokemonWithNewAttribute { - id: number; - name: string; - number: number; - image: string; - weight: number; - height: number; - baseExp: number; - description: string; - inMyPokemons: boolean; -} - -export async function getPokemons(userId: number) { - const userRepository = getRepository(User); - const pokemonsRepository = getRepository(Pokemon); - - const user = await userRepository.find({ - where: { id: userId }, - relations: ["userPokemons"], - }); - - const pokemonsObj: UserPokemonsIds = {}; - user[0].userPokemons.forEach((pokemon) => { - pokemonsObj[pokemon.pokemonId] = true; - }); - - const pokemons = await pokemonsRepository.find(); - - const pokemonsWithNewAttribute: Array = - pokemons.map((pokemon) => { - return { - ...pokemon, - inMyPokemons: pokemonsObj[pokemon.id] ? true : false, - }; - }); - - return pokemonsWithNewAttribute; -} - -export async function alterCatchedPokemonStatus( - userId: number, - pokemonId: number, - addOrRemove: string -) { - const repository = getRepository(UserPokemons); - - if (addOrRemove === "add") { - await repository.insert({ userId, pokemonId }); - } else { - await repository.delete({ userId, pokemonId }); - } -} diff --git a/src/services/userService.ts b/src/services/userService.ts deleted file mode 100644 index 42d55d5..0000000 --- a/src/services/userService.ts +++ /dev/null @@ -1,34 +0,0 @@ -import bcrypt from "bcrypt"; -import jwt from "jsonwebtoken"; -import { getRepository } from "typeorm"; - -import User from "../entities/User"; -import Session from "../entities/Session"; - -export async function signUp(email: string, password: string) { - const repository = getRepository(User); - - const user = await repository.findOne({ where: { email } }); - if (user) return false; - - const encrypted = bcrypt.hashSync(password, 12); - await repository.insert({ email, password: encrypted }); - return true; -} - -export async function signIn(email: string, password: string): Promise { - const userRepository = getRepository(User); - - const user = await userRepository.findOne({ where: { email } }); - if (!user || !bcrypt.compareSync(password, user.password)) return null; - - const data = { user: user.id }; - const secretKey = process.env.JWT_SCRET; - const configs = { expiresIn: 60 * 60 * 24 * 30 }; - const token = jwt.sign(data, secretKey, configs); - - const sessionRepository = getRepository(Session); - await sessionRepository.insert({ userId: user.id, token }); - - return token; -} diff --git a/src/setup.ts b/src/setup.ts deleted file mode 100644 index 474e167..0000000 --- a/src/setup.ts +++ /dev/null @@ -1,5 +0,0 @@ -import dotenv from "dotenv"; - -const path = process.env.NODE_ENV === "test" ? ".env.test" : ".env"; - -dotenv.config({ path }); diff --git a/tests/factories/authFactory.ts b/tests/factories/authFactory.ts deleted file mode 100644 index 0eeccf4..0000000 --- a/tests/factories/authFactory.ts +++ /dev/null @@ -1,27 +0,0 @@ -import jwt from "jsonwebtoken"; - -import { userBody, createUser } from "../factories/userFactory"; -import { createSession } from "./sessionFactory"; - -export async function getUnsavedToken() { - const body = userBody(); - const user = await createUser(body); - - const data = { user: user.id }; - const secretKey = process.env.JWT_SCRET; - const configs = { expiresIn: 60 * 60 * 24 * 30 }; - return jwt.sign(data, secretKey, configs); -} - -export async function getValidToken() { - const body = userBody(); - const user = await createUser(body); - - const data = { user: user.id }; - const secretKey = process.env.JWT_SCRET; - const configs = { expiresIn: 60 * 60 * 24 * 30 }; - const token = jwt.sign(data, secretKey, configs); - await createSession(data.user, token); - - return { token, userId: user.id }; -} diff --git a/tests/factories/pokemonFactory.ts b/tests/factories/pokemonFactory.ts deleted file mode 100644 index 3b11b76..0000000 --- a/tests/factories/pokemonFactory.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { getRepository } from "typeorm"; -import faker from "faker"; - -import Pokemon from "../../src/entities/Pokemon"; - -interface PokemonParams { - name: string; - number: number; - image: string; - weight: number; - height: number; - baseExp: number; - description: string; -} - -export function pokemonBody() { - const body = { - name: faker.name.findName(), - number: faker.datatype.number(), - image: faker.internet.url(), - weight: faker.datatype.number(), - height: faker.datatype.number(), - baseExp: faker.datatype.number(), - description: faker.lorem.paragraph(), - }; - return body; -} - -export async function createPokemon(body: PokemonParams) { - const repository = getRepository(Pokemon); - - const pokemon = await repository.create({ ...body }); - - const result = await repository.save(pokemon); - - return result; -} - -export async function createManyPokemons(qtd: number) { - const createdPokemons = []; - for (let i = 0; i < qtd; i++) { - createdPokemons.push((await createPokemon(pokemonBody())).id); - } - return createdPokemons; -} diff --git a/tests/factories/sessionFactory.ts b/tests/factories/sessionFactory.ts deleted file mode 100644 index d5abc5b..0000000 --- a/tests/factories/sessionFactory.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { getRepository } from "typeorm"; - -import Session from "../../src/entities/Session"; - -export async function createSession(userId: number, token: string) { - const sessionRepository = getRepository(Session); - await sessionRepository.insert({ userId, token }); -} diff --git a/tests/factories/userFactory.ts b/tests/factories/userFactory.ts deleted file mode 100644 index 024557e..0000000 --- a/tests/factories/userFactory.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { getRepository } from "typeorm"; -import faker from "faker"; -import bcrypt from "bcrypt"; - -import User from "../../src/entities/User"; - -interface BodyParams { - email: string; - password: string; -} - -export function userBody() { - const body = { - email: faker.internet.email(), - password: faker.internet.password(), - }; - return body; -} - -export async function createUser(body: BodyParams) { - const repository = getRepository(User); - - const encrypted = bcrypt.hashSync(body.password, 12); - - const user = await repository.create({ ...body, password: encrypted }); - - const result = await repository.save(user); - - return result; -} diff --git a/tests/factories/userPokemonsFactory.ts b/tests/factories/userPokemonsFactory.ts deleted file mode 100644 index 322049c..0000000 --- a/tests/factories/userPokemonsFactory.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { getRepository } from "typeorm"; - -import UserPokemons from "../../src/entities/UserPokemons"; - -export async function catchPokemon(userId: number, pokemonId: number) { - const repository = getRepository(UserPokemons); - - const userPokemons = await repository.create({ userId, pokemonId }); - - const result = await repository.save(userPokemons); - - return result; -} - -export async function catchManyPokemon(userId: number, pokemonsIds: number[]) { - pokemonsIds.forEach(async (pokemon) => { - await catchPokemon(userId, pokemon); - }); -} diff --git a/tests/integration/pokemons.test.ts b/tests/integration/pokemons.test.ts deleted file mode 100644 index 365d95a..0000000 --- a/tests/integration/pokemons.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import supertest from "supertest"; -import { getConnection } from "typeorm"; - -import app, { init } from "../../src/app"; -import { getUnsavedToken, getValidToken } from "../factories/authFactory"; -import { - createManyPokemons, - createPokemon, - pokemonBody, -} from "../factories/pokemonFactory"; -import { catchManyPokemon } from "../factories/userPokemonsFactory"; - -import { clearDatabase } from "../utils/database"; - -beforeAll(async () => { - await init(); -}); - -beforeEach(async () => { - await clearDatabase(); -}); - -afterAll(async () => { - await getConnection().close(); -}); - -describe("GET /pokemons", () => { - it("should answer with status 200 for valid token", async () => { - const tokenAndId = await getValidToken(); - const allPokemonsId = await createManyPokemons(4); - const pokemonsToCatch = [allPokemonsId[0], allPokemonsId[3]]; - await catchManyPokemon(tokenAndId.userId, pokemonsToCatch); - - const response = await supertest(app) - .get("/pokemons") - .set("Authorization", `Bearer ${tokenAndId.token}`); - expect(response.status).toBe(200); - }); - - it("should answer with status 401 for invalid token", async () => { - const token = await getUnsavedToken(); - - const response = await supertest(app) - .get("/pokemons") - .set("Authorization", `Bearer ${token}`); - expect(response.status).toBe(401); - }); -}); - -describe("POST /my-pokemons/:id/add", () => { - it("should answer with status 200 for success on adding pokemon", async () => { - const tokenAndId = await getValidToken(); - const pokemon = await createPokemon(pokemonBody()); - - const response = await supertest(app) - .post(`/my-pokemons/${pokemon.id}/add`) - .set("Authorization", `Bearer ${tokenAndId.token}`); - expect(response.status).toBe(200); - }); - - it("should answer with status 401 for invalid token", async () => { - const token = await getUnsavedToken(); - const pokemon = await createPokemon(pokemonBody()); - - const response = await supertest(app) - .post(`/my-pokemons/${pokemon.id}/add`) - .set("Authorization", `Bearer ${token}`); - expect(response.status).toBe(401); - }); -}); - -describe("POST /my-pokemons/:id/remove", () => { - it("should answer with status 200 for success on removing pokemon", async () => { - const tokenAndId = await getValidToken(); - const pokemon = await createPokemon(pokemonBody()); - - const response = await supertest(app) - .post(`/my-pokemons/${pokemon.id}/remove`) - .set("Authorization", `Bearer ${tokenAndId.token}`); - expect(response.status).toBe(200); - }); - - it("should answer with status 401 for invalid token", async () => { - const token = await getUnsavedToken(); - const pokemon = await createPokemon(pokemonBody()); - - const response = await supertest(app) - .post(`/my-pokemons/${pokemon.id}/remove`) - .set("Authorization", `Bearer ${token}`); - expect(response.status).toBe(401); - }); -}); diff --git a/tests/integration/users.test.ts b/tests/integration/users.test.ts deleted file mode 100644 index 3bf740e..0000000 --- a/tests/integration/users.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import supertest from "supertest"; -import { getConnection } from "typeorm"; - -import app, { init } from "../../src/app"; -import { userBody, createUser } from "../factories/userFactory"; -import { clearDatabase } from "../utils/database"; - -beforeAll(async () => { - await init(); -}); - -beforeEach(async () => { - await clearDatabase(); -}); - -afterAll(async () => { - await getConnection().close(); -}); - -describe("POST /sign-up", () => { - it("should answer with status 201 for valid params", async () => { - const params = userBody(); - const body = { ...params, confirmPassword: params.password }; - - const response = await supertest(app).post("/sign-up").send(body); - expect(response.status).toBe(201); - }); - - it("should answer with status 409 for email conflict", async () => { - const params = userBody(); - const body = { ...params, confirmPassword: params.password }; - await createUser(params); - - const response = await supertest(app).post("/sign-up").send(body); - expect(response.status).toBe(409); - }); - - it("should answer with status 400 for difference between params password and confirmPassword", async () => { - const params = userBody(); - const body = { ...params, confirmPassword: "whatever" }; - - const response = await supertest(app).post("/sign-up").send(body); - expect(response.status).toBe(400); - }); - - it("should answer with status 400 for wrong format of email param", async () => { - const params = userBody(); - const body = { ...params, email: "whatever" }; - - const response = await supertest(app).post("/sign-up").send(body); - expect(response.status).toBe(400); - }); -}); - -describe("POST /sign-in", () => { - it("should answer with status 200 for valid params", async () => { - const body = userBody(); - await createUser(body); - - const response = await supertest(app).post("/sign-in").send(body); - expect(response.status).toBe(200); - }); - - it("should answer with status 400 for wrong format of email param", async () => { - const body = userBody(); - body.email = "whatever"; - - const response = await supertest(app).post("/sign-in").send(body); - expect(response.status).toBe(400); - }); - - it("should answer with status 401 for wrong email param", async () => { - const body = userBody(); - await createUser(body); - body.email = "whatever@whatever.com"; - - const response = await supertest(app).post("/sign-in").send(body); - expect(response.status).toBe(401); - }); - - it("should answer with status 401 for wrong password param", async () => { - const body = userBody(); - const result = await createUser(body); - body.password = "whatever"; - - const response = await supertest(app).post("/sign-in").send(body); - expect(response.status).toBe(401); - }); -}); diff --git a/tests/utils/database.ts b/tests/utils/database.ts deleted file mode 100644 index 88f78a4..0000000 --- a/tests/utils/database.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { getRepository } from "typeorm"; - -import Session from "../../src/entities/Session"; -import UserPokemons from "../../src/entities/UserPokemons"; -import Pokemon from "../../src/entities/Pokemon"; -import User from "../../src/entities/User"; - -export async function clearDatabase() { - await getRepository(Session).delete({}); - await getRepository(UserPokemons).delete({}); - await getRepository(Pokemon).delete({}); - await getRepository(User).delete({}); -} diff --git a/tsconfig.json b/tsconfig.json deleted file mode 100644 index d2b0bda..0000000 --- a/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "compilerOptions": { - "noImplicitAny": true, - "esModuleInterop": true, - "emitDecoratorMetadata": true, - "experimentalDecorators": true - }, - "exclude": ["node_modules", "tests"] -}