Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Desafio Maycon Douglas #22

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,15 @@ Serão considerados diferenciais:
- Conhecimento sólido em Expo ou React Native;
- Boas práticas de escrita de código (código limpo, padrões de arquitetura, etc.);
- Conhecimento em infraestruturas em nuvem;


# Passo a passo - Como inicializar a aplicação Frontend
- Primeiramente, rode o comando npm install para instalar as dependências;
- Após isso, rode npm run dev para inicializar o app.

# Passo a passo - Como inicializar a aplicação Backend
- Rode o comando npm install;
- Rode o comando npm run dev para startar o servidor na porta 9901.

## NOTA:
- Para que a aplicação funcione corretamente, visto que a API não está em nenhum servidor, deve-se rodar as duas backend e frontend juntos para obter os dados e fazer as devidas operações localmente.
1 change: 1 addition & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MONGO_URI=mongodb+srv://dbUserAdmin:teste123@apicluster.jvgqq.mongodb.net/?retryWrites=true&w=majority
1 change: 1 addition & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
4,408 changes: 4,408 additions & 0 deletions backend/package-lock.json

Large diffs are not rendered by default.

27 changes: 27 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "tsx watch src/server.ts"
},
"keywords": [],
"author": "Maycon Douglas",
"license": "ISC",
"dependencies": {
"@fastify/cors": "^8.2.0",
"@prisma/client": "^4.9.0",
"dotenv": "^16.0.3",
"fastify": "^4.11.0",
"mongoose": "^6.8.4",
"zod": "^3.20.2"
},
"devDependencies": {
"@types/node": "^18.11.18",
"tsc": "^2.0.4",
"tsx": "^3.12.2",
"typescript": "^4.9.4"
}
}
129 changes: 129 additions & 0 deletions backend/src/controllers/CarController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import Car from "../models/Car";
import { z } from "zod";

interface ICarController {
create(request: any, reply: any): Promise<void>;
getAll(request: any, reply: any): Promise<void>;
get(request: any, reply: any): Promise<void>;
update(request: any, reply: any): Promise<void>;
delete(request: any, reply: any): Promise<void>;
deleteAll(request: any, reply: any): Promise<void>;
}

export default class CarController implements ICarController {
async create(request: any, reply: any) {
const createCarBody = z.object({
name: z.string(),
brand: z.string(),
year: z.number(),
owner: z.object({
name: z.string(),
email: z.string(),
tel: z.string(),
}),
});
const { name, brand, year, owner } = createCarBody.parse(request.body);

try {
const car = await Car.create({
name,
brand,
year,
owner,
});
reply.status(201).send(car);
} catch (error: any) {
reply.status(500).send({ error: error.message });
}
}

async getAll(request: any, reply: any) {
try {
const cars = await Car.find();
reply.status(200).send(cars);
} catch (error: any) {
reply.status(500).send({ error: error.message });
}
}

async get(request: any, reply: any) {
const getCarParams = z.object({
id: z.string(),
});
const { id } = getCarParams.parse(request.params);

try {
const car = await Car.findById(id);
if (!car) {
reply.status(404).send({ error: "Car not found" });
}
reply.status(200).send(car);
} catch (error: any) {
reply.status(500).send({ error: error.message });
}
}

async update(request: any, reply: any) {
const updateCarParams = z.object({
id: z.string(),
});
const { id } = updateCarParams.parse(request.params);

const updateCarBody = z.object({
name: z.string(),
brand: z.string(),
year: z.number(),
owner: z.object({
name: z.string(),
email: z.string(),
tel: z.string(),
}),
});
const { name, brand, year, owner } = updateCarBody.parse(request.body);

try {
const car = await Car.findByIdAndUpdate(
id,
{
name,
brand,
year,
owner,
},
{ new: true }
);
if (!car) {
reply.status(404).send({ error: "Car not found" });
}
reply.status(200).send(car);
} catch (error: any) {
reply.status(500).send({ error: error.message });
}
}

async delete(request: any, reply: any) {
const deleteCarParams = z.object({
id: z.string(),
});
const { id } = deleteCarParams.parse(request.params);

try {
const car = await Car.findByIdAndDelete(id);
if (!car) {
reply.status(404).send({ error: "Car not found" });
}
reply.status(200).send(car);
} catch (error: any) {
reply.status(500).send({ error: error.message });
}
}

async deleteAll(request: any, reply: any) {
try {
const cars = await Car.deleteMany({});
reply.status(200).send(cars);
} catch (error: any) {
reply.status(500).send({ error: error.message });
}
}
}
21 changes: 21 additions & 0 deletions backend/src/database/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import mongoose from "mongoose";

mongoose.set('strictQuery', false);

/*
* Conexão com o banco de dados para fins de teste
*/
const MONGO_URI =
"mongodb+srv://dbUserAdmin:teste123@apicluster.jvgqq.mongodb.net/?retryWrites=true&w=majority";

const connectDB: () => Promise<void> = async () => {
try {
const conn = await mongoose.connect(MONGO_URI);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error: any) {
console.error(`Error: ${error.message}`);
process.exit(1);
}
};

export default connectDB;
55 changes: 55 additions & 0 deletions backend/src/models/Car.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import mongoose from "mongoose";

interface ICar {
name: string;
brand: string;
year: number;
owner: {
name: string;
email: string;
tel: string;
};
}

const CarSchema = new mongoose.Schema<ICar>(
{
name: {
type: String,
required: true,
default: "",
},
brand: {
type: String,
required: true,
default: "",
},
year: {
type: Number,
required: true,
},
owner: {
type: Object,
required: true,
name: {
type: String,
required: true,
default: "",
},
email: {
type: String,
required: true,
default: "",
},
tel: {
type: String,
required: true,
default: "",
},
},
},
{
timestamps: true,
}
);

export default mongoose.model("Car", CarSchema);
13 changes: 13 additions & 0 deletions backend/src/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { FastifyInstance } from "fastify";
import CarController from "./controllers/CarController";

const Car = new CarController();

export async function appRoutes(app: FastifyInstance) {
app.get("/cars", Car.getAll);
app.get("/cars/:id", Car.get);
app.post("/cars", Car.create);
app.put("/cars/update/:id", Car.update);
app.delete("/cars/:id", Car.delete);
app.delete("/cars", Car.deleteAll);
}
19 changes: 19 additions & 0 deletions backend/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import fastify from "fastify";
import cors from "@fastify/cors";
import connectDB from "./database/config";
import { appRoutes } from "./routes";

const app = fastify();
connectDB();

/*
* Permitindo chamada de todas as origens somente para fins de teste
*/
app.register(cors);
app.register(appRoutes);

app.listen({
port: 9901,
}).then(() => {
console.log("Server is runing on port 9901");
});
103 changes: 103 additions & 0 deletions backend/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */

/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */

/* Language and Environment */
"target": "es2020", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */

/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */

/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */

/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
Loading