Skip to content
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
67 changes: 11 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,19 @@
Teste para desenvolvedor do Estadão
==============================
# Teste para desenvolvedor do Estadão

Olá candidato,
Olá Recrutador,

Esse teste consiste em 2 etapas para avaliarmos seu conhecimento em PHP e Front-End (HTML5, CSS e JavaScript)
- O teste foi relizado em Node js com typescript Mongobd

Para realizar o teste, você deve dar um fork neste repositório e depois clona-lo na pasta <document_root> da máquina que está realizando o teste.
Poderia ser Feito em PHP ! porem eu possuo conhecimentos mais solidos em Javascript por isso optei fazer nessa stack

Crie um branch com seu nome, e quando finalizar todo o desenvolvimento, você deverá enviar um pull-request com sua versão.
## Backend

O teste
--------
- acessar a pasta Backend e rodar o comando `yarn` para instalar as depedencias
- Depois de instalado `yarn dev` o servidor express ira rodar na pasta 8888\

### Back-End/PHP
## Front end

A primeira etapa será o desenvolvimento **backend/PHP**:
- acessar a pasta Frontend e rodar o comando `yarn` para instalar as depedencias
- Depois de instalado `yarn dev` o servidor ira rodar na pasta 3000 - http://localhost:3000

**Descrição:**

- Você deverá desenvolver uma 'mini api' para que seja possível realizar operações CRUD do objeto Carro.
> **Obs:**
> - Você pode usar arquivo (txt, json) como banco de dados.
> - Cada carro deve ter ID, Marca, Modelo, Ano.

Sugerimos o retorno dessa 'mini api' nas seguinte urls:

- `/carros` - [GET] deve retornar todos os carros cadastrados.
- `/carros` - [POST] deve cadastrar um novo carro.
- `/carros/{id}`[GET] deve retornar o carro com ID especificado.
- `/carros/{id}`[PUT] deve atualizar os dados do carro com ID especificado.
- `/carros/{id}`[DELETE] deve apagar o carro com ID especificado.

### Front-End

Para a segunda etapa do teste, você deverá desenvolver uma SPA (Single Page Application) e nela deve ser possível:

- Ver a lista de carros cadastrados
- Criar um novo carro
- Editar um carro existente
- Apagar um carro existente

> **Obs:**
> - A página deve ser responsiva.
> - A página deve funcionar 100% via AJAX, sem outros carregamentos de páginas.
> - Ao criar/editar um carro, o campo "marca" deverá ser um `SELECT`

### Ambiente

Esse teste com um ambiente Docker funcional, ou seja, basta rodar os comandos para subir o container da aplicação e acessar a URL do projeto no navegador.

Para rodar o ambiente, é necessário ter o Docker Compose instalado, e rodar o seguinte comando:
> docker-compose up -d nginx

Após o ambiente subir, basta acessar a URL abaixo e começar a desenvolver:
> http://localhost:8080

### Observações importantes:
- O teste só será considerado se rodar através do Docker.
- Caso seja necessário, você pode alterar **qualquer** configuração do Docker. Atente-se apenas para que o ambiente não precise de nenhuma configuração adicional.
- Você não deve se prender aos arquivos do repositório. Fique a vontade para criar outros.
- Você pode usar frameworks, tanto para o front-end, quanto para o back-end, mas um código limpo será melhor avaliado.
- Você pode usar ferramentas de automação (Grunt, Gulp), mas deverá informar o uso completo para funcionamento do teste.
- Será considerado ponto positivo no teste a utilização de JS puro, orientação a objetos, design patterns e rotinas para testes.
qualqer dúvida estou a disposição
3 changes: 3 additions & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mongourl=''

port=8888
24 changes: 24 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "ts-node-dev --inspect --transpile-only --ignore-watch node_modules src/server.ts",
"build": "tsc"
},
"devDependencies": {
"@types/cors": "^2.8.9",
"@types/express": "^4.17.11",
"@types/mongoose": "^5.10.3",
"cors": "^2.8.5",
"tsc": "^1.20150623.0",
"typescript": "^4.1.3"
},
"dependencies": {
"@types/node": "^14.14.25",
"express": "^4.17.1",
"mongoose": "^5.11.15",
"ts-node-dev": "^1.1.1"
}
}
57 changes: 57 additions & 0 deletions backend/src/controllers/CarController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@

import { error } from 'console'
import { Request, Response } from 'express'

import CarSchema from '../models/CarModel'


export default class CarController {



public async index(req: Request, res: Response) {
const car = await CarSchema.find()
return res.json(car);
}

public async show(req: Request, res: Response) {
const car = await CarSchema.findById(req.params._id);
return res.json(car);
}


public async create(req: Request, res: Response) {
const { marca, modelo, ano } = req.body
const car = await CarSchema.create({
marca,
modelo,
ano
})
return res.json(car)
}

public async update(req: Request, res: Response) {
try {
const car = await CarSchema.findByIdAndUpdate(req.params._id, req.body, {
new: true
});
return res.json([{
"message": "Carro editado com sucesso"
}, car]);
} catch (error) {
return res.json({ error: 'houve algum errro' })
}
}

public async destroy(req: Request, res: Response) {
try {
await CarSchema.findByIdAndDelete(req.params._id);
return res.json({
"message": "Carro Deletado com sucesso"
});
} catch (error) {
return res.json({ error: 'houve algum errro' })
}
}

}
28 changes: 28 additions & 0 deletions backend/src/controllers/MarcaController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

import { error } from 'console'
import { Request, Response } from 'express'

import MarcaSchema from '../models/MarcaModel'


export default class MarcaController {



public async index(req: Request, res: Response) {
const marca = await MarcaSchema.find()
return res.json(marca);
}

public async create(req: Request, res: Response) {
const { marca } = req.body
const brand = await MarcaSchema.create({
marca,

})
return res.json(brand)
}



}
16 changes: 16 additions & 0 deletions backend/src/models/CarModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import mongoose from 'mongoose'





const CarSchema = new mongoose.Schema({
marca: { type: String, required: true },
modelo: { type: String, required: true },
ano: { type: String, required: true },
createdAt: { type: Date, default: Date.now }

})


export default mongoose.model('Car', CarSchema);
11 changes: 11 additions & 0 deletions backend/src/models/MarcaModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import mongoose from 'mongoose'


const MarcaSchema = new mongoose.Schema({
marca: { type: String, required: true },
createdAt: { type: Date, default: Date.now }

})


export default mongoose.model('Marca', MarcaSchema);
29 changes: 29 additions & 0 deletions backend/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import Router from 'express'
import CarController from '../controllers/CarController';
import MarcaController from '../controllers/MarcaController';


const route = Router();

const carController = new CarController
const marcaController = new MarcaController


route.get('/carros/', carController.index)

route.get('/carros/:_id', carController.show)

route.post('/carros', carController.create)

route.put('/carros/:_id', carController.update)

route.delete('/carros/:_id', carController.destroy)


//marca

route.post('/marcas', marcaController.create)

route.get('/marcas', marcaController.index)

export default route
32 changes: 32 additions & 0 deletions backend/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import express from 'express'
import cors from 'cors'
import dotenv from 'dotenv'
import routes from './routes'
dotenv.config()


import mongoose from 'mongoose'

const mongourl = process.env.mongourl

mongoose.connect(`${mongourl}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})


const app = express();

app.use(cors());

app.use(express.json())

app.use(routes)

app.listen(process.env.port)




67 changes: 67 additions & 0 deletions backend/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist/", /* Redirect output structure to the directory. */
//"rootDir": "./src/", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
"isolatedModules": false, /* /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
"resolveJsonModule": true,
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
// "include": [
// "./src/config/*.json"
// ],
}
Loading