Skip to content

Commit 97005bf

Browse files
committed
finalizando aplicação
1 parent 29248a5 commit 97005bf

File tree

8 files changed

+5478
-78
lines changed

8 files changed

+5478
-78
lines changed

package.json

+18-12
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,42 @@
11
{
2-
"name": "NPS",
2+
"name": "nps-api",
33
"version": "1.0.0",
44
"main": "index.js",
55
"license": "MIT",
66
"scripts": {
7+
"heroku-postbuild": "ts-node-dev node_modules/typeorm/cli.js migration:run",
8+
"start": "ts-node src/server.ts",
79
"dev": "ts-node-dev --transpile-only --ignore-watch node_modules src/server.ts",
10+
"startTestDB": "ts-node-dev --transpile-only --ignore-watch node_modules src/database/index.ts",
811
"typeorm": "ts-node-dev node_modules/typeorm/cli.js",
9-
"test": "set NODE_ENV=test jest",
10-
"posttest": "rm ./src/database/database.test.sqlite"
12+
"test": "set NODE_ENV=test&&jest -i"
1113
},
14+
"heroku-run-build-script": true,
1215
"dependencies": {
13-
"-": "^0.0.1",
14-
"@types/jest": "^26.0.20",
15-
"D": "^1.0.0",
16+
"@types/node": "^14.14.31",
17+
"cors": "^2.8.5",
1618
"express": "^4.17.1",
19+
"express-async-errors": "^3.1.1",
1720
"handlebars": "^4.7.7",
18-
"jest": "^26.6.3",
19-
"nodemailer": "^6.5.0",
21+
"nodemailer": "^6.4.18",
2022
"reflect-metadata": "^0.1.13",
2123
"sqlite3": "^5.0.2",
24+
"swagger-ui-express": "^4.1.6",
25+
"ts-node": "^9.1.1",
2226
"typeorm": "^0.2.31",
2327
"uuid": "^8.3.2",
2428
"yup": "^0.32.9"
2529
},
2630
"devDependencies": {
2731
"@types/express": "^4.17.11",
28-
"@types/nodemailer": "^6.4.1",
32+
"@types/jest": "^26.0.20",
33+
"@types/nodemailer": "^6.4.0",
2934
"@types/supertest": "^2.0.10",
3035
"@types/uuid": "^8.3.0",
36+
"jest": "^26.6.3",
3137
"supertest": "^6.1.3",
32-
"ts-jest": "^26.5.3",
33-
"ts-node-dev": "^1.1.6",
34-
"typescript": "^4.2.2"
38+
"ts-jest": "^26.5.2",
39+
"ts-node-dev": "^1.1.1",
40+
"typescript": "^4.1.5"
3541
}
3642
}

src/__tests__/Survey.test.ts

+50-17
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,60 @@
11
import request from 'supertest';
2+
import { Connection, getConnection } from 'typeorm';
23
import { app } from '../app';
34

4-
import createConnection from '../database'
5+
import createConnection from '../database';
56

6-
describe("Surveys", ()=>{
7-
beforeAll(async()=>{
8-
const connetcion= await createConnection();
9-
await connetcion.runMigrations();
7+
8+
describe("Surveys", () => {
9+
10+
11+
beforeAll(async () => {
12+
const connection = await createConnection();
13+
await connection.runMigrations();
14+
});
15+
16+
17+
afterAll(async () => {
18+
const connection = getConnection();
19+
await connection.dropDatabase();
20+
await connection.close();
1021
});
11-
it("should be able to create a new survey", async()=>{
12-
const response = await request(app).post("/surveys").send({
13-
title:"Title Example",
14-
description:"Description Example",
22+
23+
it("Should be able to create a new survey", async () => {
24+
25+
const response = await request(app).post("/surveys")
26+
.send({
27+
title: "Title Example1",
28+
description: "Description Example1",
1529
});
16-
expect(response.status).toBe(201);
17-
expect(response.body).toHaveProperty("id");
30+
31+
32+
expect(response.status).toBe(201);
33+
34+
1835
});
19-
it("should be able to get all surveys",async()=>{
20-
await request(app).post("/surveys").send({
21-
title:"Title Example2",
22-
description:"Description Example2",
36+
37+
it("Should be able to create a new survey", async () => {
38+
39+
const response = await request(app).post("/surveys")
40+
.send({
41+
title: "Title Example2",
42+
description: "Description Example2",
2343
});
24-
const response=await request(app).get ("/surveys");
25-
expect (response.body.length).toBe(2);
44+
45+
46+
expect(response.status).toBe(201);
47+
48+
49+
expect(response.body).toHaveProperty("id");
2650
});
51+
52+
it("Should be able get all surveys", async () => {
53+
54+
const response = await request(app).get("/surveys");
55+
56+
57+
expect(response.body.length).toBe(2);
58+
});
59+
2760
});

src/__tests__/User.test.ts

+36-15
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,47 @@
11
import request from 'supertest';
2+
import { getConnection } from 'typeorm';
23
import { app } from '../app';
34

4-
import createConnection from '../database'
5+
import createConnection from '../database';
56

6-
describe("Users", ()=>{
7-
beforeAll(async()=>{
8-
const connetcion= await createConnection();
9-
await connetcion.runMigrations();
7+
8+
describe("Users", () => {
9+
10+
11+
beforeAll(async () => {
12+
const connection = await createConnection();
13+
await connection.runMigrations();
1014
});
11-
it("should be able to create a new user", async()=>{
12-
const response = await request(app).post("/users").send({
13-
email:"user@example.com",
14-
name:"User Example"
15+
16+
// Para excluir o banco de dados fake
17+
afterAll(async () => {
18+
const connection = getConnection();
19+
await connection.dropDatabase();
20+
await connection.close();
21+
});
22+
23+
it("Should be able to create a new user", async () => {
24+
25+
const response = await request(app).post("/users")
26+
.send({
27+
email: "user@example.com",
28+
name: "User Example",
1529
});
30+
31+
1632
expect(response.status).toBe(201);
17-
})
18-
it("should not to be able to create a user with exists emal",async()=>{
19-
const response = await request(app).post("/users").send({
20-
email:"user@example.com",
21-
name:"User Example"
33+
});
34+
35+
it("Should not be able to create a user with exists email", async () => {
36+
37+
const response = await request(app).post("/users")
38+
.send({
39+
email: "user@example.com",
40+
name: "User Example",
2241
});
42+
43+
2344
expect(response.status).toBe(400);
45+
});
2446

25-
})
2647
});

src/app.ts

+31-8
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,34 @@
1-
import "reflect-metadata";
2-
import express from "express";
3-
import "./database"
4-
import { router } from "./routes";
51

2+
import 'reflect-metadata'
3+
import express, { Request, Response, NextFunction } from 'express';
4+
import "express-async-errors";
5+
import createConnection from './database'
6+
import { router } from './routes';
7+
import { AppError } from './errors/AppError';
68

7-
const app= express();
8-
app.use(express.json());
9-
app.use(router);
109

11-
export{app};
10+
createConnection();
11+
const app = express();
12+
13+
14+
15+
app.use(express.json());
16+
app.use(router);
17+
18+
19+
20+
app.use((err: Error, request: Request, response: Response, _next: NextFunction) => {
21+
22+
if(err instanceof AppError) {
23+
return response.status(err.statusCode).json({
24+
message: err.message
25+
})
26+
}
27+
28+
return response.status(500).json({
29+
status: "Error",
30+
message: 'Internal server error ${err.message}',
31+
})
32+
});
33+
34+
export { app };

src/controllers/SurveysController.ts

+9-9
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,31 @@ import {SurveyRepository} from "../repositories/SurveysRepository";
55
class SurveyController{
66

77
async create(request: Request, response: Response) {
8-
// Desestruturação pois sabe que aqui está recebendo apenas o nome e email do JSON requisitado
9-
const { title, description } = request.body; // Controller recebe o título e descrição do body da requisição HTTP
8+
9+
const { title, description } = request.body;
1010

11-
// Para receber as funções necessárias
11+
1212
const surveysRepository = getCustomRepository(SurveyRepository);
1313

14-
// Criar o survey passando o que foi recebido
14+
1515
const survey = surveysRepository.create({
1616
title,
1717
description
1818
})
1919

20-
// Salvar o survey no banco de dados
20+
2121
await surveysRepository.save(survey);
2222

23-
// 201 é o código para informar quando se cria algo corretamente no HTTP
24-
return response.status(201).json(survey); // Retorna o código e o que foi criado
23+
24+
return response.status(201).json(survey);
2525

2626
}
2727

28-
// Controller para criar a rota que retorna todas as pesquisas (surveys)
28+
2929
async show(request: Request, response: Response){
3030
const surveysRepository = getCustomRepository(SurveyRepository);
3131

32-
const all = await surveysRepository.find(); // .find() é o método para listar todos os registros da tabela
32+
const all = await surveysRepository.find();
3333

3434
return response.json(all);
3535
}

src/controllers/UserController.ts

+6-15
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,23 @@
1-
import { Request, Response } from 'express'; // Express para as requisições e respostas
1+
import { Request, Response } from 'express';
22
import { getCustomRepository, UpdateDateColumn } from 'typeorm';
3-
import { UsersRepository } from '../repositories/UsersRepository'; // Aqui onde está os comandos de acesso o banco de dados por meio do TypeORM de User
3+
import { UsersRepository } from '../repositories/UsersRepository';
44
import * as yup from 'yup';
55
import { AppError } from '../errors/AppError';
66
class UserController {
77

88
async create(request: Request, response: Response) {
9-
// Desestruturação pois sabe que aqui está recebendo apenas o nome e email do JSON requisitado
9+
1010
const { name, email } = request.body;
1111

12-
// Obrigatório apra cadastrar usuário
12+
1313
const scheme = yup.object().shape({
1414
name: yup.string().required("Nome é obrigatório!"),
1515
email: yup.string().email("Email inválido!").required("Email é obrigatório")
1616
})
1717

18-
// Primeira forma de validar:
19-
// Valindo o objeto, se não for válido:
20-
// if( !(await scheme.isValid(request.body)) ) {
21-
// return response.status(400).json (
22-
// {error: "Validation Failed!"}
23-
// );
24-
// }
25-
26-
// Segunda forma de validar
27-
// Com try catch tratando:
18+
2819
try {
29-
await scheme.validate(request.body, {abortEarly: false}); // AbortEarly para fazer todas as validações
20+
await scheme.validate(request.body, {abortEarly: false});
3021
} catch (err) {
3122
throw new AppError(err);
3223
}

src/repositories/UsersRepository.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ import { Entity, EntityRepository, Repository } from "typeorm";
22
import { User } from "../models/User";
33

44
@EntityRepository(User)
5-
class UserRepository extends Repository<User>{
5+
class UsersRepository extends Repository<User>{
66

77
}
88

9-
export {UserRepository};
9+
export {UsersRepository};

0 commit comments

Comments
 (0)