Skip to content
This repository was archived by the owner on Nov 22, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
PORT=8080
HOST_NAME=http://localhost
USER_MONGO_ATLAS=boticario
PASSWORD_MONGO_ATLAS=boticario123
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,5 @@ typings/

# DynamoDB Local files
.dynamodb/

package-lock.json
106 changes: 106 additions & 0 deletions Product - Boticario.postman_collection.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
{
"info": {
"_postman_id": "b17672af-8b36-48c9-9f95-2cc79df9a93d",
"name": "Product - Boticario",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Create Product",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\r\n \"sku\": 43264,\r\n \"name\": \"L'Oréal Professionnel Expert Absolut Repair Cortex Lipidium - Máscara de Reconstrução 500g\",\r\n \"inventory\": {\r\n \"warehouses\": [\r\n {\r\n \"locality\": \"SP\",\r\n \"quantity\": 22,\r\n \"type\": \"ECOMMERCE\"\r\n },\r\n {\r\n \"locality\": \"MOEMA\",\r\n \"quantity\": 18,\r\n \"type\": \"PHYSICAL_STORE\"\r\n }\r\n ]\r\n }\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://localhost:8080/products",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"products"
]
}
},
"response": []
},
{
"name": "Get Product",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8080/products/43264",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"products",
"43264"
]
}
},
"response": []
},
{
"name": "Update Product",
"request": {
"method": "PUT",
"header": [],
"body": {
"mode": "raw",
"raw": "{\r\n \"name\": \"L'Oréal Professionnel Expert Absolut Repair Cortex Lipidium - Máscara de Reconstrução 500g\",\r\n \"inventory\": {\r\n \"warehouses\": [\r\n {\r\n \"locality\": \"SP\",\r\n \"quantity\": 26,\r\n \"type\": \"ECOMMERCE\"\r\n },\r\n {\r\n \"locality\": \"PR\",\r\n \"quantity\": 24,\r\n \"type\": \"PHYSICAL_STORE\"\r\n }\r\n ]\r\n }\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://localhost:8080/products/43264",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"products",
"43264"
]
}
},
"response": []
},
{
"name": "Delete Product",
"request": {
"method": "DELETE",
"header": [],
"url": {
"raw": "http://localhost:8080/products/43264",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"products",
"43264"
]
}
},
"response": []
}
]
}
82 changes: 37 additions & 45 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,74 +1,66 @@
### Backend Test
[![Build Status](https://travis-ci.org/belezanaweb/test-nodejs.svg?branch=master)](https://travis-ci.org/belezanaweb/test-nodejs)
### test-nodejs Boticario

Esta é uma avaliação básica de código.
## Requirements
- Node (v18.16.0)
- NPM (v9.5.1) or yarn (v1.22.19)

O objetivo é conhecer um pouco do seu conhecimento/prática de RESTful e NodeJS.
## Install dependencies
```sh
$ npm i
```
## Running project
```sh
$ npm run start:dev
```

Recomendamos que você não gaste mais do que 4 - 6 horas.
## Running tests
```sh
$ npm run test
```

Faça um fork deste repositório.
## Documentation

Ao finalizar o teste, submeta um pull request para o repositório que nosso time será notificado.
- Apos rodar o projeto acesse o link `http://localhost:8080/api`

### Tarefas
## UseCases
- Create Product
- Get Product
- Update Product
- Delete Product

Com a seguinte representação de produto:

```json
{
"sku": 43264,
"name": "L'Oréal Professionnel Expert Absolut Repair Cortex Lipidium - Máscara de Reconstrução 500g",
"inventory": {
"quantity": 15,
"warehouses": [
{
"locality": "SP",
"quantity": 12,
"type": "ECOMMERCE"
},
{
"locality": "MOEMA",
"quantity": 3,
"type": "PHYSICAL_STORE"
}
]
},
"isMarketable": true
}
```
### Observations

- Realizei a deleção para deleção logica (Soft-Delete)
- Foi disponibilizado na raiz do projeto uma collection do postman de produtos `Product - Boticario.postman_collection.json`

### Tarefas

Crie endpoints para as seguintes ações:

- [ ] Criação de produto onde o payload será o json informado acima (exceto as propriedades **isMarketable** e **inventory.quantity**)
- [x] Criação de produto onde o payload será o json informado acima (exceto as propriedades **isMarketable** e **inventory.quantity**)

- [ ] Edição de produto por **sku**
- [x] Edição de produto por **sku**

- [ ] Recuperação de produto por **sku**
- [x] Recuperação de produto por **sku**

- [ ] Deleção de produto por **sku**
- [x] Deleção de produto por **sku**

### Requisitos


- [ ] Toda vez que um produto for recuperado por **sku** deverá ser calculado a propriedade: **inventory.quantity**
- [x] Toda vez que um produto for recuperado por **sku** deverá ser calculado a propriedade: **inventory.quantity**

A propriedade inventory.quantity é a soma da quantity dos warehouses

- [ ] Toda vez que um produto for recuperado por **sku** deverá ser calculado a propriedade: **isMarketable**
- [x] Toda vez que um produto for recuperado por **sku** deverá ser calculado a propriedade: **isMarketable**

Um produto é marketable sempre que seu inventory.quantity for maior que 0

- [ ] Caso um produto já existente em memória tente ser criado com o mesmo **sku** uma exceção deverá ser lançada
- [x] Caso um produto já existente em memória tente ser criado com o mesmo **sku** uma exceção deverá ser lançada

Dois produtos são considerados iguais se os seus skus forem iguais


- [ ] Ao atualizar um produto, o antigo deve ser sobrescrito com o que esta sendo enviado na requisição
- [x] Ao atualizar um produto, o antigo deve ser sobrescrito com o que esta sendo enviado na requisição

A requisição deve receber o sku e atualizar com o produto que tbm esta vindo na requisição

### Dicas

- Os produtos podem ficar em memória, não é necessário persistir os dados
- Testes são sempre bem-vindos :smiley:
5 changes: 5 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};
2 changes: 2 additions & 0 deletions jest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import 'reflect-metadata'
jest.setTimeout(30000)
25 changes: 23 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"start:dev": "tsnd --respawn --transpile-only --clear src/server.ts",
"test": "jest",
"test:watch": "jest --watch"
},
"repository": {
"type": "git",
Expand All @@ -16,5 +18,24 @@
"bugs": {
"url": "https://github.com/belezanaweb/test-nodejs/issues"
},
"homepage": "https://github.com/belezanaweb/test-nodejs#readme"
"homepage": "https://github.com/belezanaweb/test-nodejs#readme",
"devDependencies": {
"@jest/globals": "^29.5.0",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.1",
"@types/node": "^18.15.12",
"jest": "^29.5.0",
"reflect-metadata": "^0.1.13",
"ts-jest": "^29.1.0",
"ts-node-dev": "^2.0.0",
"typescript": "^4.9.5"
},
"dependencies": {
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-async-errors": "^3.1.1",
"mongoose": "^7.0.4",
"swagger-ui-express": "^4.6.2",
"tsyringe": "^4.7.0"
}
}
30 changes: 30 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import "reflect-metadata";
import express, { Request, Response, NextFunction } from "express";
import "express-async-errors"
import router from "./routes";
import swaggerUi from 'swagger-ui-express';
import swaggerDocs from './swagger.json';
import { AppError } from "./shared/excepetions/errors";
import '../src/shared/container'

const app = express();

app.use(express.json());
app.use(router);
app.use("/api", swaggerUi.serve, swaggerUi.setup(swaggerDocs));
app.use(
(err: Error, request: Request, response: Response, next: 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 };
31 changes: 31 additions & 0 deletions src/domain/entities/products/Product.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { describe, it, expect, beforeAll } from "@jest/globals"
import { IProduct } from "./Product"
import { Inventory } from "./interface/Inventory"
import { Warehouses } from "./interface/Warehouses"

describe('Product', () => {
let product: IProduct
let inventory: Inventory
let warehouses: Array<Warehouses>

beforeAll(() => {
warehouses = [{
locality: "Florianopolis",
quantity: 15,
type: "PHYSICAL_STORE"
}, {
locality: "PR",
quantity: 51,
type: "PHYSICAL_STORE"
}]
inventory = { warehouses: warehouses }
product = new IProduct({ sku: 10231, name: 'Zaad', inventory: inventory})
})

it('should be able create a new product', () => {
expect(product).toBeInstanceOf(IProduct)
expect(product.sku).toEqual(10231)
expect(product.name).toEqual('Zaad')
expect(product.inventory).toEqual(inventory)
})
})
20 changes: 20 additions & 0 deletions src/domain/entities/products/Product.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Inventory } from "./interface/Inventory"

export class IProduct {
constructor({
sku,
name,
inventory,
}: { sku: number, name: string, inventory: Inventory}) {
this.sku = sku
this.name = name
this.inventory = inventory
this.isDeleted = false
}

public sku: number
public name: string
public inventory: Inventory
public isMarketable?: boolean
public isDeleted?: boolean
}
6 changes: 6 additions & 0 deletions src/domain/entities/products/interface/Inventory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Warehouses } from "./Warehouses"

export interface Inventory {
quantity?: number
warehouses: Warehouses[]
}
5 changes: 5 additions & 0 deletions src/domain/entities/products/interface/Warehouses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface Warehouses {
locality: string
quantity: number
type: string
}
12 changes: 12 additions & 0 deletions src/domain/repositories/IProducts.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { IProduct } from "../entities/products/Product"
import { ICreateProductDTO } from "../../modules/products/dtos/ICreateProductDTO"
import { IUpdateProductDTO } from "../../modules/products/dtos/IUpdateProductDTO"

interface IProductsRepository {
create(product: ICreateProductDTO): Promise<IProduct>
getProduct(sku: number): Promise<IProduct | null>
update(sku: number, data: IUpdateProductDTO): Promise<IProduct | null>
delete(sku: number, data: IProduct): Promise<IProduct>
}

export { IProductsRepository }
Loading