Skip to content

RESTful API project developed with MongoDB and Mongoose in the Back End module at Trybe School

Notifications You must be signed in to change notification settings

ItaloRAmaral/MongoDB-Car-Shop

Repository files navigation

MongoDB Car Shop

📃 Sobre - About

🇧🇷 Portuguese

O projeto consolida muito do que foi aprendido desde o início do módulo de Back End, como utilização de Docker, arquiteturação do código seguindo o modelo MSC e criação de APIs RESTful com CRUD completo. No caso deste projeto, nos aprofundamos ainda mais na utilização de SOLID para boa escrita e manutenabilidade do código, bem como utilização de POO e TypeScript para conferir mais robustez ao projeto. Como desafios, tivemos que criar uma API CRUD de uma concessionária, em que é possível ler, criar, editar e deletar veículos (carros e motos) do banco de dados da concessionária. Este projeto utiliza o banco de dados não relacional MongoDB, e para manipulá-lo fizemos uso da ODM Mongoose.

Também foram desenvolvidos testes com cobertura de 100% do projeto, utilizando as ferramentas Mocha, Chai e Sinon.

🇺🇸 English

The project consolidates much of what was learned since the beginning of the Back End module, such as using Docker, code architecture following the MSC model and creating RESTful APIs with full CRUD. In the case of this project, we delved further into the use of SOLID for good writing and code maintainability, as well as the use of OOP and TypeScript to give the project more robustness. As challenges, we had to create a CRUD API for a dealership, in which it is possible to read, create, edit and delete vehicles (cars and motorcycles) from the dealership database. This project uses the non-relational database MongoDB, and to manipulate it we used ODM Mongoose.

Tests were also developed with 100% coverage of the project, using Mocha, Chai and Sinon tools.

👨‍💻 Habilidades desenvolvidas - Skills developed

🇧🇷 Portuguese
  • MongoDB
  • Utilização do Mongoose (ODM) para trabalhar com o banco de dados MongoDB
  • POO
  • Contrução de uma API CRUD utilizando dos preceitos de SOLID
  • Testes unitários com: Mocha, Chai e Sinon
🇺🇸 English
  • MongoDB
  • Use of Mongoose (ODM) to work with the MongoDB database
  • OOP
  • Construction of a CRUD API using the principles of SOLID
  • Unit tests with: Mocha, Chai and Sinon

🛠️ Ferramentas Utilizadas - Tools Used

  • MongoDB
  • Mongoose.js
  • TypeScript
  • Node.js
  • Express.js
  • Mocha.js
  • Chai.js
  • Sinon.js
  • Docker
  • OPP
  • SOLID

⚙️ Como Executar - How to Run

🇧🇷 Portuguese

É necessario ter o Docker instalado.

  1. Clone o repositório em uma pasta de preferência
git clone git@github.com:ItaloRAmaral/MongoDB-Car-Shop.git
  1. Entre na pasta raíz do projeto, e instale todas as dependências
npm install
  1. Para rodar o projeto é necessario executar o comando abaixo na raiz do projeto. Isso fará com que os containers docker sejam orquestrados e a aplicação esteja disponível. Esse comando deve ser executado via terminal dentro do diretório onde está o arquivo docker-compose.yml.
docker-compose up -d
  1. Para rodar o servidor com o docker, basta acessar o terminal do container car_shop e rodar o comando abaixo e utilizar o insomnia, postman ou algum software de sua preferencia
npm run dev
  1. Para testar o projeto use o seguinte script no terminal do container car_shop
npm run test:coverage
🇺🇸 English

It is necessary to have Docker installed.

  1. Clone the repository in a preferred folder
git clone git@github.com:ItaloRAmaral/MongoDB-Car-Shop.git
  1. Enter the root folder of the project, and install all dependencies
npm install
  1. To run the project you need to run the command below in the root of the project. This will make the docker containers be orchestrated and the application will be available. This command must be executed via terminal inside the directory where the docker-compose.yml file is.
docker-compose up -d 
  1. To run the server with docker, just access the car_shop container terminal and run the command below and use insomnia, postman or any software of your preference
npm run dev
  1. To test the project use the following script in the car_shop container terminal
npm run test:coverage

📚 Documentação (endpoints) - Documentation (endpoints)

🇧🇷 Portuguese

🚗 Cars

Método Funcionalidade URL
POST Realiza o cadastro de um veiculo http://localhost:3001/cars
A estrutura do body da requisição deverá seguir o padrão abaixo:
{
  model: "Ferrari Maranello",
  year: 1963,
  color: "red",
  buyValue: 3500000,
  seatsQty: 2,
  doorsQty: 2
}
A resposta da requisição é a seguinte com status 201
{
   _id: "4edd40c86762e0fb12000003",
  model: "Ferrari Maranello",
  year: 1963,
  color: "red",
  buyValue: 3500000,
  seatsQty: 2,
  doorsQty: 2
}
A requisição irá falhar nos seguintes casos: - A rota retorna erro 400 caso a requisição receba um objeto vazio;
- A rota retorna erro 400 ao tentar criar um carro com quantidade de assentos inferior a 2;
- A rota retorna erro 400 ao tentar criar um carro com quantidade de portas inferior a 2;
- A rota retorna erro 400 ao tentar criar um carro sem `model`, `year`, `color` e `buyValue`;
- A rota retorna erro 400 ao tentar criar um carro sem `doorsQty` e `seatsQty`;
- Não é possível criar um carro se os atributos `model`, `year`, `color`, `buyValue`, `doorsQty` e `seatsQty` estiverem com tipos errados;


Método Funcionalidade URL
GET Retorna uma lista de carros cadastrados http://localhost:3001/cars
A resposta da requisição é a seguinte com status 200
[
  {
    _id: "4edd40c86762e0fb12000003",
    model: "Ferrari Maranello",
    year: 1963,
    color: "red",
    buyValue: 3500000,
    seatsQty: 2,
    doorsQty: 2
  },
  ...
]



Método Funcionalidade URL
GET Retorna um carro atravéz do id http://localhost:3001/cars/:id
A resposta da requisição é a seguinte com status 200
{
   _id: "4edd40c86762e0fb12000003",
  model: "Ferrari Maranello",
  year: 1963,
  color: "red",
  buyValue: 3500000,
  seatsQty: 2,
  doorsQty: 2
}
A requisição irá falhar nos seguintes casos: - É disparado o erro 400 Id must have 24 hexadecimal characters caso o id possua menos que 24 caracteres;
- É disparado o erro 404 Object not found caso o id possua 24 caracteres, mas seja inválido;


Método Funcionalidade URL
PUT Atualizar um carro atravéz do id http://localhost:3001/cars/:id
A resposta da requisição é a seguinte com status 200
{
  _id: "4edd40c86762e0fb12000003",
  model: "Fiat Uno",
  year: 1963,
  color: "blue",
  buyValue: 3500,
  seatsQty: 4,
  doorsQty: 4
}
A requisição irá falhar nos seguintes casos: - É disparado o erro 404 Object not found caso o id possua 24 caracteres, mas seja inválido;
- É disparado o erro 400 Id must have 24 hexadecimal characters caso o id possua menos que 24 caracteres;
- É disparado o erro 400 caso o body esteja vazio;


Método Funcionalidade URL
DELETE Deletar um carro atravéz do id http://localhost:3001/cars/:id
  • A resposta da requisição é 204 e sem body em caso de sucesso
A requisição irá falhar nos seguintes casos: - É disparado o erro 404 Object not found caso o id possua 24 caracteres, mas seja inválido;
- É disparado o erro 400 Id must have 24 hexadecimal characters caso o id possua menos que 24 caracteres;


🛵 Motorcyle

Método Funcionalidade URL
POST Realiza o cadastro de uma moto http://localhost:3001/motorcycles
A estrutura do body da requisição deverá seguir o padrão abaixo:
{
  model: "Honda CG Titan 125",
  year: 1963,
  color: "red",
  buyValue: 3500,
  category: "Street",
  engineCapacity: 125
}
A resposta da requisição é a seguinte com status 201
{
   _id: "4edd40c86762e0fb12000003",
  model: "Honda CG Titan 125",
  year: 1963,
  color: "red",
  buyValue: 3500,
  category: "Street",
  engineCapacity: 125
}
A requisição irá falhar nos seguintes casos: - A rota retorna erro 400 caso a requisição receba um objeto vazio; - A rota retorna erro 400 ao tentar criar uma moto com `category` diferente de `Street`, `Custom` ou `Trail`;
- A rota retorna erro 400 ao tentar criar uma moto com `category` diferente de string;
- A rota retorna erro 400 ao tentar criar uma moto com `engineCapacity` menor ou igual a zero;
- A rota retorna erro 400 ao tentar criar uma moto com `engineCapacity` maior que 2500;
- A rota retorna erro 400 ao tentar criar um moto sem `model`, `year`, `color` e `buyValue`;
- A rota retorna erro 400 ao tentar criar um moto sem `category` e `engineCapacity`;
- Não é possível criar uma moto se os atributos `model`, `year`, `color`, `buyValue`, `category` e `engineCapacity` estiverem com tipos errados;


Método Funcionalidade URL
GET Retorna uma lista de motos cadastradas http://localhost:3001/motorcycles
A resposta da requisição é a seguinte com status 200
[
  {
    _id: "4edd40c86762e0fb12000003",
    model: "Honda CG Titan 125",
    year: 1963,
    color: "red",
    buyValue: 3500,
    category: "Street",
    engineCapacity: 125
  },
  ...
]



Método Funcionalidade URL
GET Retorna uma moto atravéz do id http://localhost:3001/motorcycles/:id
A resposta da requisição é a seguinte com status 200
{
  _id: "4edd40c86762e0fb12000003",
  model: "Honda CG Titan 125",
  year: 1963,
  color: "red",
  buyValue: 3500,
  category: "Street",
  engineCapacity: 125
}
A requisição irá falhar nos seguintes casos: - É disparado o erro 400 Id must have 24 hexadecimal characters caso o id possua menos que 24 caracteres;
- É disparado o erro 404 Object not found caso o id possua 24 caracteres, mas seja inválido;


Método Funcionalidade URL
PUT Atualizar uma moto atravéz do id http://localhost:3001/motorcycles/:id
A resposta da requisição é a seguinte com status 200
{
  _id: "4edd40c86762e0fb12000003",
  model: "Fiat Uno",
  year: 1963,
  color: "blue",
  buyValue: 3500,
  seatsQty: 4,
  doorsQty: 4
}
A requisição irá falhar nos seguintes casos: - É disparado o erro 404 Object not found caso o id possua 24 caracteres, mas seja inválido;
- É disparado o erro 400 Id must have 24 hexadecimal characters caso o id possua menos que 24 caracteres;
- É disparado o erro 400 caso o body esteja vazio;


Método Funcionalidade URL
DELETE Deletar uma moto atravéz do id http://localhost:3001/motorcycles/:id
  • A resposta da requisição é 204 e sem body em caso de sucesso
A requisição irá falhar nos seguintes casos: - É disparado o erro 404 Object not found caso o id possua 24 caracteres, mas seja inválido;
- É disparado o erro 400 Id must have 24 hexadecimal characters caso o id possua menos que 24 caracteres;


🇺🇸 English

🚗 Cars

Method Functionality URL
POST Create a new car http://localhost:3001/cars
The request body is the following:
{
  model: "Fiat Uno",
  year: 1963,
  color: "blue",
  buyValue: 3500,
  seatsQty: 4,
  doorsQty: 4
}
The response is the following with status 201:
{
  _id: "4edd40c86762e0fb12000003",
  model: "Fiat Uno",
  year: 1963,
  color: "blue",
  buyValue: 3500,
  seatsQty: 4,
  doorsQty: 4
}
The request will fail in the following cases: - The route returns error 400 when the request receives an empty object;
- The route returns error 400 when trying to create a car with `seatsQty` less than 2;
- The route returns error 400 when trying to create a car with `doorsQty` less than 2;
- The route returns error 400 when trying to create a car without `model`, `year`, `color` and `buyValue`;
- The route returns error 400 when trying to create a car without `seatsQty` and `doorsQty`;
- The route returns error 400 when trying to create a car with `model`, `year`, `color`, `buyValue`, `seatsQty` and `doorsQty` with wrong types;


Method Functionality URL
GET Returns all cars http://localhost:3001/cars
The response is the following with status 200:
[
  {
    _id: "4edd40c86762e0fb12000003",
    model: "Ferrari Maranello",
    year: 1963,
    color: "red",
    buyValue: 3500000,
    seatsQty: 2,
    doorsQty: 2
  },
  ...
]
Método Funcionalidade URL
GET Returns a car by id http://localhost:3001/cars/:id
The response is the following with status 200:
{
  _id: "4edd40c86762e0fb12000003",
  model: "Fiat Uno",
  year: 1963,
  color: "blue",
  buyValue: 3500,
  seatsQty: 4,
  doorsQty: 4
}
The request will fail in the following cases: - The route returns error 400 when the id has less than 24 characters;
- The route returns error 404 when the id has 24 characters, but is invalid;


Method Functionality URL
PUT Update a car by id http://localhost:3001/cars/:id
The response is the following with status 200:
{
  _id: "4edd40c86762e0fb12000003",
  model: "Fiat Uno",
  year: 1963,
  color: "blue",
  buyValue: 3500,
  seatsQty: 4,
  doorsQty: 4
}
The request will fail in the following cases:
  • The route returns error 404 when the id has 24 characters, but is invalid;
  • The route returns error 400 when the id has less than 24 characters;
  • The route returns error 400 when the request body is empty;


Method Functionality URL
DELETE Delete a car by id http://localhost:3001/cars/:id
  • The response is 204 and without body in case of success
The request will fail in the following cases:
  • The route returns error 404 when the id has 24 characters, but is invalid;
  • The route returns error 400 when the id has less than 24 characters;

🏍️ Motorcycles

Method Functionality URL
POST Create a new motorcycle http://localhost:3001/motorcycles
The request body is the following:
{
  model: "Honda CG 125",
  year: 1980,
  color: "red",
  buyValue: 1500,
  displacement: 125
}
The response is the following with status 201:
{
  _id: "4edd40c86762e0fb12000003",
  model: "Honda CG 125",
  year: 1980,
  color: "red",
  buyValue: 1500,
  displacement: 125
}
The request will fail in the following cases:
  • The route returns error 400 when the request receives an empty object;
  • The route returns error 400 when trying to create a bike with a category other than Street, Custom or Trail;
  • The route returns error 400 when trying to create a motorcycle with category other than string;
  • The route returns error 400 when trying to create a motorcycle with engineCapacity less than or equal to zero;
  • The route returns error 400 when trying to create a motorcycle with engineCapacity greater than 2500;
  • The route returns error 400 when trying to create a moto without category and engineCapacity;
  • The route returns error 400 when trying to create a bike with model, year, color, buyValue, category and engineCapacity with wrong types;


Method Functionality URL
GET Returns all motorcycles http://localhost:3001/motorcycles
The response is the following with status 200:
[
  {
    _id: "4edd40c86762e0fb12000003",
    model: "Honda CG Titan 125",
    year: 1963,
    color: "red",
    buyValue: 3500,
    category: "Street",
    engineCapacity: 125
  },
  ...
]



Method Functionality URL
GET Returns a motorcycle by id http://localhost:3001/motorcycles/:id
The response is the following with status 200:
{
  _id: "4edd40c86762e0fb12000003",
  model: "Honda CG Titan 125",
  year: 1963,
  color: "red",
  buyValue: 3500,
  category: "Street",
  engineCapacity: 125
}
The request will fail in the following cases:
  • The route returns error 400 when the id has less than 24 characters;
  • The route returns error 404 when the id has 24 characters, but is invalid;


Method Functionality URL
PUT Update a motorcycle by id http://localhost:3001/motorcycles/:id
The response is the following with status 200:
{
  _id: "4edd40c86762e0fb12000003",
  model: "Honda CG Titan 125",
  year: 1963,
  color: "red",
  buyValue: 3500,
  category: "Street",
  engineCapacity: 125
}
The request will fail in the following cases:
  • The route returns error 404 when the id has 24 characters, but is invalid;
  • The route returns error 400 when the id has less than 24 characters;
  • The route returns error 400 when the request body is empty;


Method Functionality URL
DELETE Delete a motorcycle by id http://localhost:3001/motorcycles/:id
  • The response is 204 and without body in case of success
The request will fail in the following cases:
  • The route returns error 404 when the id has 24 characters, but is invalid;
  • The route returns error 400 when the id has less than 24 characters;

About

RESTful API project developed with MongoDB and Mongoose in the Back End module at Trybe School

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published