From 6993ba0bff24e9cc254e34d0e1c65e14b375d452 Mon Sep 17 00:00:00 2001 From: K0dax Date: Tue, 7 Feb 2023 15:06:38 -0300 Subject: [PATCH 01/20] setup with prisma --- .gitignore | 4 ++ package.json | 22 +++++++++ prisma/schema.prisma | 29 ++++++++++++ src/.gitignore | 3 ++ src/routes.ts | 0 src/server.ts | 15 +++++++ tsconfig.json | 103 +++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 176 insertions(+) create mode 100644 .gitignore create mode 100644 package.json create mode 100644 prisma/schema.prisma create mode 100644 src/.gitignore create mode 100644 src/routes.ts create mode 100644 src/server.ts create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..c184d2e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +*.lock +.env +migrations/ \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 00000000..ce9d4b10 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "backend-orma", + "version": "1.0.0", + "main": "src/server.ts", + "repository": "https://github.com/K0dax/backend-test-two.git", + "author": "K0dax ", + "license": "MIT", + "scripts": { + "start": "ts-node-dev src/server.ts" + }, + "dependencies": { + "@prisma/client": "^4.9.0", + "dotenv": "^16.0.3", + "express": "^4.18.2", + "prisma": "^4.9.0" + }, + "devDependencies": { + "@types/express": "^4.17.17", + "ts-node-dev": "^2.0.0", + "typescript": "^4.9.5" + } +} diff --git a/prisma/schema.prisma b/prisma/schema.prisma new file mode 100644 index 00000000..70b5fbb4 --- /dev/null +++ b/prisma/schema.prisma @@ -0,0 +1,29 @@ +// This is your Prisma schema file, +// learn more about it in the docs: https://pris.ly/d/prisma-schema + +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") +} + +model Client{ + id String @id @default(uuid()) + abv Int + address String + category String + city String + coordinates String + country String + description String + ibu Int + name String + state String + website String + + @@map("clients") +} + diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 00000000..11ddd8db --- /dev/null +++ b/src/.gitignore @@ -0,0 +1,3 @@ +node_modules +# Keep environment variables out of version control +.env diff --git a/src/routes.ts b/src/routes.ts new file mode 100644 index 00000000..e69de29b diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 00000000..a8ec1d2a --- /dev/null +++ b/src/server.ts @@ -0,0 +1,15 @@ +import express, { Request, Response, NextFunction } from "express"; + +const app = express(); +app.use(express.json()); + +app.use((err: Error, req: Request, res: Response, next: NextFunction) => { + if (err instanceof Error) { + return res.status(400).json({ error: err.message }); + } + return res + .status(500) + .json({ status: "error", message: "Internal server error" }); +}); + +app.listen(3000, () => console.log("Server is running!")); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..75dcaeac --- /dev/null +++ b/tsconfig.json @@ -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": "es2016", /* 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 ''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. */ + } +} From ab2dbe51aa443ef0b2dca3fca4f344eb444d4a77 Mon Sep 17 00:00:00 2001 From: K0dax Date: Tue, 7 Feb 2023 16:12:04 -0300 Subject: [PATCH 02/20] feat(routes): create customers --- package.json | 1 + src/controllers/CreateClientController.ts | 38 +++++++++++++++ src/prisma.ts | 3 ++ src/routes.ts | 8 +++ src/server.ts | 3 ++ src/services/CreateClientService.ts | 59 +++++++++++++++++++++++ 6 files changed, 112 insertions(+) create mode 100644 src/controllers/CreateClientController.ts create mode 100644 src/prisma.ts create mode 100644 src/services/CreateClientService.ts diff --git a/package.json b/package.json index ce9d4b10..611acd19 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "@prisma/client": "^4.9.0", "dotenv": "^16.0.3", "express": "^4.18.2", + "express-async-errors": "^3.1.1", "prisma": "^4.9.0" }, "devDependencies": { diff --git a/src/controllers/CreateClientController.ts b/src/controllers/CreateClientController.ts new file mode 100644 index 00000000..fb90a330 --- /dev/null +++ b/src/controllers/CreateClientController.ts @@ -0,0 +1,38 @@ +import { Request, Response } from "express"; +import { CreateClientService } from "../services/CreateClientService"; + +export class CreateClientController { + async handle(req: Request, res: Response) { + const { + abv, + address, + category, + city, + coordinates, + country, + description, + ibu, + name, + state, + website, + } = req.body; + + const createClientService = new CreateClientService(); + + const client = await createClientService.execute({ + abv, + address, + category, + city, + coordinates, + country, + description, + ibu, + name, + state, + website, + }); + + return res.json(client); + } +} diff --git a/src/prisma.ts b/src/prisma.ts new file mode 100644 index 00000000..11bbdfef --- /dev/null +++ b/src/prisma.ts @@ -0,0 +1,3 @@ +import { PrismaClient } from "@prisma/client"; + +export const prismaClient = new PrismaClient(); diff --git a/src/routes.ts b/src/routes.ts index e69de29b..5267143f 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -0,0 +1,8 @@ +import { Router } from "express"; +import { CreateClientController } from "./controllers/CreateClientController"; + +const router = Router(); + +router.post("/client", new CreateClientController().handle); + +export { router }; diff --git a/src/server.ts b/src/server.ts index a8ec1d2a..c4a90ba2 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,7 +1,10 @@ import express, { Request, Response, NextFunction } from "express"; +import "express-async-errors"; +import { router } from "./routes"; const app = express(); app.use(express.json()); +app.use(router); app.use((err: Error, req: Request, res: Response, next: NextFunction) => { if (err instanceof Error) { diff --git a/src/services/CreateClientService.ts b/src/services/CreateClientService.ts new file mode 100644 index 00000000..deafdaf7 --- /dev/null +++ b/src/services/CreateClientService.ts @@ -0,0 +1,59 @@ +import { prismaClient } from "../prisma"; + +interface ClientRequest { + abv: number; + address: string; + category: string; + city: string; + coordinates: string; + country: string; + description: string; + ibu: number; + name: string; + state: string; + website: string; +} + +export class CreateClientService { + async execute({ + abv, + address, + category, + city, + coordinates, + country, + description, + ibu, + name, + state, + website, + }: ClientRequest) { + const clientAlreadyExists = await prismaClient.client.findFirst({ + where: { + coordinates: coordinates, + }, + }); + + if (clientAlreadyExists) { + throw new Error("These coordinates have been registered before"); + } + + const client = await prismaClient.client.create({ + data: { + abv: abv, + address: address, + category: category, + city: city, + coordinates: coordinates, + country: country, + description: description, + ibu: ibu, + name: name, + state: state, + website: website, + }, + }); + + return client; + } +} From 5500b44659c75b8a0224bd93f145ceb057bc3137 Mon Sep 17 00:00:00 2001 From: K0dax Date: Tue, 7 Feb 2023 16:36:18 -0300 Subject: [PATCH 03/20] feat(routes): details from clients --- src/controllers/DetailsClientController.ts | 14 ++++++++++++++ src/routes.ts | 3 +++ src/services/DetailsClientService.ts | 17 +++++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 src/controllers/DetailsClientController.ts create mode 100644 src/services/DetailsClientService.ts diff --git a/src/controllers/DetailsClientController.ts b/src/controllers/DetailsClientController.ts new file mode 100644 index 00000000..5f60888c --- /dev/null +++ b/src/controllers/DetailsClientController.ts @@ -0,0 +1,14 @@ +import { Request, Response } from "express"; +import { DetailsClientService } from "../services/DetailsClientService"; + +export class DetailsClientController { + async handle(req: Request, res: Response) { + const { id } = req.body; + + const detailsClientService = new DetailsClientService(); + + const client = await detailsClientService.execute(id); + + return res.json(client); + } +} diff --git a/src/routes.ts b/src/routes.ts index 5267143f..65630c5f 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -1,8 +1,11 @@ import { Router } from "express"; import { CreateClientController } from "./controllers/CreateClientController"; +import { DetailsClientController } from "./controllers/DetailsClientController"; const router = Router(); router.post("/client", new CreateClientController().handle); +router.get("/detail", new DetailsClientController().handle); + export { router }; diff --git a/src/services/DetailsClientService.ts b/src/services/DetailsClientService.ts new file mode 100644 index 00000000..cbd04c29 --- /dev/null +++ b/src/services/DetailsClientService.ts @@ -0,0 +1,17 @@ +import { prismaClient } from "../prisma"; + +export class DetailsClientService { + async execute(id: string) { + const client = await prismaClient.client.findFirst({ + where: { + id: id, + }, + }); + + if (!client) { + throw new Error("Client not found or not exists!"); + } + + return client; + } +} From 03d6ccfa2057b9e632dab538de734ee6326ad7f8 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 10:30:33 -0300 Subject: [PATCH 04/20] fix(create/detail): removing return of empty prop --- src/controllers/CreateClientController.ts | 18 ++++++++++-- src/services/CreateClientService.ts | 34 +++++++++++++++++++---- src/services/DetailsClientService.ts | 21 +++++++++++++- 3 files changed, 65 insertions(+), 8 deletions(-) diff --git a/src/controllers/CreateClientController.ts b/src/controllers/CreateClientController.ts index fb90a330..91ee52fe 100644 --- a/src/controllers/CreateClientController.ts +++ b/src/controllers/CreateClientController.ts @@ -8,7 +8,8 @@ export class CreateClientController { address, category, city, - coordinates, + lat, + long, country, description, ibu, @@ -17,6 +18,18 @@ export class CreateClientController { website, } = req.body; + if (!category) { + category == ""; + } + + if (!description) { + description == ""; + } + + if (!website) { + website == ""; + } + const createClientService = new CreateClientService(); const client = await createClientService.execute({ @@ -24,7 +37,8 @@ export class CreateClientController { address, category, city, - coordinates, + lat, + long, country, description, ibu, diff --git a/src/services/CreateClientService.ts b/src/services/CreateClientService.ts index deafdaf7..11ca0d7f 100644 --- a/src/services/CreateClientService.ts +++ b/src/services/CreateClientService.ts @@ -5,7 +5,8 @@ interface ClientRequest { address: string; category: string; city: string; - coordinates: string; + lat: number; + long: number; country: string; description: string; ibu: number; @@ -20,7 +21,8 @@ export class CreateClientService { address, category, city, - coordinates, + lat, + long, country, description, ibu, @@ -30,7 +32,8 @@ export class CreateClientService { }: ClientRequest) { const clientAlreadyExists = await prismaClient.client.findFirst({ where: { - coordinates: coordinates, + lat: lat, + long: long, }, }); @@ -44,7 +47,8 @@ export class CreateClientService { address: address, category: category, city: city, - coordinates: coordinates, + lat: lat, + long: long, country: country, description: description, ibu: ibu, @@ -54,6 +58,26 @@ export class CreateClientService { }, }); - return client; + let clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + + function removeEmpty(client: object) { + return Object.fromEntries( + Object.entries(client).filter(([_, v]) => v != "") + ); + } + + return removeEmpty(clientCoord); } } diff --git a/src/services/DetailsClientService.ts b/src/services/DetailsClientService.ts index cbd04c29..efdb3f0f 100644 --- a/src/services/DetailsClientService.ts +++ b/src/services/DetailsClientService.ts @@ -12,6 +12,25 @@ export class DetailsClientService { throw new Error("Client not found or not exists!"); } - return client; + let clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + function removeEmpty(client: object) { + return Object.fromEntries( + Object.entries(client).filter(([_, v]) => v != "") + ); + } + + return removeEmpty(clientCoord); } } From d02f7799ef9eec771c245fa3295df5d5855348c8 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 10:32:45 -0300 Subject: [PATCH 05/20] fix(db): lat, long and abv now is a float --- prisma/schema.prisma | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 70b5fbb4..f3bd9d68 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -12,11 +12,12 @@ datasource db { model Client{ id String @id @default(uuid()) - abv Int + abv Float address String category String city String - coordinates String + lat Float + long Float country String description String ibu Int From c9927640aa3a60792fa2b9f0ba59a2f50bf2356e Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 11:40:55 -0300 Subject: [PATCH 06/20] feat(routes): added all clients route --- src/controllers/AllClientsController.ts.ts | 12 +++++++ src/routes.ts | 4 +++ src/services/AllClientsService.ts | 38 ++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 src/controllers/AllClientsController.ts.ts create mode 100644 src/services/AllClientsService.ts diff --git a/src/controllers/AllClientsController.ts.ts b/src/controllers/AllClientsController.ts.ts new file mode 100644 index 00000000..cd545db1 --- /dev/null +++ b/src/controllers/AllClientsController.ts.ts @@ -0,0 +1,12 @@ +import { Request, Response } from "express"; +import { AllClientsService } from "../services/AllClientsService"; + +export class AllClientsController { + async handle(req: Request, res: Response) { + const allClientsService = await new AllClientsService(); + + const clients = await allClientsService.execute(); + + return res.json(clients); + } +} diff --git a/src/routes.ts b/src/routes.ts index 65630c5f..052f1213 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -1,6 +1,8 @@ import { Router } from "express"; + import { CreateClientController } from "./controllers/CreateClientController"; import { DetailsClientController } from "./controllers/DetailsClientController"; +import { AllClientsController } from "./controllers/AllClientsController.ts"; const router = Router(); @@ -8,4 +10,6 @@ router.post("/client", new CreateClientController().handle); router.get("/detail", new DetailsClientController().handle); +router.get("/clients", new AllClientsController().handle); + export { router }; diff --git a/src/services/AllClientsService.ts b/src/services/AllClientsService.ts new file mode 100644 index 00000000..90a4dfdc --- /dev/null +++ b/src/services/AllClientsService.ts @@ -0,0 +1,38 @@ +import { prismaClient } from "../prisma"; + +export class AllClientsService { + async execute() { + const clients = await prismaClient.client.findMany({ + orderBy: { + name: "asc", + }, + }); + + const clientsArray = [] as Array; + for (let i = 0; i < clients.length; i++) { + const element = clients[i]; + function removeEmpty(element: object) { + let client = Object.fromEntries( + Object.entries(element).filter(([_, v]) => v != "") + ); + let clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + clientsArray.push(clientCoord); + } + removeEmpty(element); + } + + return clientsArray; + } +} From 5481cd963bd3c1602e6eeb4f291476d34b71486a Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 14:14:37 -0300 Subject: [PATCH 07/20] feat(routes): added update client route --- src/controllers/UpdateClientController.ts | 57 +++++++++++++++++ src/routes.ts | 3 + src/services/UpdateClientService.ts | 76 +++++++++++++++++++++++ 3 files changed, 136 insertions(+) create mode 100644 src/controllers/UpdateClientController.ts create mode 100644 src/services/UpdateClientService.ts diff --git a/src/controllers/UpdateClientController.ts b/src/controllers/UpdateClientController.ts new file mode 100644 index 00000000..10dcc15c --- /dev/null +++ b/src/controllers/UpdateClientController.ts @@ -0,0 +1,57 @@ +import { Request, Response } from "express"; +import { UpdateClientService } from "../services/UpdateClientService"; + +interface ClientRequest { + id: string; + abv?: number; + address?: string; + category?: string; + city?: string; + lat?: number; + long?: number; + country?: string; + description?: string; + ibu?: number; + name?: string; + state?: string; + website?: string; +} +export class UpdateClientController { + async handle(req: Request, res: Response) { + const { id } = req.query; + const { + abv, + address, + category, + city, + lat, + long, + country, + description, + ibu, + name, + state, + website, + } = req.body; + + const updateClientService = await new UpdateClientService(); + + const client = await updateClientService.execute({ + id, + abv, + address, + category, + city, + lat, + long, + country, + description, + ibu, + name, + state, + website, + } as ClientRequest); + + res.json(client); + } +} diff --git a/src/routes.ts b/src/routes.ts index 052f1213..2764f061 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -3,6 +3,7 @@ import { Router } from "express"; import { CreateClientController } from "./controllers/CreateClientController"; import { DetailsClientController } from "./controllers/DetailsClientController"; import { AllClientsController } from "./controllers/AllClientsController.ts"; +import { UpdateClientController } from "./controllers/UpdateClientController"; const router = Router(); @@ -12,4 +13,6 @@ router.get("/detail", new DetailsClientController().handle); router.get("/clients", new AllClientsController().handle); +router.put("/update", new UpdateClientController().handle); + export { router }; diff --git a/src/services/UpdateClientService.ts b/src/services/UpdateClientService.ts new file mode 100644 index 00000000..b6535137 --- /dev/null +++ b/src/services/UpdateClientService.ts @@ -0,0 +1,76 @@ +import { prismaClient } from "../prisma"; + +interface ClientRequest { + id: string; + abv?: number; + address?: string; + category?: string; + city?: string; + lat?: number; + long?: number; + country?: string; + description?: string; + ibu?: number; + name?: string; + state?: string; + website?: string; +} + +export class UpdateClientService { + async execute({ + id, + abv, + address, + category, + city, + lat, + long, + country, + description, + ibu, + name, + state, + website, + }: ClientRequest) { + const client = await prismaClient.client.update({ + where: { + id: id, + }, + data: { + abv: abv, + address: address, + category: category, + city: city, + lat: lat, + long: long, + country: country, + description: description, + ibu: ibu, + name: name, + state: state, + website: website, + }, + }); + let clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + + function removeEmpty(client: object) { + return Object.fromEntries( + Object.entries(client).filter(([_, v]) => v != "") + ); + } + + return removeEmpty(clientCoord); + } +} From 32ab313d51ef2f0cb00bbc71c0baa521489f7e51 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 14:39:16 -0300 Subject: [PATCH 08/20] feat(routes): added delete client route --- src/controllers/DeleteClientController.ts | 16 ++++++++++ src/routes.ts | 3 ++ src/services/DeleteClientService.ts | 36 +++++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 src/controllers/DeleteClientController.ts create mode 100644 src/services/DeleteClientService.ts diff --git a/src/controllers/DeleteClientController.ts b/src/controllers/DeleteClientController.ts new file mode 100644 index 00000000..b61f9715 --- /dev/null +++ b/src/controllers/DeleteClientController.ts @@ -0,0 +1,16 @@ +import { Request, Response } from "express"; +import { DeleteClientService } from "../services/DeleteClientService"; + +interface ClientRequest { + id: string; +} +export class DeleteClientController { + async handle(req: Request, res: Response) { + const { id } = req.query; + const deleteClientService = await new DeleteClientService(); + + const client = await deleteClientService.execute({ id } as ClientRequest); + + res.json(client); + } +} diff --git a/src/routes.ts b/src/routes.ts index 2764f061..12dd1781 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -4,6 +4,7 @@ import { CreateClientController } from "./controllers/CreateClientController"; import { DetailsClientController } from "./controllers/DetailsClientController"; import { AllClientsController } from "./controllers/AllClientsController.ts"; import { UpdateClientController } from "./controllers/UpdateClientController"; +import { DeleteClientController } from "./controllers/DeleteClientController"; const router = Router(); @@ -15,4 +16,6 @@ router.get("/clients", new AllClientsController().handle); router.put("/update", new UpdateClientController().handle); +router.delete("/remove", new DeleteClientController().handle); + export { router }; diff --git a/src/services/DeleteClientService.ts b/src/services/DeleteClientService.ts new file mode 100644 index 00000000..3a29c3af --- /dev/null +++ b/src/services/DeleteClientService.ts @@ -0,0 +1,36 @@ +import { prismaClient } from "../prisma"; + +interface ClientRequest { + id: string; +} + +export class DeleteClientService { + async execute({ id }: ClientRequest) { + const client = await prismaClient.client.delete({ + where: { + id: id, + }, + }); + let clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + + function removeEmpty(client: object) { + return Object.fromEntries( + Object.entries(client).filter(([_, v]) => v != "") + ); + } + + return removeEmpty(clientCoord); + } +} From eb01722eec874b64548ee24898b2751ba669aec7 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 15:23:10 -0300 Subject: [PATCH 09/20] refactor(func): simplifying func & improving org --- src/helpers/CoordinatesClient.ts | 31 ++++++++++++++++++++++++++++ src/helpers/RemoveEmpty.ts | 3 +++ src/services/CreateClientService.ts | 23 +++------------------ src/services/DeleteClientService.ts | 22 +++----------------- src/services/DetailsClientService.ts | 21 +++---------------- src/services/UpdateClientService.ts | 22 +++----------------- 6 files changed, 46 insertions(+), 76 deletions(-) create mode 100644 src/helpers/CoordinatesClient.ts create mode 100644 src/helpers/RemoveEmpty.ts diff --git a/src/helpers/CoordinatesClient.ts b/src/helpers/CoordinatesClient.ts new file mode 100644 index 00000000..6e9484a0 --- /dev/null +++ b/src/helpers/CoordinatesClient.ts @@ -0,0 +1,31 @@ +interface IClient { + abv: number; + address: string; + category: string; + city: string; + lat: number; + long: number; + country: string; + description: string; + ibu: number; + name: string; + state: string; + website: string; +} + +export function Coord(client: IClient) { + const clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + return clientCoord; +} diff --git a/src/helpers/RemoveEmpty.ts b/src/helpers/RemoveEmpty.ts new file mode 100644 index 00000000..e8a81fd7 --- /dev/null +++ b/src/helpers/RemoveEmpty.ts @@ -0,0 +1,3 @@ +export function removeEmpty(client: object) { + return Object.fromEntries(Object.entries(client).filter(([_, v]) => v != "")); +} diff --git a/src/services/CreateClientService.ts b/src/services/CreateClientService.ts index 11ca0d7f..614e63d8 100644 --- a/src/services/CreateClientService.ts +++ b/src/services/CreateClientService.ts @@ -1,4 +1,6 @@ import { prismaClient } from "../prisma"; +import { Coord } from "../helpers/CoordinatesClient"; +import { removeEmpty } from "../helpers/RemoveEmpty"; interface ClientRequest { abv: number; @@ -57,26 +59,7 @@ export class CreateClientService { website: website, }, }); - - let clientCoord = { - abv: client.abv, - address: client.address, - category: client.category, - city: client.city, - coordinates: [client.lat, client.long], - country: client.country, - description: client.description, - ibu: client.ibu, - name: client.name, - state: client.state, - website: client.website, - }; - - function removeEmpty(client: object) { - return Object.fromEntries( - Object.entries(client).filter(([_, v]) => v != "") - ); - } + const clientCoord = Coord(client); return removeEmpty(clientCoord); } diff --git a/src/services/DeleteClientService.ts b/src/services/DeleteClientService.ts index 3a29c3af..e5ac59e0 100644 --- a/src/services/DeleteClientService.ts +++ b/src/services/DeleteClientService.ts @@ -1,4 +1,6 @@ import { prismaClient } from "../prisma"; +import { Coord } from "../helpers/CoordinatesClient"; +import { removeEmpty } from "../helpers/RemoveEmpty"; interface ClientRequest { id: string; @@ -11,25 +13,7 @@ export class DeleteClientService { id: id, }, }); - let clientCoord = { - abv: client.abv, - address: client.address, - category: client.category, - city: client.city, - coordinates: [client.lat, client.long], - country: client.country, - description: client.description, - ibu: client.ibu, - name: client.name, - state: client.state, - website: client.website, - }; - - function removeEmpty(client: object) { - return Object.fromEntries( - Object.entries(client).filter(([_, v]) => v != "") - ); - } + const clientCoord = Coord(client); return removeEmpty(clientCoord); } diff --git a/src/services/DetailsClientService.ts b/src/services/DetailsClientService.ts index efdb3f0f..ed187c39 100644 --- a/src/services/DetailsClientService.ts +++ b/src/services/DetailsClientService.ts @@ -1,4 +1,6 @@ import { prismaClient } from "../prisma"; +import { Coord } from "../helpers/CoordinatesClient"; +import { removeEmpty } from "../helpers/RemoveEmpty"; export class DetailsClientService { async execute(id: string) { @@ -12,24 +14,7 @@ export class DetailsClientService { throw new Error("Client not found or not exists!"); } - let clientCoord = { - abv: client.abv, - address: client.address, - category: client.category, - city: client.city, - coordinates: [client.lat, client.long], - country: client.country, - description: client.description, - ibu: client.ibu, - name: client.name, - state: client.state, - website: client.website, - }; - function removeEmpty(client: object) { - return Object.fromEntries( - Object.entries(client).filter(([_, v]) => v != "") - ); - } + const clientCoord = Coord(client); return removeEmpty(clientCoord); } diff --git a/src/services/UpdateClientService.ts b/src/services/UpdateClientService.ts index b6535137..3510039f 100644 --- a/src/services/UpdateClientService.ts +++ b/src/services/UpdateClientService.ts @@ -1,4 +1,6 @@ import { prismaClient } from "../prisma"; +import { Coord } from "../helpers/CoordinatesClient"; +import { removeEmpty } from "../helpers/RemoveEmpty"; interface ClientRequest { id: string; @@ -51,25 +53,7 @@ export class UpdateClientService { website: website, }, }); - let clientCoord = { - abv: client.abv, - address: client.address, - category: client.category, - city: client.city, - coordinates: [client.lat, client.long], - country: client.country, - description: client.description, - ibu: client.ibu, - name: client.name, - state: client.state, - website: client.website, - }; - - function removeEmpty(client: object) { - return Object.fromEntries( - Object.entries(client).filter(([_, v]) => v != "") - ); - } + const clientCoord = Coord(client); return removeEmpty(clientCoord); } From 87885d3eb6a8ddfea57383f2feaef8f8f01b5e63 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 15:45:25 -0300 Subject: [PATCH 10/20] feat(routes): clients filtered by query --- .../GetFilteredClientsController.ts | 56 +++++++++++++ src/routes.ts | 3 + src/services/GetFilteredClientsService.ts | 78 +++++++++++++++++++ 3 files changed, 137 insertions(+) create mode 100644 src/controllers/GetFilteredClientsController.ts create mode 100644 src/services/GetFilteredClientsService.ts diff --git a/src/controllers/GetFilteredClientsController.ts b/src/controllers/GetFilteredClientsController.ts new file mode 100644 index 00000000..f47c6001 --- /dev/null +++ b/src/controllers/GetFilteredClientsController.ts @@ -0,0 +1,56 @@ +import { Request, Response } from "express"; +import { GetFilteredClientsService } from "../services/GetFilteredClientsService"; + +interface ClientRequest { + abv?: number; + address?: string; + category?: string; + city?: string; + lat?: number; + long?: number; + country?: string; + description?: string; + ibu?: number; + name?: string; + state?: string; + website?: string; +} + +export class GetFilteredClientsController { + async handle(req: Request, res: Response) { + const { + id, + abv, + address, + category, + city, + lat, + long, + country, + description, + ibu, + name, + state, + website, + } = req.query; + + const getFilteredClientsService = await new GetFilteredClientsService(); + + const clients = await getFilteredClientsService.execute({ + abv, + address, + category, + city, + lat, + long, + country, + description, + ibu, + name, + state, + website, + } as ClientRequest); + + res.json(clients); + } +} diff --git a/src/routes.ts b/src/routes.ts index 12dd1781..6f9e1d3c 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -3,6 +3,7 @@ import { Router } from "express"; import { CreateClientController } from "./controllers/CreateClientController"; import { DetailsClientController } from "./controllers/DetailsClientController"; import { AllClientsController } from "./controllers/AllClientsController.ts"; +import { GetFilteredClientsController } from "./controllers/GetFilteredClientsController"; import { UpdateClientController } from "./controllers/UpdateClientController"; import { DeleteClientController } from "./controllers/DeleteClientController"; @@ -14,6 +15,8 @@ router.get("/detail", new DetailsClientController().handle); router.get("/clients", new AllClientsController().handle); +router.get("/filtered", new GetFilteredClientsController().handle); + router.put("/update", new UpdateClientController().handle); router.delete("/remove", new DeleteClientController().handle); diff --git a/src/services/GetFilteredClientsService.ts b/src/services/GetFilteredClientsService.ts new file mode 100644 index 00000000..6cfc0d28 --- /dev/null +++ b/src/services/GetFilteredClientsService.ts @@ -0,0 +1,78 @@ +import { prismaClient } from "../prisma"; +import { Coord } from "../helpers/CoordinatesClient"; +import { removeEmpty } from "../helpers/RemoveEmpty"; + +interface ClientRequest { + abv?: number; + address?: string; + category?: string; + city?: string; + lat?: number; + long?: number; + country?: string; + description?: string; + ibu?: number; + name?: string; + state?: string; + website?: string; +} +export class GetFilteredClientsService { + async execute({ + abv, + address, + category, + city, + lat, + long, + country, + description, + ibu, + name, + state, + website, + }: ClientRequest) { + const clients = await prismaClient.client.findMany({ + where: { + abv: abv, + address: address, + category: category, + city: city, + lat: lat, + long: long, + country: country, + description: description, + ibu: ibu, + name: name, + state: state, + website: website, + }, + }); + + const clientsArray = [] as Array; + for (let i = 0; i < clients.length; i++) { + const element = clients[i]; + function removeEmpty(element: object) { + let client = Object.fromEntries( + Object.entries(element).filter(([_, v]) => v != "") + ); + let clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + clientsArray.push(clientCoord); + } + removeEmpty(element); + } + + return clientsArray; + } +} From 7974a959f0f5c4f7790f22d41af06d0c9fe42706 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 16:52:01 -0300 Subject: [PATCH 11/20] fix(getfiltered): now can't use id, lat or long --- src/controllers/GetFilteredClientsController.ts | 5 ----- src/services/GetFilteredClientsService.ts | 8 -------- 2 files changed, 13 deletions(-) diff --git a/src/controllers/GetFilteredClientsController.ts b/src/controllers/GetFilteredClientsController.ts index f47c6001..1cfc926b 100644 --- a/src/controllers/GetFilteredClientsController.ts +++ b/src/controllers/GetFilteredClientsController.ts @@ -19,13 +19,10 @@ interface ClientRequest { export class GetFilteredClientsController { async handle(req: Request, res: Response) { const { - id, abv, address, category, city, - lat, - long, country, description, ibu, @@ -41,8 +38,6 @@ export class GetFilteredClientsController { address, category, city, - lat, - long, country, description, ibu, diff --git a/src/services/GetFilteredClientsService.ts b/src/services/GetFilteredClientsService.ts index 6cfc0d28..c0134585 100644 --- a/src/services/GetFilteredClientsService.ts +++ b/src/services/GetFilteredClientsService.ts @@ -1,14 +1,10 @@ import { prismaClient } from "../prisma"; -import { Coord } from "../helpers/CoordinatesClient"; -import { removeEmpty } from "../helpers/RemoveEmpty"; interface ClientRequest { abv?: number; address?: string; category?: string; city?: string; - lat?: number; - long?: number; country?: string; description?: string; ibu?: number; @@ -22,8 +18,6 @@ export class GetFilteredClientsService { address, category, city, - lat, - long, country, description, ibu, @@ -37,8 +31,6 @@ export class GetFilteredClientsService { address: address, category: category, city: city, - lat: lat, - long: long, country: country, description: description, ibu: ibu, From 1f63eeb1bc41e64e6aec54db4338c5560bd9facc Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 17:15:56 -0300 Subject: [PATCH 12/20] doc: example.env --- exemple.env | 1 + 1 file changed, 1 insertion(+) create mode 100644 exemple.env diff --git a/exemple.env b/exemple.env new file mode 100644 index 00000000..49b8b60f --- /dev/null +++ b/exemple.env @@ -0,0 +1 @@ +DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public" \ No newline at end of file From 78a2c4f26a3926158954fd8519a4336baae2b7e5 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 17:33:29 -0300 Subject: [PATCH 13/20] docs: deploy configs --- package.json | 3 ++- tsconfig.json | 14 +++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 611acd19..8c4e6ff2 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,8 @@ "author": "K0dax ", "license": "MIT", "scripts": { - "start": "ts-node-dev src/server.ts" + "build": "rm -rf ./dist && tsc", + "start": "node ./dist/server.js" }, "dependencies": { "@prisma/client": "^4.9.0", diff --git a/tsconfig.json b/tsconfig.json index 75dcaeac..be00030a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,7 +11,7 @@ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "target": "es2016" /* 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. */ @@ -25,7 +25,7 @@ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ + "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. */ @@ -49,7 +49,7 @@ // "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. */ + "outDir": "./dist" /* 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. */ @@ -71,12 +71,12 @@ /* 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. */ + "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. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ + "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. */ @@ -98,6 +98,6 @@ /* Completeness */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ } } From 511a96ae2bb78d758be073a4cc5619bec3c1af61 Mon Sep 17 00:00:00 2001 From: Yan Carlos <78356819+K0dax@users.noreply.github.com> Date: Wed, 8 Feb 2023 18:08:29 -0300 Subject: [PATCH 14/20] Update and rename exemple.env to .env --- .env | 1 + exemple.env | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 .env delete mode 100644 exemple.env diff --git a/.env b/.env new file mode 100644 index 00000000..ee4343e9 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +DATABASE_URL="postgres://idmzutgt:JMeCd9HS2bp7xH2ytimcU9J9CxH3E85F@babar.db.elephantsql.com/idmzutgt" diff --git a/exemple.env b/exemple.env deleted file mode 100644 index 49b8b60f..00000000 --- a/exemple.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public" \ No newline at end of file From f25b6c1c5c9d06f8745ac8fa447aed41f6139405 Mon Sep 17 00:00:00 2001 From: Yan Carlos <78356819+K0dax@users.noreply.github.com> Date: Wed, 8 Feb 2023 18:10:40 -0300 Subject: [PATCH 15/20] Update package.json --- package.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 8c4e6ff2..9f1dd2fe 100644 --- a/package.json +++ b/package.json @@ -6,8 +6,9 @@ "author": "K0dax ", "license": "MIT", "scripts": { - "build": "rm -rf ./dist && tsc", - "start": "node ./dist/server.js" + "install": "npm install" + "build": "rm -rf /dist && tsc", + "start": "node /dist/server.js" }, "dependencies": { "@prisma/client": "^4.9.0", From b71cb87bffa4a92c98ee77674b99fa56f37b25f6 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 18:13:31 -0300 Subject: [PATCH 16/20] aaa --- dist/controllers/AllClientsController.ts.js | 23 ++++++++ dist/controllers/CreateClientController.js | 46 +++++++++++++++ dist/controllers/DeleteClientController.js | 24 ++++++++ dist/controllers/DetailsClientController.js | 24 ++++++++ .../GetFilteredClientsController.js | 35 ++++++++++++ dist/controllers/UpdateClientController.js | 39 +++++++++++++ dist/helpers/CoordinatesClient.js | 20 +++++++ dist/helpers/RemoveEmpty.js | 7 +++ dist/prisma.js | 5 ++ dist/routes.js | 18 ++++++ dist/server.js | 20 +++++++ dist/services/AllClientsService.js | 48 ++++++++++++++++ dist/services/CreateClientService.js | 49 ++++++++++++++++ dist/services/DeleteClientService.js | 29 ++++++++++ dist/services/DetailsClientService.js | 32 +++++++++++ dist/services/GetFilteredClientsService.js | 57 +++++++++++++++++++ dist/services/UpdateClientService.js | 43 ++++++++++++++ package.json | 2 +- 18 files changed, 520 insertions(+), 1 deletion(-) create mode 100644 dist/controllers/AllClientsController.ts.js create mode 100644 dist/controllers/CreateClientController.js create mode 100644 dist/controllers/DeleteClientController.js create mode 100644 dist/controllers/DetailsClientController.js create mode 100644 dist/controllers/GetFilteredClientsController.js create mode 100644 dist/controllers/UpdateClientController.js create mode 100644 dist/helpers/CoordinatesClient.js create mode 100644 dist/helpers/RemoveEmpty.js create mode 100644 dist/prisma.js create mode 100644 dist/routes.js create mode 100644 dist/server.js create mode 100644 dist/services/AllClientsService.js create mode 100644 dist/services/CreateClientService.js create mode 100644 dist/services/DeleteClientService.js create mode 100644 dist/services/DetailsClientService.js create mode 100644 dist/services/GetFilteredClientsService.js create mode 100644 dist/services/UpdateClientService.js diff --git a/dist/controllers/AllClientsController.ts.js b/dist/controllers/AllClientsController.ts.js new file mode 100644 index 00000000..daac2db8 --- /dev/null +++ b/dist/controllers/AllClientsController.ts.js @@ -0,0 +1,23 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AllClientsController = void 0; +const AllClientsService_1 = require("../services/AllClientsService"); +class AllClientsController { + handle(req, res) { + return __awaiter(this, void 0, void 0, function* () { + const allClientsService = yield new AllClientsService_1.AllClientsService(); + const clients = yield allClientsService.execute(); + return res.json(clients); + }); + } +} +exports.AllClientsController = AllClientsController; diff --git a/dist/controllers/CreateClientController.js b/dist/controllers/CreateClientController.js new file mode 100644 index 00000000..edef1c84 --- /dev/null +++ b/dist/controllers/CreateClientController.js @@ -0,0 +1,46 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CreateClientController = void 0; +const CreateClientService_1 = require("../services/CreateClientService"); +class CreateClientController { + handle(req, res) { + return __awaiter(this, void 0, void 0, function* () { + const { abv, address, category, city, lat, long, country, description, ibu, name, state, website, } = req.body; + if (!category) { + category == ""; + } + if (!description) { + description == ""; + } + if (!website) { + website == ""; + } + const createClientService = new CreateClientService_1.CreateClientService(); + const client = yield createClientService.execute({ + abv, + address, + category, + city, + lat, + long, + country, + description, + ibu, + name, + state, + website, + }); + return res.json(client); + }); + } +} +exports.CreateClientController = CreateClientController; diff --git a/dist/controllers/DeleteClientController.js b/dist/controllers/DeleteClientController.js new file mode 100644 index 00000000..af7812a1 --- /dev/null +++ b/dist/controllers/DeleteClientController.js @@ -0,0 +1,24 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DeleteClientController = void 0; +const DeleteClientService_1 = require("../services/DeleteClientService"); +class DeleteClientController { + handle(req, res) { + return __awaiter(this, void 0, void 0, function* () { + const { id } = req.query; + const deleteClientService = yield new DeleteClientService_1.DeleteClientService(); + const client = yield deleteClientService.execute({ id }); + res.json(client); + }); + } +} +exports.DeleteClientController = DeleteClientController; diff --git a/dist/controllers/DetailsClientController.js b/dist/controllers/DetailsClientController.js new file mode 100644 index 00000000..6cbdfa36 --- /dev/null +++ b/dist/controllers/DetailsClientController.js @@ -0,0 +1,24 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DetailsClientController = void 0; +const DetailsClientService_1 = require("../services/DetailsClientService"); +class DetailsClientController { + handle(req, res) { + return __awaiter(this, void 0, void 0, function* () { + const { id } = req.body; + const detailsClientService = new DetailsClientService_1.DetailsClientService(); + const client = yield detailsClientService.execute(id); + return res.json(client); + }); + } +} +exports.DetailsClientController = DetailsClientController; diff --git a/dist/controllers/GetFilteredClientsController.js b/dist/controllers/GetFilteredClientsController.js new file mode 100644 index 00000000..f832ef73 --- /dev/null +++ b/dist/controllers/GetFilteredClientsController.js @@ -0,0 +1,35 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GetFilteredClientsController = void 0; +const GetFilteredClientsService_1 = require("../services/GetFilteredClientsService"); +class GetFilteredClientsController { + handle(req, res) { + return __awaiter(this, void 0, void 0, function* () { + const { abv, address, category, city, country, description, ibu, name, state, website, } = req.query; + const getFilteredClientsService = yield new GetFilteredClientsService_1.GetFilteredClientsService(); + const clients = yield getFilteredClientsService.execute({ + abv, + address, + category, + city, + country, + description, + ibu, + name, + state, + website, + }); + res.json(clients); + }); + } +} +exports.GetFilteredClientsController = GetFilteredClientsController; diff --git a/dist/controllers/UpdateClientController.js b/dist/controllers/UpdateClientController.js new file mode 100644 index 00000000..a0b7e4b0 --- /dev/null +++ b/dist/controllers/UpdateClientController.js @@ -0,0 +1,39 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UpdateClientController = void 0; +const UpdateClientService_1 = require("../services/UpdateClientService"); +class UpdateClientController { + handle(req, res) { + return __awaiter(this, void 0, void 0, function* () { + const { id } = req.query; + const { abv, address, category, city, lat, long, country, description, ibu, name, state, website, } = req.body; + const updateClientService = yield new UpdateClientService_1.UpdateClientService(); + const client = yield updateClientService.execute({ + id, + abv, + address, + category, + city, + lat, + long, + country, + description, + ibu, + name, + state, + website, + }); + res.json(client); + }); + } +} +exports.UpdateClientController = UpdateClientController; diff --git a/dist/helpers/CoordinatesClient.js b/dist/helpers/CoordinatesClient.js new file mode 100644 index 00000000..f984cc41 --- /dev/null +++ b/dist/helpers/CoordinatesClient.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Coord = void 0; +function Coord(client) { + const clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + return clientCoord; +} +exports.Coord = Coord; diff --git a/dist/helpers/RemoveEmpty.js b/dist/helpers/RemoveEmpty.js new file mode 100644 index 00000000..1dc3d549 --- /dev/null +++ b/dist/helpers/RemoveEmpty.js @@ -0,0 +1,7 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.removeEmpty = void 0; +function removeEmpty(client) { + return Object.fromEntries(Object.entries(client).filter(([_, v]) => v != "")); +} +exports.removeEmpty = removeEmpty; diff --git a/dist/prisma.js b/dist/prisma.js new file mode 100644 index 00000000..4ed3fc88 --- /dev/null +++ b/dist/prisma.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.prismaClient = void 0; +const client_1 = require("@prisma/client"); +exports.prismaClient = new client_1.PrismaClient(); diff --git a/dist/routes.js b/dist/routes.js new file mode 100644 index 00000000..db5334c0 --- /dev/null +++ b/dist/routes.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.router = void 0; +const express_1 = require("express"); +const CreateClientController_1 = require("./controllers/CreateClientController"); +const DetailsClientController_1 = require("./controllers/DetailsClientController"); +const AllClientsController_ts_1 = require("./controllers/AllClientsController.ts"); +const GetFilteredClientsController_1 = require("./controllers/GetFilteredClientsController"); +const UpdateClientController_1 = require("./controllers/UpdateClientController"); +const DeleteClientController_1 = require("./controllers/DeleteClientController"); +const router = (0, express_1.Router)(); +exports.router = router; +router.post("/client", new CreateClientController_1.CreateClientController().handle); +router.get("/detail", new DetailsClientController_1.DetailsClientController().handle); +router.get("/clients", new AllClientsController_ts_1.AllClientsController().handle); +router.get("/filtered", new GetFilteredClientsController_1.GetFilteredClientsController().handle); +router.put("/update", new UpdateClientController_1.UpdateClientController().handle); +router.delete("/remove", new DeleteClientController_1.DeleteClientController().handle); diff --git a/dist/server.js b/dist/server.js new file mode 100644 index 00000000..3cf54f72 --- /dev/null +++ b/dist/server.js @@ -0,0 +1,20 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const express_1 = __importDefault(require("express")); +require("express-async-errors"); +const routes_1 = require("./routes"); +const app = (0, express_1.default)(); +app.use(express_1.default.json()); +app.use(routes_1.router); +app.use((err, req, res, next) => { + if (err instanceof Error) { + return res.status(400).json({ error: err.message }); + } + return res + .status(500) + .json({ status: "error", message: "Internal server error" }); +}); +app.listen(3000, () => console.log("Server is running!")); diff --git a/dist/services/AllClientsService.js b/dist/services/AllClientsService.js new file mode 100644 index 00000000..f0034c9d --- /dev/null +++ b/dist/services/AllClientsService.js @@ -0,0 +1,48 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AllClientsService = void 0; +const prisma_1 = require("../prisma"); +class AllClientsService { + execute() { + return __awaiter(this, void 0, void 0, function* () { + const clients = yield prisma_1.prismaClient.client.findMany({ + orderBy: { + name: "asc", + }, + }); + const clientsArray = []; + for (let i = 0; i < clients.length; i++) { + const element = clients[i]; + function removeEmpty(element) { + let client = Object.fromEntries(Object.entries(element).filter(([_, v]) => v != "")); + let clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + clientsArray.push(clientCoord); + } + removeEmpty(element); + } + return clientsArray; + }); + } +} +exports.AllClientsService = AllClientsService; diff --git a/dist/services/CreateClientService.js b/dist/services/CreateClientService.js new file mode 100644 index 00000000..aa231d6c --- /dev/null +++ b/dist/services/CreateClientService.js @@ -0,0 +1,49 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CreateClientService = void 0; +const prisma_1 = require("../prisma"); +const CoordinatesClient_1 = require("../helpers/CoordinatesClient"); +const RemoveEmpty_1 = require("../helpers/RemoveEmpty"); +class CreateClientService { + execute({ abv, address, category, city, lat, long, country, description, ibu, name, state, website, }) { + return __awaiter(this, void 0, void 0, function* () { + const clientAlreadyExists = yield prisma_1.prismaClient.client.findFirst({ + where: { + lat: lat, + long: long, + }, + }); + if (clientAlreadyExists) { + throw new Error("These coordinates have been registered before"); + } + const client = yield prisma_1.prismaClient.client.create({ + data: { + abv: abv, + address: address, + category: category, + city: city, + lat: lat, + long: long, + country: country, + description: description, + ibu: ibu, + name: name, + state: state, + website: website, + }, + }); + const clientCoord = (0, CoordinatesClient_1.Coord)(client); + return (0, RemoveEmpty_1.removeEmpty)(clientCoord); + }); + } +} +exports.CreateClientService = CreateClientService; diff --git a/dist/services/DeleteClientService.js b/dist/services/DeleteClientService.js new file mode 100644 index 00000000..1ba8c43a --- /dev/null +++ b/dist/services/DeleteClientService.js @@ -0,0 +1,29 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DeleteClientService = void 0; +const prisma_1 = require("../prisma"); +const CoordinatesClient_1 = require("../helpers/CoordinatesClient"); +const RemoveEmpty_1 = require("../helpers/RemoveEmpty"); +class DeleteClientService { + execute({ id }) { + return __awaiter(this, void 0, void 0, function* () { + const client = yield prisma_1.prismaClient.client.delete({ + where: { + id: id, + }, + }); + const clientCoord = (0, CoordinatesClient_1.Coord)(client); + return (0, RemoveEmpty_1.removeEmpty)(clientCoord); + }); + } +} +exports.DeleteClientService = DeleteClientService; diff --git a/dist/services/DetailsClientService.js b/dist/services/DetailsClientService.js new file mode 100644 index 00000000..33f4dc16 --- /dev/null +++ b/dist/services/DetailsClientService.js @@ -0,0 +1,32 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DetailsClientService = void 0; +const prisma_1 = require("../prisma"); +const CoordinatesClient_1 = require("../helpers/CoordinatesClient"); +const RemoveEmpty_1 = require("../helpers/RemoveEmpty"); +class DetailsClientService { + execute(id) { + return __awaiter(this, void 0, void 0, function* () { + const client = yield prisma_1.prismaClient.client.findFirst({ + where: { + id: id, + }, + }); + if (!client) { + throw new Error("Client not found or not exists!"); + } + const clientCoord = (0, CoordinatesClient_1.Coord)(client); + return (0, RemoveEmpty_1.removeEmpty)(clientCoord); + }); + } +} +exports.DetailsClientService = DetailsClientService; diff --git a/dist/services/GetFilteredClientsService.js b/dist/services/GetFilteredClientsService.js new file mode 100644 index 00000000..4a1298e5 --- /dev/null +++ b/dist/services/GetFilteredClientsService.js @@ -0,0 +1,57 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GetFilteredClientsService = void 0; +const prisma_1 = require("../prisma"); +class GetFilteredClientsService { + execute({ abv, address, category, city, country, description, ibu, name, state, website, }) { + return __awaiter(this, void 0, void 0, function* () { + const clients = yield prisma_1.prismaClient.client.findMany({ + where: { + abv: abv, + address: address, + category: category, + city: city, + country: country, + description: description, + ibu: ibu, + name: name, + state: state, + website: website, + }, + }); + const clientsArray = []; + for (let i = 0; i < clients.length; i++) { + const element = clients[i]; + function removeEmpty(element) { + let client = Object.fromEntries(Object.entries(element).filter(([_, v]) => v != "")); + let clientCoord = { + abv: client.abv, + address: client.address, + category: client.category, + city: client.city, + coordinates: [client.lat, client.long], + country: client.country, + description: client.description, + ibu: client.ibu, + name: client.name, + state: client.state, + website: client.website, + }; + clientsArray.push(clientCoord); + } + removeEmpty(element); + } + return clientsArray; + }); + } +} +exports.GetFilteredClientsService = GetFilteredClientsService; diff --git a/dist/services/UpdateClientService.js b/dist/services/UpdateClientService.js new file mode 100644 index 00000000..2ff39ad3 --- /dev/null +++ b/dist/services/UpdateClientService.js @@ -0,0 +1,43 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UpdateClientService = void 0; +const prisma_1 = require("../prisma"); +const CoordinatesClient_1 = require("../helpers/CoordinatesClient"); +const RemoveEmpty_1 = require("../helpers/RemoveEmpty"); +class UpdateClientService { + execute({ id, abv, address, category, city, lat, long, country, description, ibu, name, state, website, }) { + return __awaiter(this, void 0, void 0, function* () { + const client = yield prisma_1.prismaClient.client.update({ + where: { + id: id, + }, + data: { + abv: abv, + address: address, + category: category, + city: city, + lat: lat, + long: long, + country: country, + description: description, + ibu: ibu, + name: name, + state: state, + website: website, + }, + }); + const clientCoord = (0, CoordinatesClient_1.Coord)(client); + return (0, RemoveEmpty_1.removeEmpty)(clientCoord); + }); + } +} +exports.UpdateClientService = UpdateClientService; diff --git a/package.json b/package.json index 9f1dd2fe..5f788687 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "author": "K0dax ", "license": "MIT", "scripts": { - "install": "npm install" + "install": "npm install", "build": "rm -rf /dist && tsc", "start": "node /dist/server.js" }, From 048d168465bbdd72d2a52c91d0c1adb5af23ef72 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 18:16:32 -0300 Subject: [PATCH 17/20] a --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 8c4e6ff2..b60be0a0 100644 --- a/package.json +++ b/package.json @@ -6,8 +6,8 @@ "author": "K0dax ", "license": "MIT", "scripts": { - "build": "rm -rf ./dist && tsc", - "start": "node ./dist/server.js" + "build": "rm -rf /dist && tsc", + "start": "node /dist/server.js" }, "dependencies": { "@prisma/client": "^4.9.0", From 46f89aa88261ef7ad4d5ee60d8aac19d37a4ef52 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 18:26:34 -0300 Subject: [PATCH 18/20] Deploy test --- package.json | 3 ++- tsconfig.json | 14 +++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 611acd19..8c4e6ff2 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,8 @@ "author": "K0dax ", "license": "MIT", "scripts": { - "start": "ts-node-dev src/server.ts" + "build": "rm -rf ./dist && tsc", + "start": "node ./dist/server.js" }, "dependencies": { "@prisma/client": "^4.9.0", diff --git a/tsconfig.json b/tsconfig.json index 75dcaeac..be00030a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,7 +11,7 @@ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ /* Language and Environment */ - "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + "target": "es2016" /* 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. */ @@ -25,7 +25,7 @@ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ + "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. */ @@ -49,7 +49,7 @@ // "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. */ + "outDir": "./dist" /* 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. */ @@ -71,12 +71,12 @@ /* 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. */ + "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. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ + "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. */ @@ -98,6 +98,6 @@ /* Completeness */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ } } From 5284715a0b7fdedab24875cdbc4d9e34a8bd92f2 Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 18:47:29 -0300 Subject: [PATCH 19/20] doc: deployment failure --- package.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/package.json b/package.json index 8c4e6ff2..611acd19 100644 --- a/package.json +++ b/package.json @@ -6,8 +6,7 @@ "author": "K0dax ", "license": "MIT", "scripts": { - "build": "rm -rf ./dist && tsc", - "start": "node ./dist/server.js" + "start": "ts-node-dev src/server.ts" }, "dependencies": { "@prisma/client": "^4.9.0", From e75c49a8190ce92e4744cbcaeb97e08671e0b6aa Mon Sep 17 00:00:00 2001 From: K0dax Date: Wed, 8 Feb 2023 19:03:32 -0300 Subject: [PATCH 20/20] doc: readme --- README.md | 70 ++++++++++++++----------------------------------------- 1 file changed, 17 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index f36cc9af..8b6b19a4 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,25 @@ -# **TESTE DE BACKEND** +# Instalação -## SITUAÇÃO-PROBLEMA +## Alterar nome de example.env para .env e atualizar o conteúdo com os dados do seu banco: -Você acabou de ser contratado para uma vaga de desenvolvedor backend de uma empresa que revende cervejas do mundo inteiro. O desenvolvedor anterior corrompeu completamente o banco de dados e a API anterior e sobrou apenas um arquivo .JSON com todas as informações do banco. Seu líder confiou a tarefa de recriar a API e o banco de dados a você. +```code +DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public" +``` -Neste teste, você deverá criar uma API com endpoints a serem consumidos via REST e um banco de dados, utilizando os dados fornecidos no arquivo. ````db.json````. +## Instalar dependências ---------------------------------------------------------------------- +``` +npm install +``` -## REQUISITOS OBRIGATÓRIOS: +## Fazer a migração para o banco de dados Postgresql -- Seja original, projetos suspeitos de serem copiados serão descartados. -- Queremos ver o seu código, e não o de outros. -- Criar coleção no Postman (seu teste será testado por aqui). +``` +npx prisma migrate dev +``` -## GIT - -- Faça um fork deste repositório. -- Crie uma branch para codar as suas features. -- Faça um pull-request quando o teste for finalizado. - -##### **NOTA: Será avaliado também se o nome da branch, títulos de commit, push e comentários possuem boa legibilidade.** - ------------------------------------------------------ - -## FRAMEWORK - - -- Servidor: Express (Javascript/Typescript) ***OU*** Gin (Golang) -- Banco de dados: MongoDB, DynamoDB, MySQL, Postgres... - ------------------------------------------------------ - -## PROJETO - -- Api deve conter pelo menos 1 endpoint para cada operação crud (Create, Read, Update, Delete). -- Um endpoint para listagem de conteúdo. -- Banco de dados a escolha do dev. - -------------------------------------------------------- - -## REQUISITOS DIFERENCIAIS: - -- Seguir os princípios de SOLID. -- Fazer o teste em GoLang. -- Codar um código performático. -- Utilizar inglês no projeto todo. -- Utilizar Injeção de dependências. -- Criar um frontend que consuma a API -- Fazer deploy do mesmo (heroku, aws, google cloud ou outro da preferência). - - - ---- - -## ENTREGA - -- Faça um pull request e nomeie-o como no ex.: Teste de (Seu nome aqui). -- Envie um email para schmidt@repenso.eco e kevin@repenso.eco com o link do pull request, do deploy (tanto do front quanto do back se feito), e anexe a coleção do postman. -- Assim que avaliarmos seu teste, enviaremos uma devolutiva de sucesso ou falha, e caso seja aprovado, um link para agendar sua entrevista técnica. +## Rodar a API na porta 3000 +``` +npm start +```