From e648750265402ec10b503170f0c85121c131a416 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Wed, 28 Jul 2021 20:54:12 -0400 Subject: [PATCH 01/29] Inicializando o projeto --- semana17/LabenuSystem/.eslintrc.json | 252 ++++++++++++++++++ semana17/LabenuSystem/.gitignore | 5 + semana17/LabenuSystem/package.json | 26 ++ semana17/LabenuSystem/src/@types/index.d.ts | 123 +++++++++ .../src/database/mysql/connection.ts | 13 + semana17/LabenuSystem/src/env.ts | 2 + semana17/LabenuSystem/src/index.ts | 19 ++ semana17/LabenuSystem/src/queries.sql | 75 ++++++ semana17/LabenuSystem/tsconfig.json | 73 +++++ 9 files changed, 588 insertions(+) create mode 100644 semana17/LabenuSystem/.eslintrc.json create mode 100644 semana17/LabenuSystem/.gitignore create mode 100644 semana17/LabenuSystem/package.json create mode 100644 semana17/LabenuSystem/src/@types/index.d.ts create mode 100644 semana17/LabenuSystem/src/database/mysql/connection.ts create mode 100644 semana17/LabenuSystem/src/env.ts create mode 100644 semana17/LabenuSystem/src/index.ts create mode 100644 semana17/LabenuSystem/src/queries.sql create mode 100644 semana17/LabenuSystem/tsconfig.json diff --git a/semana17/LabenuSystem/.eslintrc.json b/semana17/LabenuSystem/.eslintrc.json new file mode 100644 index 0000000..c6cf55d --- /dev/null +++ b/semana17/LabenuSystem/.eslintrc.json @@ -0,0 +1,252 @@ +{ + "root": true, + "env": { + "browser": true, + "es2020": true, + "node": true + }, + "extends": [ + "eslint:recommended", + "plugin:react/recommended", + "plugin:@typescript-eslint/recommended", + "plugin:react-hooks/recommended" + ], + "settings": { + "react": { + "version": "detect" + } + }, + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaFeatures": { + "jsx": true + }, + "ecmaVersion": 11, + "sourceType": "module" + }, + "plugins": ["react", "@typescript-eslint", "react-hooks"], + "rules": { + "no-cond-assign": ["error", "always"], + "no-console": "warn", + "no-constant-condition": "error", + "no-debugger": "error", + "no-dupe-else-if": "error", + "no-dupe-keys": "error", + "no-duplicate-case": "error", + "no-empty": "warn", + "no-empty-character-class": "error", + "no-extra-boolean-cast": "warn", + "no-extra-parens": "off", + "@typescript-eslint/no-extra-parens": ["warn", "all", { "ignoreJSX": "multi-line" }], + "no-extra-semi": "warn", + "no-func-assign": "warn", + "no-import-assign": "warn", + "no-inner-declarations": ["warn", "both"], + "no-invalid-regexp": "error", + "no-irregular-whitespace": ["warn", { + "skipRegExps": true, + "skipTemplates": true + }], + "no-loss-of-precision": "warn", + "no-misleading-character-class": "warn", + "no-obj-calls": "warn", + "no-prototype-builtins": "error", + "no-sparse-arrays": "error", + "no-template-curly-in-string": "warn", + "no-unexpected-multiline": "warn", + "no-unreachable": "error", + "no-unreachable-loop": "error", + "no-unsafe-finally": "error", + "no-unsafe-negation": "error", + "use-isnan": "warn", + "valid-typeof": "error", + + "curly": ["warn", "multi", "consistent"], + "no-empty-function": "warn", + + "array-bracket-newline": ["warn", { "multiline": true }], + "array-bracket-spacing": ["warn", "always"], + "array-element-newline": ["warn", { "multiline": true, "minItems": 3 }], + "block-spacing": "warn", + "brace-style": ["warn", "1tbs", { "allowSingleLine": true }], + "capitalized-comments": "warn", + "camelcase": "off", + "comma-dangle": ["warn", "never"], + "comma-spacing": ["warn", { "before": false, "after": true }], + "comma-style": ["warn", "last"], + "computed-property-spacing": "warn", + "eol-last": ["warn", "always"], + "func-call-spacing": ["error", "never"], + "func-names": ["error", "always"], + "func-style": ["error", "declaration", { "allowArrowFunctions": true }], + "function-call-argument-newline": ["warn", "consistent"], + "function-paren-newline": ["warn", "multiline"], + "id-length": ["warn", { "min": 3, "exceptions": ["id", "_"] }], + "implicit-arrow-linebreak": ["warn", "beside"], + "indent": ["warn", 2, { + "SwitchCase": 1, + "VariableDeclarator": "first", + "MemberExpression": 1, + "FunctionDeclaration": {"parameters": "first"}, + "FunctionExpression": {"parameters": "first"}, + "CallExpression": {"arguments": "first"}, + "ArrayExpression": "first", + "ObjectExpression": "first", + "ImportDeclaration": "first", + "flatTernaryExpressions": false, + "offsetTernaryExpressions": true, + "ignoreComments": false + }], + "jsx-quotes": ["warn", "prefer-double"], + "key-spacing": ["warn", { + "beforeColon": false, + "afterColon": true, + "mode": "strict" , + "align": "value" + }], + "keyword-spacing": "warn", + "linebreak-style": ["warn", "unix"], + "lines-around-comment": ["warn", { + "beforeBlockComment": true, + "afterBlockComment": true, + "beforeLineComment": true, + "afterLineComment": false + }], + "lines-between-class-members": ["warn", "always"], + "max-depth": ["warn", 4], + "max-len": ["warn", { "code": 85 }], + "max-lines-per-function": ["warn", { + "max": 100, + "skipBlankLines": true, + "skipComments": true + }], + "max-nested-callbacks": ["warn", 3], + "max-params": ["warn", 6], + "max-statements-per-line": ["warn", { "max": 2 }], + "multiline-comment-style": ["warn", "bare-block"], + "multiline-ternary": ["warn", "always-multiline"], + "newline-per-chained-call": ["warn", { "ignoreChainWithDepth": 3 }], + "no-lonely-if": "warn", + "no-mixed-spaces-and-tabs": "warn", + "no-multi-assign": "warn", + "no-multiple-empty-lines": ["warn", { "max": 1 }], + "no-negated-condition": "warn", + "no-nested-ternary": "warn", + "no-new-object": "error", + "no-tabs": "warn", + "no-trailing-spaces": "warn", + "no-unneeded-ternary": "warn", + "no-whitespace-before-property": "warn", + "nonblock-statement-body-position": ["warn", "below"], + "object-curly-newline": ["warn", { + "ObjectExpression": { "multiline": true, "minProperties": 4 }, + "ObjectPattern": { "multiline": true, "minProperties": 4 }, + "ImportDeclaration": { "multiline": true, "minProperties": 4 }, + "ExportDeclaration": { "multiline": true, "minProperties": 4 } + }], + "object-curly-spacing": ["warn", "always"], + "object-property-newline": "warn", + "one-var": ["warn", { "initialized": "never" }], + "one-var-declaration-per-line": ["warn", "initializations"], + "operator-assignment": ["warn", "always"], + "operator-linebreak": ["warn", "before"], + "padded-blocks": ["warn", "never", { "allowSingleLineBlocks": true } ], + "prefer-exponentiation-operator": "warn", + "prefer-object-spread": "warn", + "quote-props": ["warn", "as-needed"], + "quotes": ["warn", "double"], + "semi": ["warn", "always"], + "semi-spacing": ["warn", {"before": false, "after": true}], + "semi-style": ["warn", "last"], + "space-before-blocks": "warn", + "space-before-function-paren": ["warn", {"anonymous": "always", "named": "never", "asyncArrow": "always"}], + "space-in-parens": ["warn", "never"], + "space-infix-ops": "warn", + "space-unary-ops": [ "warn", {"words": true, "nonwords": false}], + "spaced-comment": ["warn", "never"], + "switch-colon-spacing": "warn", + "template-tag-spacing": "warn", + "wrap-regex": "warn", + + "arrow-body-style": ["warn", "as-needed"], + "arrow-parens": ["warn", "always"], + "arrow-spacing": "warn", + "constructor-super": "error", + "generator-star-spacing": ["warn", "before"], + "no-class-assign": "error", + "no-confusing-arrow": "warn", + "no-const-assign": "error", + "no-duplicate-imports": ["error", { "includeExports": true }], + "no-new-symbol": "error", + "no-useless-computed-key": "warn", + "no-useless-constructor": "error", + "no-useless-rename": "warn", + "no-var": "warn", + "prefer-arrow-callback": "warn", + "prefer-const": "warn", + "prefer-numeric-literals": "warn", + "prefer-rest-params": "error", + "prefer-spread": "warn", + "prefer-template": "warn", + "require-yield": "error", + "rest-spread-spacing": ["warn", "never"], + "symbol-description": "error", + "template-curly-spacing": "warn", + "yield-star-spacing": ["warn", "before"], + + "react/no-array-index-key": "error", + "react/no-deprecated": "error", + "react/self-closing-comp": ["warn", { + "component": true, + "html": true + }], + + "react/jsx-child-element-spacing": "warn", + "react/jsx-closing-bracket-location": "warn", + "react/jsx-closing-tag-location": "warn", + "react/jsx-curly-brace-presence": "warn", + "react/jsx-curly-newline": "warn", + "react/jsx-curly-spacing": "warn", + "react/jsx-equals-spacing": ["warn", "never"], + "react/jsx-filename-extension": ["warn", { "extensions": [".tsx", ".jsx", ".js"] }], + "react/jsx-first-prop-new-line": ["warn", "multiline"], + "react/jsx-fragments": ["warn", "syntax"], + "react/jsx-indent": ["warn", 2, { + "checkAttributes": true, + "indentLogicalExpressions": true + }], + "react/jsx-indent-props": ["warn", 2], + "react/jsx-key": ["warn", { "checkFragmentShorthand": true }], + "react/jsx-max-depth": ["warn", { "max": 5 }], + "react/jsx-max-props-per-line": ["warn", { + "maximum": 1, + "when": "multiline" + }], + "react/jsx-no-comment-textnodes": "warn", + "react/jsx-no-duplicate-props": "error", + "react/jsx-no-script-url": "error", + "react/jsx-no-undef": "warn", + "react/jsx-one-expression-per-line": ["warn", { "allow": "single-child" }], + "react/jsx-pascal-case": "warn", + "react/jsx-props-no-multi-spaces": "warn", + "react/jsx-tag-spacing": ["warn", { + "beforeSelfClosing": "never", + "closingSlash": "never", + "afterOpening": "never", + "beforeClosing": "never" + }], + "react/jsx-uses-react": "error", + "react/jsx-uses-vars": "error", + "react/prop-types": "off", + + "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }] + }, + "overrides": [ + { + "files": ["*.jsx", "*.js"], + "rules": { + "@typescript-eslint/explicit-module-boundary-types": "off" + } + } + ] +} diff --git a/semana17/LabenuSystem/.gitignore b/semana17/LabenuSystem/.gitignore new file mode 100644 index 0000000..853f700 --- /dev/null +++ b/semana17/LabenuSystem/.gitignore @@ -0,0 +1,5 @@ +node_module +build +.env +package-lock.json +yarn.lock diff --git a/semana17/LabenuSystem/package.json b/semana17/LabenuSystem/package.json new file mode 100644 index 0000000..3799173 --- /dev/null +++ b/semana17/LabenuSystem/package.json @@ -0,0 +1,26 @@ +{ + "name": "aula47", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "start": "npx tsc && node build/index.js", + "lint": "npx eslint --fix ./src" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "cors": "^2.8.5", + "dotenv": "^10.0.0", + "express": "^4.17.1", + "knex": "^0.95.7", + "mysql": "^2.18.1", + "yup": "^0.32.9" + }, + "devDependencies": { + "@types/cors": "^2.8.12", + "@types/express": "^4.17.13", + "@types/node": "^16.4.0" + } +} diff --git a/semana17/LabenuSystem/src/@types/index.d.ts b/semana17/LabenuSystem/src/@types/index.d.ts new file mode 100644 index 0000000..a2de643 --- /dev/null +++ b/semana17/LabenuSystem/src/@types/index.d.ts @@ -0,0 +1,123 @@ +import { Knex } from "knex"; + +export type ID = string; + +export interface Turma { + id: ID; + nome: string; + dataInicio: Date; + dataFinal: Date; + modulo: number; +} + +export interface TurmaDatabase { + id: ID; + nome: string; + data_inicio: Date; + data_final: Date; + modulo: number; +} + +export interface Estudante { + id: ID; + nome: string; + email: string; + dataDeNascimento: string; + turmaID: ID; +} + +export interface EstudanteDatabase { + id: ID; + nome: string; + email: string; + data_de_nascimento: string; + turma_id: ID; +} + +export interface Passatempo { + id: ID; + nome: string; +} + +export interface EstudantePassatempo { + estudanteID: ID; + passatempoID: ID; +} + +export interface EstudantePassatempoDatabase { + estudante_id: ID; + passatempo_id: ID; +} + +export type Professor = Estudante; + +export type ProfessorDatabase = EstudanteDatabase; + +export interface Especialidade { + id: ID; + nome: string; +} + +export interface ProfessorEspecialidade { + especialidadeID: ID; + professorID: ID; +} + +export interface ProfessorEspecialidadeDatabase { + especialidade_id: ID; + professor_id: ID; +} + +//Veja https://knexjs.org/#typescript-support +declare module "knex/types/tables" { + interface Tables { + LabenuSystem_Turma: TurmaDatabase; + LabenuSystem_Turma_composite: Knex.CompositeTableType< + TurmaDatabase, + TurmaDatabase, + Omit + >; + + LabenuSystem_Estudante: EstudanteDatabase; + LabenuSystem_Estudante_composite: Knex.CompositeTableType< + EstudanteDatabase, + EstudanteDatabase, + Omit + >; + + LabenuSystem_Passatempo: Passatempo; + LabenuSystem_Passatempo_composite: Knex.CompositeTableType< + Passatempo, + Passatempo, + Omit + >; + + LabenuSystem_Estudante_Passatempo: EstudantePassatempoDatabase; + LabenuSystem_Estudante_Passatempo_composite: Knex.CompositeTableType< + EstudantePassatempoDatabase, + EstudantePassatempoDatabase, + Omit + >; + + LabenuSystem_Professor: ProfessorDatabase; + LabenuSystem_Professor_composite: Knex.CompositeTableType< + ProfessorDatabase, + ProfessorDatabase, + Omit + >; + + LabenuSystem_Especialidade: Especialidade; + LabenuSystem_Especialidade_composite: Knex.CompositeTableType< + Especialidade, + Especialidade, + Omit + >; + + LabenuSystem_Professor_Especialidade: ProfessorEspecialidadeDatabase; + LabenuSystem_Professor_Especialidade_composite: Knex.CompositeTableType< + ProfessorEspecialidadeDatabase, + ProfessorEspecialidadeDatabase, + Omit + >; + } +} diff --git a/semana17/LabenuSystem/src/database/mysql/connection.ts b/semana17/LabenuSystem/src/database/mysql/connection.ts new file mode 100644 index 0000000..9a2cb91 --- /dev/null +++ b/semana17/LabenuSystem/src/database/mysql/connection.ts @@ -0,0 +1,13 @@ +import { knex } from "knex"; + +export const connection = knex({ + client: process.env.DATABASE_TYPE, + connection: { + host: process.env.DATABASE_HOST, + port: Number(process.env.DATABASE_PORT), + database: process.env.DATABASE_SCHEMA, + user: process.env.DATABASE_USER, + password: process.env.DATABASE_PASSWORD, + multipleStatements: true + } +}); diff --git a/semana17/LabenuSystem/src/env.ts b/semana17/LabenuSystem/src/env.ts new file mode 100644 index 0000000..7ff27f7 --- /dev/null +++ b/semana17/LabenuSystem/src/env.ts @@ -0,0 +1,2 @@ +import dotenv from "dotenv"; +dotenv.config(); diff --git a/semana17/LabenuSystem/src/index.ts b/semana17/LabenuSystem/src/index.ts new file mode 100644 index 0000000..cfe5501 --- /dev/null +++ b/semana17/LabenuSystem/src/index.ts @@ -0,0 +1,19 @@ +import "./env"; +import express from "express"; +import cors from "cors"; + +const serverPort = process.env.NODE_PORT || 3003; + +const server = express(); +server.use(express.json()); +server.use(cors()); + +const serverListener = server.listen(serverPort, () => { + if (serverListener) + //eslint-disable-next-line no-console + console.log(`Server is running in http://localhost:${serverPort}`); + else + //eslint-disable-next-line no-console + console.error("Failure upon starting server."); +}); + diff --git a/semana17/LabenuSystem/src/queries.sql b/semana17/LabenuSystem/src/queries.sql new file mode 100644 index 0000000..bdf744d --- /dev/null +++ b/semana17/LabenuSystem/src/queries.sql @@ -0,0 +1,75 @@ + +SHOW DATABASES; + +SHOW TABLES; + +SELECT * FROM information_schema.columns WHERE TABLE_NAME LIKE "LabenuSystem%"; + +SELECT TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT, COLUMN_TYPE, COLUMN_KEY FROM information_schema.columns WHERE TABLE_NAME LIKE "LabenuSystem%"; + +DROP TABLE LabenuSystem_Professor_Especialidade; + +DROP TABLE LabenuSystem_Estudante_Passatempo; + +DROP TABLE LabenuSystem_Especialidade; + +DROP TABLE LabenuSystem_Passatempo; + +DROP TABLE LabenuSystem_Professor; + +DROP TABLE LabenuSystem_Estudante; + +DROP TABLE LabenuSystem_Turma; + +CREATE TABLE LabenuSystem_Turma ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome VARCHAR(255) UNIQUE NOT NULL, + data_inicio DATE NOT NULL, + data_final DATE NOT NULL, + modulo TINYINT UNSIGNED NOT NULL DEFAULT 0, + tipo ENUM("Integral", "Noturno") NOT NULL +); + +CREATE TABLE LabenuSystem_Estudante ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome VARCHAR(255) NOT NULL, + email VARCHAR(255) UNIQUE NOT NULL, + data_de_nascimento DATE NOT NULL, + turma_id CHAR(36) NOT NULL, + FOREIGN KEY (turma_id) REFERENCES LabenuSystem_Turma(id) +); + +CREATE TABLE LabenuSystem_Passatempo ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome VARCHAR(255) UNIQUE NOT NULL +); + +CREATE TABLE LabenuSystem_Estudante_Passatempo ( + estudante_id CHAR(36) NOT NULL, + passatempo_id CHAR(36) NOT NULL, + FOREIGN KEY (estudante_id) REFERENCES LabenuSystem_Estudante(id), + FOREIGN KEY (passatempo_id) REFERENCES LabenuSystem_Passatempo(id) +); + +CREATE TABLE LabenuSystem_Professor ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome VARCHAR(255) NOT NULL, + email VARCHAR(255) UNIQUE NOT NULL, + data_de_nascimento DATE NOT NULL, + turma_id CHAR(36) NOT NULL, + FOREIGN KEY (turma_id) REFERENCES LabenuSystem_Turma(id) +); + +CREATE TABLE LabenuSystem_Especialidade ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome ENUM("React", "Redux", "CSS", "Testes", "Typescript", "POO", "Backend") + NOT NULL +); + +CREATE TABLE LabenuSystem_Professor_Especialidade ( + especialidade_id CHAR(36) NOT NULL, + professor_id CHAR(36) NOT NULL, + FOREIGN KEY (especialidade_id) REFERENCES LabenuSystem_Especialidade(id), + FOREIGN KEY (professor_id) REFERENCES LabenuSystem_Professor(id) +); + diff --git a/semana17/LabenuSystem/tsconfig.json b/semana17/LabenuSystem/tsconfig.json new file mode 100644 index 0000000..cd88c2c --- /dev/null +++ b/semana17/LabenuSystem/tsconfig.json @@ -0,0 +1,73 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Basic Options */ + // "incremental": true, /* Enable incremental compilation */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./build", /* Redirect output structure to the directory. */ + "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + "noUnusedLocals": true, /* Report errors on unused locals. */ + "noUnusedParameters": true, /* Report errors on unused parameters. */ + "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ + "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ + // "nPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + "typeRoots": ["./nodemodules/@types", "./src/@types"], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + + /* Advanced Options */ + "skipLibCheck": true, /* Skip type checking of declaration files. */ + "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ + "resolveJsonModule": true + } +} From 5869bbfb357c7dc92c965f51cc458a548048ea3e Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Wed, 28 Jul 2021 20:54:12 -0400 Subject: [PATCH 02/29] Inicializando o projeto --- .eslintrc.json | 252 +++++++++++++++++++++++++++++++ .gitignore | 5 + package.json | 26 ++++ src/@types/index.d.ts | 123 +++++++++++++++ src/database/mysql/connection.ts | 13 ++ src/env.ts | 2 + src/index.ts | 19 +++ src/queries.sql | 75 +++++++++ tsconfig.json | 73 +++++++++ 9 files changed, 588 insertions(+) create mode 100644 .eslintrc.json create mode 100644 .gitignore create mode 100644 package.json create mode 100644 src/@types/index.d.ts create mode 100644 src/database/mysql/connection.ts create mode 100644 src/env.ts create mode 100644 src/index.ts create mode 100644 src/queries.sql create mode 100644 tsconfig.json diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..c6cf55d --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,252 @@ +{ + "root": true, + "env": { + "browser": true, + "es2020": true, + "node": true + }, + "extends": [ + "eslint:recommended", + "plugin:react/recommended", + "plugin:@typescript-eslint/recommended", + "plugin:react-hooks/recommended" + ], + "settings": { + "react": { + "version": "detect" + } + }, + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaFeatures": { + "jsx": true + }, + "ecmaVersion": 11, + "sourceType": "module" + }, + "plugins": ["react", "@typescript-eslint", "react-hooks"], + "rules": { + "no-cond-assign": ["error", "always"], + "no-console": "warn", + "no-constant-condition": "error", + "no-debugger": "error", + "no-dupe-else-if": "error", + "no-dupe-keys": "error", + "no-duplicate-case": "error", + "no-empty": "warn", + "no-empty-character-class": "error", + "no-extra-boolean-cast": "warn", + "no-extra-parens": "off", + "@typescript-eslint/no-extra-parens": ["warn", "all", { "ignoreJSX": "multi-line" }], + "no-extra-semi": "warn", + "no-func-assign": "warn", + "no-import-assign": "warn", + "no-inner-declarations": ["warn", "both"], + "no-invalid-regexp": "error", + "no-irregular-whitespace": ["warn", { + "skipRegExps": true, + "skipTemplates": true + }], + "no-loss-of-precision": "warn", + "no-misleading-character-class": "warn", + "no-obj-calls": "warn", + "no-prototype-builtins": "error", + "no-sparse-arrays": "error", + "no-template-curly-in-string": "warn", + "no-unexpected-multiline": "warn", + "no-unreachable": "error", + "no-unreachable-loop": "error", + "no-unsafe-finally": "error", + "no-unsafe-negation": "error", + "use-isnan": "warn", + "valid-typeof": "error", + + "curly": ["warn", "multi", "consistent"], + "no-empty-function": "warn", + + "array-bracket-newline": ["warn", { "multiline": true }], + "array-bracket-spacing": ["warn", "always"], + "array-element-newline": ["warn", { "multiline": true, "minItems": 3 }], + "block-spacing": "warn", + "brace-style": ["warn", "1tbs", { "allowSingleLine": true }], + "capitalized-comments": "warn", + "camelcase": "off", + "comma-dangle": ["warn", "never"], + "comma-spacing": ["warn", { "before": false, "after": true }], + "comma-style": ["warn", "last"], + "computed-property-spacing": "warn", + "eol-last": ["warn", "always"], + "func-call-spacing": ["error", "never"], + "func-names": ["error", "always"], + "func-style": ["error", "declaration", { "allowArrowFunctions": true }], + "function-call-argument-newline": ["warn", "consistent"], + "function-paren-newline": ["warn", "multiline"], + "id-length": ["warn", { "min": 3, "exceptions": ["id", "_"] }], + "implicit-arrow-linebreak": ["warn", "beside"], + "indent": ["warn", 2, { + "SwitchCase": 1, + "VariableDeclarator": "first", + "MemberExpression": 1, + "FunctionDeclaration": {"parameters": "first"}, + "FunctionExpression": {"parameters": "first"}, + "CallExpression": {"arguments": "first"}, + "ArrayExpression": "first", + "ObjectExpression": "first", + "ImportDeclaration": "first", + "flatTernaryExpressions": false, + "offsetTernaryExpressions": true, + "ignoreComments": false + }], + "jsx-quotes": ["warn", "prefer-double"], + "key-spacing": ["warn", { + "beforeColon": false, + "afterColon": true, + "mode": "strict" , + "align": "value" + }], + "keyword-spacing": "warn", + "linebreak-style": ["warn", "unix"], + "lines-around-comment": ["warn", { + "beforeBlockComment": true, + "afterBlockComment": true, + "beforeLineComment": true, + "afterLineComment": false + }], + "lines-between-class-members": ["warn", "always"], + "max-depth": ["warn", 4], + "max-len": ["warn", { "code": 85 }], + "max-lines-per-function": ["warn", { + "max": 100, + "skipBlankLines": true, + "skipComments": true + }], + "max-nested-callbacks": ["warn", 3], + "max-params": ["warn", 6], + "max-statements-per-line": ["warn", { "max": 2 }], + "multiline-comment-style": ["warn", "bare-block"], + "multiline-ternary": ["warn", "always-multiline"], + "newline-per-chained-call": ["warn", { "ignoreChainWithDepth": 3 }], + "no-lonely-if": "warn", + "no-mixed-spaces-and-tabs": "warn", + "no-multi-assign": "warn", + "no-multiple-empty-lines": ["warn", { "max": 1 }], + "no-negated-condition": "warn", + "no-nested-ternary": "warn", + "no-new-object": "error", + "no-tabs": "warn", + "no-trailing-spaces": "warn", + "no-unneeded-ternary": "warn", + "no-whitespace-before-property": "warn", + "nonblock-statement-body-position": ["warn", "below"], + "object-curly-newline": ["warn", { + "ObjectExpression": { "multiline": true, "minProperties": 4 }, + "ObjectPattern": { "multiline": true, "minProperties": 4 }, + "ImportDeclaration": { "multiline": true, "minProperties": 4 }, + "ExportDeclaration": { "multiline": true, "minProperties": 4 } + }], + "object-curly-spacing": ["warn", "always"], + "object-property-newline": "warn", + "one-var": ["warn", { "initialized": "never" }], + "one-var-declaration-per-line": ["warn", "initializations"], + "operator-assignment": ["warn", "always"], + "operator-linebreak": ["warn", "before"], + "padded-blocks": ["warn", "never", { "allowSingleLineBlocks": true } ], + "prefer-exponentiation-operator": "warn", + "prefer-object-spread": "warn", + "quote-props": ["warn", "as-needed"], + "quotes": ["warn", "double"], + "semi": ["warn", "always"], + "semi-spacing": ["warn", {"before": false, "after": true}], + "semi-style": ["warn", "last"], + "space-before-blocks": "warn", + "space-before-function-paren": ["warn", {"anonymous": "always", "named": "never", "asyncArrow": "always"}], + "space-in-parens": ["warn", "never"], + "space-infix-ops": "warn", + "space-unary-ops": [ "warn", {"words": true, "nonwords": false}], + "spaced-comment": ["warn", "never"], + "switch-colon-spacing": "warn", + "template-tag-spacing": "warn", + "wrap-regex": "warn", + + "arrow-body-style": ["warn", "as-needed"], + "arrow-parens": ["warn", "always"], + "arrow-spacing": "warn", + "constructor-super": "error", + "generator-star-spacing": ["warn", "before"], + "no-class-assign": "error", + "no-confusing-arrow": "warn", + "no-const-assign": "error", + "no-duplicate-imports": ["error", { "includeExports": true }], + "no-new-symbol": "error", + "no-useless-computed-key": "warn", + "no-useless-constructor": "error", + "no-useless-rename": "warn", + "no-var": "warn", + "prefer-arrow-callback": "warn", + "prefer-const": "warn", + "prefer-numeric-literals": "warn", + "prefer-rest-params": "error", + "prefer-spread": "warn", + "prefer-template": "warn", + "require-yield": "error", + "rest-spread-spacing": ["warn", "never"], + "symbol-description": "error", + "template-curly-spacing": "warn", + "yield-star-spacing": ["warn", "before"], + + "react/no-array-index-key": "error", + "react/no-deprecated": "error", + "react/self-closing-comp": ["warn", { + "component": true, + "html": true + }], + + "react/jsx-child-element-spacing": "warn", + "react/jsx-closing-bracket-location": "warn", + "react/jsx-closing-tag-location": "warn", + "react/jsx-curly-brace-presence": "warn", + "react/jsx-curly-newline": "warn", + "react/jsx-curly-spacing": "warn", + "react/jsx-equals-spacing": ["warn", "never"], + "react/jsx-filename-extension": ["warn", { "extensions": [".tsx", ".jsx", ".js"] }], + "react/jsx-first-prop-new-line": ["warn", "multiline"], + "react/jsx-fragments": ["warn", "syntax"], + "react/jsx-indent": ["warn", 2, { + "checkAttributes": true, + "indentLogicalExpressions": true + }], + "react/jsx-indent-props": ["warn", 2], + "react/jsx-key": ["warn", { "checkFragmentShorthand": true }], + "react/jsx-max-depth": ["warn", { "max": 5 }], + "react/jsx-max-props-per-line": ["warn", { + "maximum": 1, + "when": "multiline" + }], + "react/jsx-no-comment-textnodes": "warn", + "react/jsx-no-duplicate-props": "error", + "react/jsx-no-script-url": "error", + "react/jsx-no-undef": "warn", + "react/jsx-one-expression-per-line": ["warn", { "allow": "single-child" }], + "react/jsx-pascal-case": "warn", + "react/jsx-props-no-multi-spaces": "warn", + "react/jsx-tag-spacing": ["warn", { + "beforeSelfClosing": "never", + "closingSlash": "never", + "afterOpening": "never", + "beforeClosing": "never" + }], + "react/jsx-uses-react": "error", + "react/jsx-uses-vars": "error", + "react/prop-types": "off", + + "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }] + }, + "overrides": [ + { + "files": ["*.jsx", "*.js"], + "rules": { + "@typescript-eslint/explicit-module-boundary-types": "off" + } + } + ] +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..853f700 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_module +build +.env +package-lock.json +yarn.lock diff --git a/package.json b/package.json new file mode 100644 index 0000000..3799173 --- /dev/null +++ b/package.json @@ -0,0 +1,26 @@ +{ + "name": "aula47", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "start": "npx tsc && node build/index.js", + "lint": "npx eslint --fix ./src" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "cors": "^2.8.5", + "dotenv": "^10.0.0", + "express": "^4.17.1", + "knex": "^0.95.7", + "mysql": "^2.18.1", + "yup": "^0.32.9" + }, + "devDependencies": { + "@types/cors": "^2.8.12", + "@types/express": "^4.17.13", + "@types/node": "^16.4.0" + } +} diff --git a/src/@types/index.d.ts b/src/@types/index.d.ts new file mode 100644 index 0000000..a2de643 --- /dev/null +++ b/src/@types/index.d.ts @@ -0,0 +1,123 @@ +import { Knex } from "knex"; + +export type ID = string; + +export interface Turma { + id: ID; + nome: string; + dataInicio: Date; + dataFinal: Date; + modulo: number; +} + +export interface TurmaDatabase { + id: ID; + nome: string; + data_inicio: Date; + data_final: Date; + modulo: number; +} + +export interface Estudante { + id: ID; + nome: string; + email: string; + dataDeNascimento: string; + turmaID: ID; +} + +export interface EstudanteDatabase { + id: ID; + nome: string; + email: string; + data_de_nascimento: string; + turma_id: ID; +} + +export interface Passatempo { + id: ID; + nome: string; +} + +export interface EstudantePassatempo { + estudanteID: ID; + passatempoID: ID; +} + +export interface EstudantePassatempoDatabase { + estudante_id: ID; + passatempo_id: ID; +} + +export type Professor = Estudante; + +export type ProfessorDatabase = EstudanteDatabase; + +export interface Especialidade { + id: ID; + nome: string; +} + +export interface ProfessorEspecialidade { + especialidadeID: ID; + professorID: ID; +} + +export interface ProfessorEspecialidadeDatabase { + especialidade_id: ID; + professor_id: ID; +} + +//Veja https://knexjs.org/#typescript-support +declare module "knex/types/tables" { + interface Tables { + LabenuSystem_Turma: TurmaDatabase; + LabenuSystem_Turma_composite: Knex.CompositeTableType< + TurmaDatabase, + TurmaDatabase, + Omit + >; + + LabenuSystem_Estudante: EstudanteDatabase; + LabenuSystem_Estudante_composite: Knex.CompositeTableType< + EstudanteDatabase, + EstudanteDatabase, + Omit + >; + + LabenuSystem_Passatempo: Passatempo; + LabenuSystem_Passatempo_composite: Knex.CompositeTableType< + Passatempo, + Passatempo, + Omit + >; + + LabenuSystem_Estudante_Passatempo: EstudantePassatempoDatabase; + LabenuSystem_Estudante_Passatempo_composite: Knex.CompositeTableType< + EstudantePassatempoDatabase, + EstudantePassatempoDatabase, + Omit + >; + + LabenuSystem_Professor: ProfessorDatabase; + LabenuSystem_Professor_composite: Knex.CompositeTableType< + ProfessorDatabase, + ProfessorDatabase, + Omit + >; + + LabenuSystem_Especialidade: Especialidade; + LabenuSystem_Especialidade_composite: Knex.CompositeTableType< + Especialidade, + Especialidade, + Omit + >; + + LabenuSystem_Professor_Especialidade: ProfessorEspecialidadeDatabase; + LabenuSystem_Professor_Especialidade_composite: Knex.CompositeTableType< + ProfessorEspecialidadeDatabase, + ProfessorEspecialidadeDatabase, + Omit + >; + } +} diff --git a/src/database/mysql/connection.ts b/src/database/mysql/connection.ts new file mode 100644 index 0000000..9a2cb91 --- /dev/null +++ b/src/database/mysql/connection.ts @@ -0,0 +1,13 @@ +import { knex } from "knex"; + +export const connection = knex({ + client: process.env.DATABASE_TYPE, + connection: { + host: process.env.DATABASE_HOST, + port: Number(process.env.DATABASE_PORT), + database: process.env.DATABASE_SCHEMA, + user: process.env.DATABASE_USER, + password: process.env.DATABASE_PASSWORD, + multipleStatements: true + } +}); diff --git a/src/env.ts b/src/env.ts new file mode 100644 index 0000000..7ff27f7 --- /dev/null +++ b/src/env.ts @@ -0,0 +1,2 @@ +import dotenv from "dotenv"; +dotenv.config(); diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..cfe5501 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,19 @@ +import "./env"; +import express from "express"; +import cors from "cors"; + +const serverPort = process.env.NODE_PORT || 3003; + +const server = express(); +server.use(express.json()); +server.use(cors()); + +const serverListener = server.listen(serverPort, () => { + if (serverListener) + //eslint-disable-next-line no-console + console.log(`Server is running in http://localhost:${serverPort}`); + else + //eslint-disable-next-line no-console + console.error("Failure upon starting server."); +}); + diff --git a/src/queries.sql b/src/queries.sql new file mode 100644 index 0000000..bdf744d --- /dev/null +++ b/src/queries.sql @@ -0,0 +1,75 @@ + +SHOW DATABASES; + +SHOW TABLES; + +SELECT * FROM information_schema.columns WHERE TABLE_NAME LIKE "LabenuSystem%"; + +SELECT TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT, COLUMN_TYPE, COLUMN_KEY FROM information_schema.columns WHERE TABLE_NAME LIKE "LabenuSystem%"; + +DROP TABLE LabenuSystem_Professor_Especialidade; + +DROP TABLE LabenuSystem_Estudante_Passatempo; + +DROP TABLE LabenuSystem_Especialidade; + +DROP TABLE LabenuSystem_Passatempo; + +DROP TABLE LabenuSystem_Professor; + +DROP TABLE LabenuSystem_Estudante; + +DROP TABLE LabenuSystem_Turma; + +CREATE TABLE LabenuSystem_Turma ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome VARCHAR(255) UNIQUE NOT NULL, + data_inicio DATE NOT NULL, + data_final DATE NOT NULL, + modulo TINYINT UNSIGNED NOT NULL DEFAULT 0, + tipo ENUM("Integral", "Noturno") NOT NULL +); + +CREATE TABLE LabenuSystem_Estudante ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome VARCHAR(255) NOT NULL, + email VARCHAR(255) UNIQUE NOT NULL, + data_de_nascimento DATE NOT NULL, + turma_id CHAR(36) NOT NULL, + FOREIGN KEY (turma_id) REFERENCES LabenuSystem_Turma(id) +); + +CREATE TABLE LabenuSystem_Passatempo ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome VARCHAR(255) UNIQUE NOT NULL +); + +CREATE TABLE LabenuSystem_Estudante_Passatempo ( + estudante_id CHAR(36) NOT NULL, + passatempo_id CHAR(36) NOT NULL, + FOREIGN KEY (estudante_id) REFERENCES LabenuSystem_Estudante(id), + FOREIGN KEY (passatempo_id) REFERENCES LabenuSystem_Passatempo(id) +); + +CREATE TABLE LabenuSystem_Professor ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome VARCHAR(255) NOT NULL, + email VARCHAR(255) UNIQUE NOT NULL, + data_de_nascimento DATE NOT NULL, + turma_id CHAR(36) NOT NULL, + FOREIGN KEY (turma_id) REFERENCES LabenuSystem_Turma(id) +); + +CREATE TABLE LabenuSystem_Especialidade ( + id CHAR(36) PRIMARY KEY NOT NULL, + nome ENUM("React", "Redux", "CSS", "Testes", "Typescript", "POO", "Backend") + NOT NULL +); + +CREATE TABLE LabenuSystem_Professor_Especialidade ( + especialidade_id CHAR(36) NOT NULL, + professor_id CHAR(36) NOT NULL, + FOREIGN KEY (especialidade_id) REFERENCES LabenuSystem_Especialidade(id), + FOREIGN KEY (professor_id) REFERENCES LabenuSystem_Professor(id) +); + diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..cd88c2c --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,73 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Basic Options */ + // "incremental": true, /* Enable incremental compilation */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./build", /* Redirect output structure to the directory. */ + "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + "noUnusedLocals": true, /* Report errors on unused locals. */ + "noUnusedParameters": true, /* Report errors on unused parameters. */ + "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ + "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ + // "nPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + "typeRoots": ["./nodemodules/@types", "./src/@types"], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + + /* Advanced Options */ + "skipLibCheck": true, /* Skip type checking of declaration files. */ + "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ + "resolveJsonModule": true + } +} From 2a3e1632daa5fea4bb53d101347bf851579301e8 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 13:42:15 -0400 Subject: [PATCH 03/29] Adicionando a funcionalidade de criar turma --- semana17/LabenuSystem/package.json | 4 +- semana17/LabenuSystem/src/@types/index.d.ts | 6 ++- .../LabenuSystem/src/database/mysql/index.ts | 1 + .../LabenuSystem/src/database/mysql/turma.ts | 21 ++++++++ .../LabenuSystem/src/handlers/turma/index.ts | 53 +++++++++++++++++++ semana17/LabenuSystem/src/index.ts | 3 ++ semana17/LabenuSystem/src/queries.sql | 5 ++ semana17/LabenuSystem/src/validate/index.ts | 27 ++++++++++ 8 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 semana17/LabenuSystem/src/database/mysql/index.ts create mode 100644 semana17/LabenuSystem/src/database/mysql/turma.ts create mode 100644 semana17/LabenuSystem/src/handlers/turma/index.ts create mode 100644 semana17/LabenuSystem/src/validate/index.ts diff --git a/semana17/LabenuSystem/package.json b/semana17/LabenuSystem/package.json index 3799173..98319ca 100644 --- a/semana17/LabenuSystem/package.json +++ b/semana17/LabenuSystem/package.json @@ -16,11 +16,13 @@ "express": "^4.17.1", "knex": "^0.95.7", "mysql": "^2.18.1", + "uuid": "^8.3.2", "yup": "^0.32.9" }, "devDependencies": { "@types/cors": "^2.8.12", "@types/express": "^4.17.13", - "@types/node": "^16.4.0" + "@types/node": "^16.4.0", + "@types/uuid": "^8.3.1" } } diff --git a/semana17/LabenuSystem/src/@types/index.d.ts b/semana17/LabenuSystem/src/@types/index.d.ts index a2de643..f83ee1d 100644 --- a/semana17/LabenuSystem/src/@types/index.d.ts +++ b/semana17/LabenuSystem/src/@types/index.d.ts @@ -5,17 +5,19 @@ export type ID = string; export interface Turma { id: ID; nome: string; + modulo: number; dataInicio: Date; dataFinal: Date; - modulo: number; + tipo: "Integral" | "Noturno"; } export interface TurmaDatabase { id: ID; nome: string; + modulo: number; data_inicio: Date; data_final: Date; - modulo: number; + tipo: "Integral" | "Noturno"; } export interface Estudante { diff --git a/semana17/LabenuSystem/src/database/mysql/index.ts b/semana17/LabenuSystem/src/database/mysql/index.ts new file mode 100644 index 0000000..f2e32c8 --- /dev/null +++ b/semana17/LabenuSystem/src/database/mysql/index.ts @@ -0,0 +1 @@ +export * from "./turma"; diff --git a/semana17/LabenuSystem/src/database/mysql/turma.ts b/semana17/LabenuSystem/src/database/mysql/turma.ts new file mode 100644 index 0000000..d7e61bd --- /dev/null +++ b/semana17/LabenuSystem/src/database/mysql/turma.ts @@ -0,0 +1,21 @@ +import { v1 as uuidV1 } from "uuid"; +import { connection } from "./connection"; +import { Turma, TurmaDatabase } from "../../@types"; + +export async function criarTurma(turma: Omit): Promise { + const turmaNova: TurmaDatabase = { + id: uuidV1(), + nome: turma.nome, + data_final: turma.dataFinal, + data_inicio: turma.dataInicio, + modulo: turma.modulo, + tipo: turma.tipo + }; + + await connection("LabenuSystem_Turma").insert(turmaNova); + + return { + ...turma, + id: turmaNova.id + }; +} diff --git a/semana17/LabenuSystem/src/handlers/turma/index.ts b/semana17/LabenuSystem/src/handlers/turma/index.ts new file mode 100644 index 0000000..19fbae9 --- /dev/null +++ b/semana17/LabenuSystem/src/handlers/turma/index.ts @@ -0,0 +1,53 @@ +import express, { Request, Response } from "express"; +import { turmaSchemaWithoutID } from "../../validate"; +import { criarTurma as criarTurmaDatabase } from "../../database/mysql"; + +const erros = { + inesperado: "Aconteceu um erro inesperado", + nomeExiste: "Nome da turma já existe" +}; + +export const turmaRouter = express.Router(); + +turmaRouter.post("/", criarTurma); + +const PADRAO_TIPO = "Integral"; + +async function criarTurma(request: Request, response: Response): Promise { + const { + nome, + dataInicio, + dataFinal, + modulo, + tipo + } = request.body; + + const turma = { + nome, + dataInicio, + dataFinal, + modulo, + tipo: tipo || PADRAO_TIPO + }; + + try { + await turmaSchemaWithoutID.validate(turma, { abortEarly: false }); + + const turmaNova = await criarTurmaDatabase(turma); + + response.send(turmaNova); + } catch (error) { + if (error.name === "ValidationError") { + response.status(400).send(error.errors); + return; + } + + if (error.code === "ER_DUP_ENTRY") { + response.status(409).send(erros.nomeExiste); + return; + } + + response.status(500).send(erros.inesperado); + } +} + diff --git a/semana17/LabenuSystem/src/index.ts b/semana17/LabenuSystem/src/index.ts index cfe5501..be64fe3 100644 --- a/semana17/LabenuSystem/src/index.ts +++ b/semana17/LabenuSystem/src/index.ts @@ -1,6 +1,7 @@ import "./env"; import express from "express"; import cors from "cors"; +import { turmaRouter } from "./handlers/turma"; const serverPort = process.env.NODE_PORT || 3003; @@ -8,6 +9,8 @@ const server = express(); server.use(express.json()); server.use(cors()); +server.use("/turma", turmaRouter); + const serverListener = server.listen(serverPort, () => { if (serverListener) //eslint-disable-next-line no-console diff --git a/semana17/LabenuSystem/src/queries.sql b/semana17/LabenuSystem/src/queries.sql index bdf744d..20ea631 100644 --- a/semana17/LabenuSystem/src/queries.sql +++ b/semana17/LabenuSystem/src/queries.sql @@ -7,6 +7,11 @@ SELECT * FROM information_schema.columns WHERE TABLE_NAME LIKE "LabenuSystem%"; SELECT TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT, COLUMN_TYPE, COLUMN_KEY FROM information_schema.columns WHERE TABLE_NAME LIKE "LabenuSystem%"; +SELECT * FROM LabenuSystem_Turma; + +INSERT INTO LabenuSystem_Turma (id, nome, data_inicio, data_final, modulo, tipo) +VALUES ("00000000-0000-0000-0000-000000000000", "Turma Zero", "2017-01-01", "9999-12-31", "0", "Integral"); + DROP TABLE LabenuSystem_Professor_Especialidade; DROP TABLE LabenuSystem_Estudante_Passatempo; diff --git a/semana17/LabenuSystem/src/validate/index.ts b/semana17/LabenuSystem/src/validate/index.ts new file mode 100644 index 0000000..d6877c5 --- /dev/null +++ b/semana17/LabenuSystem/src/validate/index.ts @@ -0,0 +1,27 @@ +import * as yup from "yup"; +import { Turma } from "../@types"; + +const MIN_CARACTER = 6; +const MAX_CARACTER = 255; + +const MIN_MODULO = 0; +const MAX_MODULO = 7; + +//@ts-expect-error issue an yup https://github.com/jquense/yup/issues/1183 +export const turmaSchema: yup.SchemaOf = yup.object({ + id: yup.string().uuid().defined(), + nome: yup.string() + .min(MIN_CARACTER) + .max(MAX_CARACTER) + .defined(), + modulo: yup.number() + .min(MIN_MODULO) + .max(MAX_MODULO) + .defined(), + dataFinal: yup.date().defined(), + dataInicio: yup.date().defined(), + tipo: yup.mixed().oneOf([ "Integral", "Noturno" ]).defined() +}); + +export const turmaSchemaWithoutID: yup.SchemaOf> + = turmaSchema.omit([ "id" ]); From c7241fc07e2501c38459114a6bbf1c94dfd6e4ea Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 13:42:15 -0400 Subject: [PATCH 04/29] Adicionando a funcionalidade de criar turma --- package.json | 4 ++- src/@types/index.d.ts | 6 +++-- src/database/mysql/index.ts | 1 + src/database/mysql/turma.ts | 21 +++++++++++++++ src/handlers/turma/index.ts | 53 +++++++++++++++++++++++++++++++++++++ src/index.ts | 3 +++ src/queries.sql | 5 ++++ src/validate/index.ts | 27 +++++++++++++++++++ 8 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 src/database/mysql/index.ts create mode 100644 src/database/mysql/turma.ts create mode 100644 src/handlers/turma/index.ts create mode 100644 src/validate/index.ts diff --git a/package.json b/package.json index 3799173..98319ca 100644 --- a/package.json +++ b/package.json @@ -16,11 +16,13 @@ "express": "^4.17.1", "knex": "^0.95.7", "mysql": "^2.18.1", + "uuid": "^8.3.2", "yup": "^0.32.9" }, "devDependencies": { "@types/cors": "^2.8.12", "@types/express": "^4.17.13", - "@types/node": "^16.4.0" + "@types/node": "^16.4.0", + "@types/uuid": "^8.3.1" } } diff --git a/src/@types/index.d.ts b/src/@types/index.d.ts index a2de643..f83ee1d 100644 --- a/src/@types/index.d.ts +++ b/src/@types/index.d.ts @@ -5,17 +5,19 @@ export type ID = string; export interface Turma { id: ID; nome: string; + modulo: number; dataInicio: Date; dataFinal: Date; - modulo: number; + tipo: "Integral" | "Noturno"; } export interface TurmaDatabase { id: ID; nome: string; + modulo: number; data_inicio: Date; data_final: Date; - modulo: number; + tipo: "Integral" | "Noturno"; } export interface Estudante { diff --git a/src/database/mysql/index.ts b/src/database/mysql/index.ts new file mode 100644 index 0000000..f2e32c8 --- /dev/null +++ b/src/database/mysql/index.ts @@ -0,0 +1 @@ +export * from "./turma"; diff --git a/src/database/mysql/turma.ts b/src/database/mysql/turma.ts new file mode 100644 index 0000000..d7e61bd --- /dev/null +++ b/src/database/mysql/turma.ts @@ -0,0 +1,21 @@ +import { v1 as uuidV1 } from "uuid"; +import { connection } from "./connection"; +import { Turma, TurmaDatabase } from "../../@types"; + +export async function criarTurma(turma: Omit): Promise { + const turmaNova: TurmaDatabase = { + id: uuidV1(), + nome: turma.nome, + data_final: turma.dataFinal, + data_inicio: turma.dataInicio, + modulo: turma.modulo, + tipo: turma.tipo + }; + + await connection("LabenuSystem_Turma").insert(turmaNova); + + return { + ...turma, + id: turmaNova.id + }; +} diff --git a/src/handlers/turma/index.ts b/src/handlers/turma/index.ts new file mode 100644 index 0000000..19fbae9 --- /dev/null +++ b/src/handlers/turma/index.ts @@ -0,0 +1,53 @@ +import express, { Request, Response } from "express"; +import { turmaSchemaWithoutID } from "../../validate"; +import { criarTurma as criarTurmaDatabase } from "../../database/mysql"; + +const erros = { + inesperado: "Aconteceu um erro inesperado", + nomeExiste: "Nome da turma já existe" +}; + +export const turmaRouter = express.Router(); + +turmaRouter.post("/", criarTurma); + +const PADRAO_TIPO = "Integral"; + +async function criarTurma(request: Request, response: Response): Promise { + const { + nome, + dataInicio, + dataFinal, + modulo, + tipo + } = request.body; + + const turma = { + nome, + dataInicio, + dataFinal, + modulo, + tipo: tipo || PADRAO_TIPO + }; + + try { + await turmaSchemaWithoutID.validate(turma, { abortEarly: false }); + + const turmaNova = await criarTurmaDatabase(turma); + + response.send(turmaNova); + } catch (error) { + if (error.name === "ValidationError") { + response.status(400).send(error.errors); + return; + } + + if (error.code === "ER_DUP_ENTRY") { + response.status(409).send(erros.nomeExiste); + return; + } + + response.status(500).send(erros.inesperado); + } +} + diff --git a/src/index.ts b/src/index.ts index cfe5501..be64fe3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ import "./env"; import express from "express"; import cors from "cors"; +import { turmaRouter } from "./handlers/turma"; const serverPort = process.env.NODE_PORT || 3003; @@ -8,6 +9,8 @@ const server = express(); server.use(express.json()); server.use(cors()); +server.use("/turma", turmaRouter); + const serverListener = server.listen(serverPort, () => { if (serverListener) //eslint-disable-next-line no-console diff --git a/src/queries.sql b/src/queries.sql index bdf744d..20ea631 100644 --- a/src/queries.sql +++ b/src/queries.sql @@ -7,6 +7,11 @@ SELECT * FROM information_schema.columns WHERE TABLE_NAME LIKE "LabenuSystem%"; SELECT TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT, COLUMN_TYPE, COLUMN_KEY FROM information_schema.columns WHERE TABLE_NAME LIKE "LabenuSystem%"; +SELECT * FROM LabenuSystem_Turma; + +INSERT INTO LabenuSystem_Turma (id, nome, data_inicio, data_final, modulo, tipo) +VALUES ("00000000-0000-0000-0000-000000000000", "Turma Zero", "2017-01-01", "9999-12-31", "0", "Integral"); + DROP TABLE LabenuSystem_Professor_Especialidade; DROP TABLE LabenuSystem_Estudante_Passatempo; diff --git a/src/validate/index.ts b/src/validate/index.ts new file mode 100644 index 0000000..d6877c5 --- /dev/null +++ b/src/validate/index.ts @@ -0,0 +1,27 @@ +import * as yup from "yup"; +import { Turma } from "../@types"; + +const MIN_CARACTER = 6; +const MAX_CARACTER = 255; + +const MIN_MODULO = 0; +const MAX_MODULO = 7; + +//@ts-expect-error issue an yup https://github.com/jquense/yup/issues/1183 +export const turmaSchema: yup.SchemaOf = yup.object({ + id: yup.string().uuid().defined(), + nome: yup.string() + .min(MIN_CARACTER) + .max(MAX_CARACTER) + .defined(), + modulo: yup.number() + .min(MIN_MODULO) + .max(MAX_MODULO) + .defined(), + dataFinal: yup.date().defined(), + dataInicio: yup.date().defined(), + tipo: yup.mixed().oneOf([ "Integral", "Noturno" ]).defined() +}); + +export const turmaSchemaWithoutID: yup.SchemaOf> + = turmaSchema.omit([ "id" ]); From bc7bf7d76c33d21c873d7c09c96228ff13fb43ff Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 15:19:22 -0400 Subject: [PATCH 05/29] Adicionando a funcionalidades de adicionar professor e estudante --- .../src/database/mysql/estudante.ts | 21 ++++++++ .../LabenuSystem/src/database/mysql/index.ts | 2 + .../src/database/mysql/professor.ts | 22 ++++++++ .../src/handlers/estudante/index.ts | 50 +++++++++++++++++++ semana17/LabenuSystem/src/handlers/index.ts | 2 + .../src/handlers/professor/index.ts | 50 +++++++++++++++++++ .../LabenuSystem/src/handlers/turma/index.ts | 6 ++- semana17/LabenuSystem/src/index.ts | 3 +- semana17/LabenuSystem/src/queries.sql | 4 ++ semana17/LabenuSystem/src/validate/index.ts | 35 ++++++++++++- 10 files changed, 190 insertions(+), 5 deletions(-) create mode 100644 semana17/LabenuSystem/src/database/mysql/estudante.ts create mode 100644 semana17/LabenuSystem/src/database/mysql/professor.ts create mode 100644 semana17/LabenuSystem/src/handlers/estudante/index.ts create mode 100644 semana17/LabenuSystem/src/handlers/index.ts create mode 100644 semana17/LabenuSystem/src/handlers/professor/index.ts diff --git a/semana17/LabenuSystem/src/database/mysql/estudante.ts b/semana17/LabenuSystem/src/database/mysql/estudante.ts new file mode 100644 index 0000000..6a97996 --- /dev/null +++ b/semana17/LabenuSystem/src/database/mysql/estudante.ts @@ -0,0 +1,21 @@ +import { v1 as uuidV1 } from "uuid"; +import { Estudante, EstudanteDatabase } from "../../@types"; +import { connection } from "./connection"; + +export async function criarEstudante(estudante: Omit) +: Promise { + const estudanteNovo: EstudanteDatabase = { + id: uuidV1(), + nome: estudante.nome, + email: estudante.email, + turma_id: estudante.turmaID, + data_de_nascimento: estudante.dataDeNascimento + }; + + await connection("LabenuSystem_Estudante").insert(estudanteNovo); + + return { + ...estudante, + id: estudanteNovo.id + }; +} diff --git a/semana17/LabenuSystem/src/database/mysql/index.ts b/semana17/LabenuSystem/src/database/mysql/index.ts index f2e32c8..297e8d7 100644 --- a/semana17/LabenuSystem/src/database/mysql/index.ts +++ b/semana17/LabenuSystem/src/database/mysql/index.ts @@ -1 +1,3 @@ export * from "./turma"; +export * from "./estudante"; +export * from "./professor"; diff --git a/semana17/LabenuSystem/src/database/mysql/professor.ts b/semana17/LabenuSystem/src/database/mysql/professor.ts new file mode 100644 index 0000000..15cc962 --- /dev/null +++ b/semana17/LabenuSystem/src/database/mysql/professor.ts @@ -0,0 +1,22 @@ +import { v1 as uuidV1 } from "uuid"; +import { Professor, ProfessorDatabase } from "../../@types"; +import { connection } from "./connection"; + +export async function criarProfessor(professor: Omit) +: Promise { + const professorNovo: ProfessorDatabase = { + id: uuidV1(), + nome: professor.nome, + email: professor.email, + turma_id: professor.turmaID, + data_de_nascimento: professor.dataDeNascimento + }; + + await connection("LabenuSystem_Professor").insert(professorNovo); + + return { + ...professor, + id: professorNovo.id + }; +} + diff --git a/semana17/LabenuSystem/src/handlers/estudante/index.ts b/semana17/LabenuSystem/src/handlers/estudante/index.ts new file mode 100644 index 0000000..5018507 --- /dev/null +++ b/semana17/LabenuSystem/src/handlers/estudante/index.ts @@ -0,0 +1,50 @@ +import express, { Request, Response } from "express"; +import { criarEstudanteSchema } from "../../validate"; +import { criarEstudante as criarEstudanteDatabase } from "../../database/mysql"; +import { TURMA_ZERO_ID } from "../turma"; + +const erros = { + inesperado: "Aconteceu um erro inesperado", + emailExiste: "Email já existe" +}; + +export const estudanteRouter = express.Router(); + +estudanteRouter.post("/", criarEstudante); + +async function criarEstudante(request: Request, response: Response): Promise { + const { + nome, + email, + dataDeNascimento, + turmaID + } = request.body; + + const estudante = { + nome, + email, + dataDeNascimento, + turmaID: turmaID || TURMA_ZERO_ID + }; + + try { + await criarEstudanteSchema.validate(estudante, { abortEarly: false }); + + const estudanteNova = await criarEstudanteDatabase(estudante); + + response.send(estudanteNova); + } catch (error) { + if (error.name === "ValidationError") { + response.status(400).send(error.errors); + return; + } + + if (error.code === "ER_DUP_ENTRY") { + response.status(409).send(erros.emailExiste); + return; + } + + response.status(500).send(erros.inesperado); + } +} + diff --git a/semana17/LabenuSystem/src/handlers/index.ts b/semana17/LabenuSystem/src/handlers/index.ts new file mode 100644 index 0000000..7a3427c --- /dev/null +++ b/semana17/LabenuSystem/src/handlers/index.ts @@ -0,0 +1,2 @@ +export * from "./turma"; +export * from "./estudante"; diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts new file mode 100644 index 0000000..f4e79fd --- /dev/null +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -0,0 +1,50 @@ +import express, { Request, Response } from "express"; +import { criarProfessorSchema } from "../../validate"; +import { criarProfessor as criarProfessorDatabase } from "../../database/mysql"; +import { TURMA_ZERO_ID } from "../turma"; + +const erros = { + inesperado: "Aconteceu um erro inesperado", + emailExiste: "Email já existe" +}; + +export const professorRouter = express.Router(); + +professorRouter.post("/", criarProfessor); + +async function criarProfessor(request: Request, response: Response): Promise { + const { + nome, + email, + dataDeNascimento, + turmaID + } = request.body; + + const professor = { + nome, + email, + dataDeNascimento, + turmaID: turmaID || TURMA_ZERO_ID + }; + + try { + await criarProfessorSchema.validate(professor, { abortEarly: false }); + + const professorNova = await criarProfessorDatabase(professor); + + response.send(professorNova); + } catch (error) { + if (error.name === "ValidationError") { + response.status(400).send(error.errors); + return; + } + + if (error.code === "ER_DUP_ENTRY") { + response.status(409).send(erros.emailExiste); + return; + } + + response.status(500).send(erros.inesperado); + } +} + diff --git a/semana17/LabenuSystem/src/handlers/turma/index.ts b/semana17/LabenuSystem/src/handlers/turma/index.ts index 19fbae9..ea7469b 100644 --- a/semana17/LabenuSystem/src/handlers/turma/index.ts +++ b/semana17/LabenuSystem/src/handlers/turma/index.ts @@ -1,5 +1,5 @@ import express, { Request, Response } from "express"; -import { turmaSchemaWithoutID } from "../../validate"; +import { criarTurmaSchema } from "../../validate"; import { criarTurma as criarTurmaDatabase } from "../../database/mysql"; const erros = { @@ -11,6 +11,8 @@ export const turmaRouter = express.Router(); turmaRouter.post("/", criarTurma); +export const TURMA_ZERO_ID = "00000000-0000-0000-0000-000000000000"; + const PADRAO_TIPO = "Integral"; async function criarTurma(request: Request, response: Response): Promise { @@ -31,7 +33,7 @@ async function criarTurma(request: Request, response: Response): Promise { }; try { - await turmaSchemaWithoutID.validate(turma, { abortEarly: false }); + await criarTurmaSchema.validate(turma, { abortEarly: false }); const turmaNova = await criarTurmaDatabase(turma); diff --git a/semana17/LabenuSystem/src/index.ts b/semana17/LabenuSystem/src/index.ts index be64fe3..be9869d 100644 --- a/semana17/LabenuSystem/src/index.ts +++ b/semana17/LabenuSystem/src/index.ts @@ -1,7 +1,7 @@ import "./env"; import express from "express"; import cors from "cors"; -import { turmaRouter } from "./handlers/turma"; +import { estudanteRouter, turmaRouter } from "./handlers"; const serverPort = process.env.NODE_PORT || 3003; @@ -10,6 +10,7 @@ server.use(express.json()); server.use(cors()); server.use("/turma", turmaRouter); +server.use("/estudante", estudanteRouter); const serverListener = server.listen(serverPort, () => { if (serverListener) diff --git a/semana17/LabenuSystem/src/queries.sql b/semana17/LabenuSystem/src/queries.sql index 20ea631..338fc26 100644 --- a/semana17/LabenuSystem/src/queries.sql +++ b/semana17/LabenuSystem/src/queries.sql @@ -9,6 +9,10 @@ SELECT TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT, COLUMN_TYPE, COLUMN_KEY FROM inf SELECT * FROM LabenuSystem_Turma; +SELECT * FROM LabenuSystem_Estudante; + +SELECT * FROM LabenuSystem_Professor; + INSERT INTO LabenuSystem_Turma (id, nome, data_inicio, data_final, modulo, tipo) VALUES ("00000000-0000-0000-0000-000000000000", "Turma Zero", "2017-01-01", "9999-12-31", "0", "Integral"); diff --git a/semana17/LabenuSystem/src/validate/index.ts b/semana17/LabenuSystem/src/validate/index.ts index d6877c5..d5564c6 100644 --- a/semana17/LabenuSystem/src/validate/index.ts +++ b/semana17/LabenuSystem/src/validate/index.ts @@ -1,5 +1,5 @@ import * as yup from "yup"; -import { Turma } from "../@types"; +import { Estudante, Professor, Turma } from "../@types"; const MIN_CARACTER = 6; const MAX_CARACTER = 255; @@ -23,5 +23,36 @@ export const turmaSchema: yup.SchemaOf = yup.object({ tipo: yup.mixed().oneOf([ "Integral", "Noturno" ]).defined() }); -export const turmaSchemaWithoutID: yup.SchemaOf> +export const criarTurmaSchema: yup.SchemaOf> = turmaSchema.omit([ "id" ]); + +//@ts-expect-error issue an yup https://github.com/jquense/yup/issues/1183 +export const estudanteSchema: yup.SchemaOf = yup.object({ + id: yup.string().uuid().defined(), + nome: yup.string() + .min(MIN_CARACTER) + .max(MAX_CARACTER) + .defined(), + email: yup.string().email().defined(), + turmaID: yup.string().uuid().defined(), + dataDeNascimento: yup.date().defined() +}); + +export const criarEstudanteSchema: yup.SchemaOf> + = estudanteSchema.omit([ "id" ]).shape({ turmaID: yup.string().uuid() }); + +//@ts-expect-error issue an yup https://github.com/jquense/yup/issues/1183 +export const professorSchema: yup.SchemaOf = yup.object({ + id: yup.string().uuid().defined(), + nome: yup.string() + .min(MIN_CARACTER) + .max(MAX_CARACTER) + .defined(), + email: yup.string().email().defined(), + turmaID: yup.string().uuid().defined(), + dataDeNascimento: yup.date().defined() +}); + +export const criarProfessorSchema: yup.SchemaOf> + = professorSchema.omit([ "id" ]).shape({ turmaID: yup.string().uuid() }); + From 9209c43863553aeb0616c9468e9c43b29e6f93ad Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 15:19:22 -0400 Subject: [PATCH 06/29] Adicionando a funcionalidades de adicionar professor e estudante --- src/database/mysql/estudante.ts | 21 ++++++++++++++ src/database/mysql/index.ts | 2 ++ src/database/mysql/professor.ts | 22 +++++++++++++++ src/handlers/estudante/index.ts | 50 +++++++++++++++++++++++++++++++++ src/handlers/index.ts | 2 ++ src/handlers/professor/index.ts | 50 +++++++++++++++++++++++++++++++++ src/handlers/turma/index.ts | 6 ++-- src/index.ts | 3 +- src/queries.sql | 4 +++ src/validate/index.ts | 35 +++++++++++++++++++++-- 10 files changed, 190 insertions(+), 5 deletions(-) create mode 100644 src/database/mysql/estudante.ts create mode 100644 src/database/mysql/professor.ts create mode 100644 src/handlers/estudante/index.ts create mode 100644 src/handlers/index.ts create mode 100644 src/handlers/professor/index.ts diff --git a/src/database/mysql/estudante.ts b/src/database/mysql/estudante.ts new file mode 100644 index 0000000..6a97996 --- /dev/null +++ b/src/database/mysql/estudante.ts @@ -0,0 +1,21 @@ +import { v1 as uuidV1 } from "uuid"; +import { Estudante, EstudanteDatabase } from "../../@types"; +import { connection } from "./connection"; + +export async function criarEstudante(estudante: Omit) +: Promise { + const estudanteNovo: EstudanteDatabase = { + id: uuidV1(), + nome: estudante.nome, + email: estudante.email, + turma_id: estudante.turmaID, + data_de_nascimento: estudante.dataDeNascimento + }; + + await connection("LabenuSystem_Estudante").insert(estudanteNovo); + + return { + ...estudante, + id: estudanteNovo.id + }; +} diff --git a/src/database/mysql/index.ts b/src/database/mysql/index.ts index f2e32c8..297e8d7 100644 --- a/src/database/mysql/index.ts +++ b/src/database/mysql/index.ts @@ -1 +1,3 @@ export * from "./turma"; +export * from "./estudante"; +export * from "./professor"; diff --git a/src/database/mysql/professor.ts b/src/database/mysql/professor.ts new file mode 100644 index 0000000..15cc962 --- /dev/null +++ b/src/database/mysql/professor.ts @@ -0,0 +1,22 @@ +import { v1 as uuidV1 } from "uuid"; +import { Professor, ProfessorDatabase } from "../../@types"; +import { connection } from "./connection"; + +export async function criarProfessor(professor: Omit) +: Promise { + const professorNovo: ProfessorDatabase = { + id: uuidV1(), + nome: professor.nome, + email: professor.email, + turma_id: professor.turmaID, + data_de_nascimento: professor.dataDeNascimento + }; + + await connection("LabenuSystem_Professor").insert(professorNovo); + + return { + ...professor, + id: professorNovo.id + }; +} + diff --git a/src/handlers/estudante/index.ts b/src/handlers/estudante/index.ts new file mode 100644 index 0000000..5018507 --- /dev/null +++ b/src/handlers/estudante/index.ts @@ -0,0 +1,50 @@ +import express, { Request, Response } from "express"; +import { criarEstudanteSchema } from "../../validate"; +import { criarEstudante as criarEstudanteDatabase } from "../../database/mysql"; +import { TURMA_ZERO_ID } from "../turma"; + +const erros = { + inesperado: "Aconteceu um erro inesperado", + emailExiste: "Email já existe" +}; + +export const estudanteRouter = express.Router(); + +estudanteRouter.post("/", criarEstudante); + +async function criarEstudante(request: Request, response: Response): Promise { + const { + nome, + email, + dataDeNascimento, + turmaID + } = request.body; + + const estudante = { + nome, + email, + dataDeNascimento, + turmaID: turmaID || TURMA_ZERO_ID + }; + + try { + await criarEstudanteSchema.validate(estudante, { abortEarly: false }); + + const estudanteNova = await criarEstudanteDatabase(estudante); + + response.send(estudanteNova); + } catch (error) { + if (error.name === "ValidationError") { + response.status(400).send(error.errors); + return; + } + + if (error.code === "ER_DUP_ENTRY") { + response.status(409).send(erros.emailExiste); + return; + } + + response.status(500).send(erros.inesperado); + } +} + diff --git a/src/handlers/index.ts b/src/handlers/index.ts new file mode 100644 index 0000000..7a3427c --- /dev/null +++ b/src/handlers/index.ts @@ -0,0 +1,2 @@ +export * from "./turma"; +export * from "./estudante"; diff --git a/src/handlers/professor/index.ts b/src/handlers/professor/index.ts new file mode 100644 index 0000000..f4e79fd --- /dev/null +++ b/src/handlers/professor/index.ts @@ -0,0 +1,50 @@ +import express, { Request, Response } from "express"; +import { criarProfessorSchema } from "../../validate"; +import { criarProfessor as criarProfessorDatabase } from "../../database/mysql"; +import { TURMA_ZERO_ID } from "../turma"; + +const erros = { + inesperado: "Aconteceu um erro inesperado", + emailExiste: "Email já existe" +}; + +export const professorRouter = express.Router(); + +professorRouter.post("/", criarProfessor); + +async function criarProfessor(request: Request, response: Response): Promise { + const { + nome, + email, + dataDeNascimento, + turmaID + } = request.body; + + const professor = { + nome, + email, + dataDeNascimento, + turmaID: turmaID || TURMA_ZERO_ID + }; + + try { + await criarProfessorSchema.validate(professor, { abortEarly: false }); + + const professorNova = await criarProfessorDatabase(professor); + + response.send(professorNova); + } catch (error) { + if (error.name === "ValidationError") { + response.status(400).send(error.errors); + return; + } + + if (error.code === "ER_DUP_ENTRY") { + response.status(409).send(erros.emailExiste); + return; + } + + response.status(500).send(erros.inesperado); + } +} + diff --git a/src/handlers/turma/index.ts b/src/handlers/turma/index.ts index 19fbae9..ea7469b 100644 --- a/src/handlers/turma/index.ts +++ b/src/handlers/turma/index.ts @@ -1,5 +1,5 @@ import express, { Request, Response } from "express"; -import { turmaSchemaWithoutID } from "../../validate"; +import { criarTurmaSchema } from "../../validate"; import { criarTurma as criarTurmaDatabase } from "../../database/mysql"; const erros = { @@ -11,6 +11,8 @@ export const turmaRouter = express.Router(); turmaRouter.post("/", criarTurma); +export const TURMA_ZERO_ID = "00000000-0000-0000-0000-000000000000"; + const PADRAO_TIPO = "Integral"; async function criarTurma(request: Request, response: Response): Promise { @@ -31,7 +33,7 @@ async function criarTurma(request: Request, response: Response): Promise { }; try { - await turmaSchemaWithoutID.validate(turma, { abortEarly: false }); + await criarTurmaSchema.validate(turma, { abortEarly: false }); const turmaNova = await criarTurmaDatabase(turma); diff --git a/src/index.ts b/src/index.ts index be64fe3..be9869d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,7 @@ import "./env"; import express from "express"; import cors from "cors"; -import { turmaRouter } from "./handlers/turma"; +import { estudanteRouter, turmaRouter } from "./handlers"; const serverPort = process.env.NODE_PORT || 3003; @@ -10,6 +10,7 @@ server.use(express.json()); server.use(cors()); server.use("/turma", turmaRouter); +server.use("/estudante", estudanteRouter); const serverListener = server.listen(serverPort, () => { if (serverListener) diff --git a/src/queries.sql b/src/queries.sql index 20ea631..338fc26 100644 --- a/src/queries.sql +++ b/src/queries.sql @@ -9,6 +9,10 @@ SELECT TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT, COLUMN_TYPE, COLUMN_KEY FROM inf SELECT * FROM LabenuSystem_Turma; +SELECT * FROM LabenuSystem_Estudante; + +SELECT * FROM LabenuSystem_Professor; + INSERT INTO LabenuSystem_Turma (id, nome, data_inicio, data_final, modulo, tipo) VALUES ("00000000-0000-0000-0000-000000000000", "Turma Zero", "2017-01-01", "9999-12-31", "0", "Integral"); diff --git a/src/validate/index.ts b/src/validate/index.ts index d6877c5..d5564c6 100644 --- a/src/validate/index.ts +++ b/src/validate/index.ts @@ -1,5 +1,5 @@ import * as yup from "yup"; -import { Turma } from "../@types"; +import { Estudante, Professor, Turma } from "../@types"; const MIN_CARACTER = 6; const MAX_CARACTER = 255; @@ -23,5 +23,36 @@ export const turmaSchema: yup.SchemaOf = yup.object({ tipo: yup.mixed().oneOf([ "Integral", "Noturno" ]).defined() }); -export const turmaSchemaWithoutID: yup.SchemaOf> +export const criarTurmaSchema: yup.SchemaOf> = turmaSchema.omit([ "id" ]); + +//@ts-expect-error issue an yup https://github.com/jquense/yup/issues/1183 +export const estudanteSchema: yup.SchemaOf = yup.object({ + id: yup.string().uuid().defined(), + nome: yup.string() + .min(MIN_CARACTER) + .max(MAX_CARACTER) + .defined(), + email: yup.string().email().defined(), + turmaID: yup.string().uuid().defined(), + dataDeNascimento: yup.date().defined() +}); + +export const criarEstudanteSchema: yup.SchemaOf> + = estudanteSchema.omit([ "id" ]).shape({ turmaID: yup.string().uuid() }); + +//@ts-expect-error issue an yup https://github.com/jquense/yup/issues/1183 +export const professorSchema: yup.SchemaOf = yup.object({ + id: yup.string().uuid().defined(), + nome: yup.string() + .min(MIN_CARACTER) + .max(MAX_CARACTER) + .defined(), + email: yup.string().email().defined(), + turmaID: yup.string().uuid().defined(), + dataDeNascimento: yup.date().defined() +}); + +export const criarProfessorSchema: yup.SchemaOf> + = professorSchema.omit([ "id" ]).shape({ turmaID: yup.string().uuid() }); + From 9ff3c2e26ae1930ed09c7a72cd24fbc63b47eb81 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 16:01:14 -0400 Subject: [PATCH 07/29] Adicionando as funcionalidades de mudar a turma do professor e aluno --- .../src/database/mysql/estudante.ts | 10 +++- .../src/database/mysql/professor.ts | 9 +++- .../src/handlers/estudante/index.ts | 45 ++++++++++++++-- .../src/handlers/professor/index.ts | 53 ++++++++++++++++--- semana17/LabenuSystem/src/index.ts | 2 + semana17/LabenuSystem/src/validate/index.ts | 10 ++++ 6 files changed, 115 insertions(+), 14 deletions(-) diff --git a/semana17/LabenuSystem/src/database/mysql/estudante.ts b/semana17/LabenuSystem/src/database/mysql/estudante.ts index 6a97996..395c8f0 100644 --- a/semana17/LabenuSystem/src/database/mysql/estudante.ts +++ b/semana17/LabenuSystem/src/database/mysql/estudante.ts @@ -1,5 +1,5 @@ import { v1 as uuidV1 } from "uuid"; -import { Estudante, EstudanteDatabase } from "../../@types"; +import { Estudante, EstudanteDatabase, ID } from "../../@types"; import { connection } from "./connection"; export async function criarEstudante(estudante: Omit) @@ -19,3 +19,11 @@ export async function criarEstudante(estudante: Omit) id: estudanteNovo.id }; } + +export async function adicionarEstudanteNaTurma(estudanteID: ID, turmaID: ID) +: Promise { + return connection("LabenuSystem_Estudante") + .update({ turma_id: turmaID }) + .where({ id: estudanteID }); +} + diff --git a/semana17/LabenuSystem/src/database/mysql/professor.ts b/semana17/LabenuSystem/src/database/mysql/professor.ts index 15cc962..b290bbc 100644 --- a/semana17/LabenuSystem/src/database/mysql/professor.ts +++ b/semana17/LabenuSystem/src/database/mysql/professor.ts @@ -1,5 +1,5 @@ import { v1 as uuidV1 } from "uuid"; -import { Professor, ProfessorDatabase } from "../../@types"; +import { ID, Professor, ProfessorDatabase } from "../../@types"; import { connection } from "./connection"; export async function criarProfessor(professor: Omit) @@ -20,3 +20,10 @@ export async function criarProfessor(professor: Omit) }; } +export async function adicionarProfessorNaTurma(professorID: ID, turmaID: ID) +: Promise { + return connection("LabenuSystem_Professor") + .update({ turma_id: turmaID }) + .where({ id: professorID }); +} + diff --git a/semana17/LabenuSystem/src/handlers/estudante/index.ts b/semana17/LabenuSystem/src/handlers/estudante/index.ts index 5018507..dacd11d 100644 --- a/semana17/LabenuSystem/src/handlers/estudante/index.ts +++ b/semana17/LabenuSystem/src/handlers/estudante/index.ts @@ -1,16 +1,22 @@ import express, { Request, Response } from "express"; -import { criarEstudanteSchema } from "../../validate"; -import { criarEstudante as criarEstudanteDatabase } from "../../database/mysql"; +import { criarEstudanteSchema, estudanteAdicionarTurmaSchema } from "../../validate"; +import { + adicionarEstudanteNaTurma, + criarEstudante as criarEstudanteDatabase +} from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; const erros = { - inesperado: "Aconteceu um erro inesperado", - emailExiste: "Email já existe" + inesperado: "Aconteceu um erro inesperado", + emailExiste: "Email já existe", + estudanteNaoEcontrada: "Estudante não econtrada", + turmaNaoEcontrada: "Turma não econtrada" }; export const estudanteRouter = express.Router(); estudanteRouter.post("/", criarEstudante); +estudanteRouter.put("/turma", adicionarTurma); async function criarEstudante(request: Request, response: Response): Promise { const { @@ -48,3 +54,34 @@ async function criarEstudante(request: Request, response: Response): Promise { + const { turmaID, estudanteID } = request.body; + + try { + await estudanteAdicionarTurmaSchema.validate({ + turmaID, + estudanteID + }, { abortEarly: false }); + + const adicionado = await adicionarEstudanteNaTurma(estudanteID, turmaID); + if (!adicionado) { + response.status(404).send(erros.estudanteNaoEcontrada); + return; + } + + response.send("Estudante adicionado na turma com sucesso"); + } catch (erro) { + if (erro.name === "ValidationError") { + response.status(400).send(erro.errors); + return; + } + + if (erro.code.includes("ER_NO_REFERENCED_ROW")) { + response.status(404).send(erros.turmaNaoEcontrada); + return; + } + + response.status(500).send(erros.inesperado); + } +} diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts index f4e79fd..5807336 100644 --- a/semana17/LabenuSystem/src/handlers/professor/index.ts +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -1,16 +1,22 @@ import express, { Request, Response } from "express"; -import { criarProfessorSchema } from "../../validate"; -import { criarProfessor as criarProfessorDatabase } from "../../database/mysql"; +import { criarProfessorSchema, professorAdicionarTurmaSchema } from "../../validate"; +import { + adicionarProfessorNaTurma, + criarProfessor as criarProfessorDatabase +} from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; const erros = { - inesperado: "Aconteceu um erro inesperado", - emailExiste: "Email já existe" + inesperado: "Aconteceu um erro inesperado", + emailExiste: "Email já existe", + professorNaoEcontrada: "Professor não econtrada", + turmaNaoEcontrada: "Turma não econtrada" }; export const professorRouter = express.Router(); professorRouter.post("/", criarProfessor); +professorRouter.put("/turma", adicionarTurma); async function criarProfessor(request: Request, response: Response): Promise { const { @@ -33,13 +39,13 @@ async function criarProfessor(request: Request, response: Response): Promise { + const { turmaID, professorID } = request.body; + + try { + await professorAdicionarTurmaSchema.validate({ + turmaID, + professorID + }, { abortEarly: false }); + + const adicionado = await adicionarProfessorNaTurma(professorID, turmaID); + if (!adicionado) { + response.status(404).send(erros.professorNaoEcontrada); + return; + } + + response.send("Professor adicionado na turma com sucesso"); + } catch (erro) { + if (erro.name === "ValidationError") { + response.status(400).send(erro.errors); + return; + } + + if (erro.code.includes("ER_NO_REFERENCED_ROW")) { + response.status(404).send(erros.turmaNaoEcontrada); + return; + } + + response.status(500).send(erros.inesperado); + } +} diff --git a/semana17/LabenuSystem/src/index.ts b/semana17/LabenuSystem/src/index.ts index be9869d..ec1c3ef 100644 --- a/semana17/LabenuSystem/src/index.ts +++ b/semana17/LabenuSystem/src/index.ts @@ -2,6 +2,7 @@ import "./env"; import express from "express"; import cors from "cors"; import { estudanteRouter, turmaRouter } from "./handlers"; +import { professorRouter } from "./handlers/professor"; const serverPort = process.env.NODE_PORT || 3003; @@ -11,6 +12,7 @@ server.use(cors()); server.use("/turma", turmaRouter); server.use("/estudante", estudanteRouter); +server.use("/professor", professorRouter); const serverListener = server.listen(serverPort, () => { if (serverListener) diff --git a/semana17/LabenuSystem/src/validate/index.ts b/semana17/LabenuSystem/src/validate/index.ts index d5564c6..fcb3359 100644 --- a/semana17/LabenuSystem/src/validate/index.ts +++ b/semana17/LabenuSystem/src/validate/index.ts @@ -41,6 +41,11 @@ export const estudanteSchema: yup.SchemaOf = yup.object({ export const criarEstudanteSchema: yup.SchemaOf> = estudanteSchema.omit([ "id" ]).shape({ turmaID: yup.string().uuid() }); +export const professorAdicionarTurmaSchema = yup.object({ + turmaID: yup.string().uuid().defined(), + professorID: yup.string().uuid().defined() +}); + //@ts-expect-error issue an yup https://github.com/jquense/yup/issues/1183 export const professorSchema: yup.SchemaOf = yup.object({ id: yup.string().uuid().defined(), @@ -56,3 +61,8 @@ export const professorSchema: yup.SchemaOf = yup.object({ export const criarProfessorSchema: yup.SchemaOf> = professorSchema.omit([ "id" ]).shape({ turmaID: yup.string().uuid() }); +export const estudanteAdicionarTurmaSchema = yup.object({ + turmaID: yup.string().uuid().defined(), + estudanteID: yup.string().uuid().defined() +}); + From 19d07c2e02f0da28337b0c5af8239aead83aab0d Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 16:01:14 -0400 Subject: [PATCH 08/29] Adicionando as funcionalidades de mudar a turma do professor e aluno --- src/database/mysql/estudante.ts | 10 ++++++- src/database/mysql/professor.ts | 9 +++++- src/handlers/estudante/index.ts | 45 +++++++++++++++++++++++++--- src/handlers/professor/index.ts | 53 ++++++++++++++++++++++++++++----- src/index.ts | 2 ++ src/validate/index.ts | 10 +++++++ 6 files changed, 115 insertions(+), 14 deletions(-) diff --git a/src/database/mysql/estudante.ts b/src/database/mysql/estudante.ts index 6a97996..395c8f0 100644 --- a/src/database/mysql/estudante.ts +++ b/src/database/mysql/estudante.ts @@ -1,5 +1,5 @@ import { v1 as uuidV1 } from "uuid"; -import { Estudante, EstudanteDatabase } from "../../@types"; +import { Estudante, EstudanteDatabase, ID } from "../../@types"; import { connection } from "./connection"; export async function criarEstudante(estudante: Omit) @@ -19,3 +19,11 @@ export async function criarEstudante(estudante: Omit) id: estudanteNovo.id }; } + +export async function adicionarEstudanteNaTurma(estudanteID: ID, turmaID: ID) +: Promise { + return connection("LabenuSystem_Estudante") + .update({ turma_id: turmaID }) + .where({ id: estudanteID }); +} + diff --git a/src/database/mysql/professor.ts b/src/database/mysql/professor.ts index 15cc962..b290bbc 100644 --- a/src/database/mysql/professor.ts +++ b/src/database/mysql/professor.ts @@ -1,5 +1,5 @@ import { v1 as uuidV1 } from "uuid"; -import { Professor, ProfessorDatabase } from "../../@types"; +import { ID, Professor, ProfessorDatabase } from "../../@types"; import { connection } from "./connection"; export async function criarProfessor(professor: Omit) @@ -20,3 +20,10 @@ export async function criarProfessor(professor: Omit) }; } +export async function adicionarProfessorNaTurma(professorID: ID, turmaID: ID) +: Promise { + return connection("LabenuSystem_Professor") + .update({ turma_id: turmaID }) + .where({ id: professorID }); +} + diff --git a/src/handlers/estudante/index.ts b/src/handlers/estudante/index.ts index 5018507..dacd11d 100644 --- a/src/handlers/estudante/index.ts +++ b/src/handlers/estudante/index.ts @@ -1,16 +1,22 @@ import express, { Request, Response } from "express"; -import { criarEstudanteSchema } from "../../validate"; -import { criarEstudante as criarEstudanteDatabase } from "../../database/mysql"; +import { criarEstudanteSchema, estudanteAdicionarTurmaSchema } from "../../validate"; +import { + adicionarEstudanteNaTurma, + criarEstudante as criarEstudanteDatabase +} from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; const erros = { - inesperado: "Aconteceu um erro inesperado", - emailExiste: "Email já existe" + inesperado: "Aconteceu um erro inesperado", + emailExiste: "Email já existe", + estudanteNaoEcontrada: "Estudante não econtrada", + turmaNaoEcontrada: "Turma não econtrada" }; export const estudanteRouter = express.Router(); estudanteRouter.post("/", criarEstudante); +estudanteRouter.put("/turma", adicionarTurma); async function criarEstudante(request: Request, response: Response): Promise { const { @@ -48,3 +54,34 @@ async function criarEstudante(request: Request, response: Response): Promise { + const { turmaID, estudanteID } = request.body; + + try { + await estudanteAdicionarTurmaSchema.validate({ + turmaID, + estudanteID + }, { abortEarly: false }); + + const adicionado = await adicionarEstudanteNaTurma(estudanteID, turmaID); + if (!adicionado) { + response.status(404).send(erros.estudanteNaoEcontrada); + return; + } + + response.send("Estudante adicionado na turma com sucesso"); + } catch (erro) { + if (erro.name === "ValidationError") { + response.status(400).send(erro.errors); + return; + } + + if (erro.code.includes("ER_NO_REFERENCED_ROW")) { + response.status(404).send(erros.turmaNaoEcontrada); + return; + } + + response.status(500).send(erros.inesperado); + } +} diff --git a/src/handlers/professor/index.ts b/src/handlers/professor/index.ts index f4e79fd..5807336 100644 --- a/src/handlers/professor/index.ts +++ b/src/handlers/professor/index.ts @@ -1,16 +1,22 @@ import express, { Request, Response } from "express"; -import { criarProfessorSchema } from "../../validate"; -import { criarProfessor as criarProfessorDatabase } from "../../database/mysql"; +import { criarProfessorSchema, professorAdicionarTurmaSchema } from "../../validate"; +import { + adicionarProfessorNaTurma, + criarProfessor as criarProfessorDatabase +} from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; const erros = { - inesperado: "Aconteceu um erro inesperado", - emailExiste: "Email já existe" + inesperado: "Aconteceu um erro inesperado", + emailExiste: "Email já existe", + professorNaoEcontrada: "Professor não econtrada", + turmaNaoEcontrada: "Turma não econtrada" }; export const professorRouter = express.Router(); professorRouter.post("/", criarProfessor); +professorRouter.put("/turma", adicionarTurma); async function criarProfessor(request: Request, response: Response): Promise { const { @@ -33,13 +39,13 @@ async function criarProfessor(request: Request, response: Response): Promise { + const { turmaID, professorID } = request.body; + + try { + await professorAdicionarTurmaSchema.validate({ + turmaID, + professorID + }, { abortEarly: false }); + + const adicionado = await adicionarProfessorNaTurma(professorID, turmaID); + if (!adicionado) { + response.status(404).send(erros.professorNaoEcontrada); + return; + } + + response.send("Professor adicionado na turma com sucesso"); + } catch (erro) { + if (erro.name === "ValidationError") { + response.status(400).send(erro.errors); + return; + } + + if (erro.code.includes("ER_NO_REFERENCED_ROW")) { + response.status(404).send(erros.turmaNaoEcontrada); + return; + } + + response.status(500).send(erros.inesperado); + } +} diff --git a/src/index.ts b/src/index.ts index be9869d..ec1c3ef 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,6 +2,7 @@ import "./env"; import express from "express"; import cors from "cors"; import { estudanteRouter, turmaRouter } from "./handlers"; +import { professorRouter } from "./handlers/professor"; const serverPort = process.env.NODE_PORT || 3003; @@ -11,6 +12,7 @@ server.use(cors()); server.use("/turma", turmaRouter); server.use("/estudante", estudanteRouter); +server.use("/professor", professorRouter); const serverListener = server.listen(serverPort, () => { if (serverListener) diff --git a/src/validate/index.ts b/src/validate/index.ts index d5564c6..fcb3359 100644 --- a/src/validate/index.ts +++ b/src/validate/index.ts @@ -41,6 +41,11 @@ export const estudanteSchema: yup.SchemaOf = yup.object({ export const criarEstudanteSchema: yup.SchemaOf> = estudanteSchema.omit([ "id" ]).shape({ turmaID: yup.string().uuid() }); +export const professorAdicionarTurmaSchema = yup.object({ + turmaID: yup.string().uuid().defined(), + professorID: yup.string().uuid().defined() +}); + //@ts-expect-error issue an yup https://github.com/jquense/yup/issues/1183 export const professorSchema: yup.SchemaOf = yup.object({ id: yup.string().uuid().defined(), @@ -56,3 +61,8 @@ export const professorSchema: yup.SchemaOf = yup.object({ export const criarProfessorSchema: yup.SchemaOf> = professorSchema.omit([ "id" ]).shape({ turmaID: yup.string().uuid() }); +export const estudanteAdicionarTurmaSchema = yup.object({ + turmaID: yup.string().uuid().defined(), + estudanteID: yup.string().uuid().defined() +}); + From e2b306bf3d62eb2cb478d4abb95b15287024d86c Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 16:52:23 -0400 Subject: [PATCH 09/29] Adicionando a funcionalidade de ver os professores e estudantes por turma --- .../src/database/mysql/estudante.ts | 16 ++++++++++++ .../src/database/mysql/professor.ts | 16 ++++++++++++ .../src/handlers/estudante/index.ts | 26 +++++++++++++++++-- .../src/handlers/professor/index.ts | 26 +++++++++++++++++-- 4 files changed, 80 insertions(+), 4 deletions(-) diff --git a/semana17/LabenuSystem/src/database/mysql/estudante.ts b/semana17/LabenuSystem/src/database/mysql/estudante.ts index 395c8f0..71aee24 100644 --- a/semana17/LabenuSystem/src/database/mysql/estudante.ts +++ b/semana17/LabenuSystem/src/database/mysql/estudante.ts @@ -20,6 +20,22 @@ export async function criarEstudante(estudante: Omit) }; } +export async function verEstudantesNaTurma(turmaID: ID) +: Promise[]> { + const database = await connection("LabenuSystem_Estudante") + .select("id", "nome", "email", "data_de_nascimento") + .where({ turma_id: turmaID }); + + return database.map(({ + id, nome, data_de_nascimento, email + }) => ({ + id, + email, + nome, + dataDeNascimento: data_de_nascimento + })); +} + export async function adicionarEstudanteNaTurma(estudanteID: ID, turmaID: ID) : Promise { return connection("LabenuSystem_Estudante") diff --git a/semana17/LabenuSystem/src/database/mysql/professor.ts b/semana17/LabenuSystem/src/database/mysql/professor.ts index b290bbc..7370642 100644 --- a/semana17/LabenuSystem/src/database/mysql/professor.ts +++ b/semana17/LabenuSystem/src/database/mysql/professor.ts @@ -20,6 +20,22 @@ export async function criarProfessor(professor: Omit) }; } +export async function verProfessoresNaTurma(turmaID: ID) +: Promise[]> { + const database = await connection("LabenuSystem_Professor") + .select("id", "nome", "email", "data_de_nascimento") + .where({ turma_id: turmaID }); + + return database.map(({ + id, nome, data_de_nascimento, email + }) => ({ + id, + email, + nome, + dataDeNascimento: data_de_nascimento + })); +} + export async function adicionarProfessorNaTurma(professorID: ID, turmaID: ID) : Promise { return connection("LabenuSystem_Professor") diff --git a/semana17/LabenuSystem/src/handlers/estudante/index.ts b/semana17/LabenuSystem/src/handlers/estudante/index.ts index dacd11d..4c8b57a 100644 --- a/semana17/LabenuSystem/src/handlers/estudante/index.ts +++ b/semana17/LabenuSystem/src/handlers/estudante/index.ts @@ -2,21 +2,25 @@ import express, { Request, Response } from "express"; import { criarEstudanteSchema, estudanteAdicionarTurmaSchema } from "../../validate"; import { adicionarEstudanteNaTurma, - criarEstudante as criarEstudanteDatabase + criarEstudante as criarEstudanteDatabase, + verEstudantesNaTurma } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; +import { validate as validarUUID } from "uuid"; const erros = { inesperado: "Aconteceu um erro inesperado", emailExiste: "Email já existe", estudanteNaoEcontrada: "Estudante não econtrada", - turmaNaoEcontrada: "Turma não econtrada" + turmaNaoEcontrada: "Turma não econtrada", + turmaIDInvalido: "O turmaID precisa ser um id válido" }; export const estudanteRouter = express.Router(); estudanteRouter.post("/", criarEstudante); estudanteRouter.put("/turma", adicionarTurma); +estudanteRouter.get("/turma/:turmaID", verTurma); async function criarEstudante(request: Request, response: Response): Promise { const { @@ -85,3 +89,21 @@ async function adicionarTurma(request: Request, response: Response) response.status(500).send(erros.inesperado); } } + +export async function verTurma(request: Request, response: Response): Promise { + const { turmaID } = request.params; + if (!validarUUID(turmaID)) { + response.status(400).send(erros.turmaIDInvalido); + return; + } + + try { + const estudantes = await verEstudantesNaTurma(turmaID); + response.send({ + quantidate: estudantes.length, + estudantes + }); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts index 5807336..6bec256 100644 --- a/semana17/LabenuSystem/src/handlers/professor/index.ts +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -2,21 +2,25 @@ import express, { Request, Response } from "express"; import { criarProfessorSchema, professorAdicionarTurmaSchema } from "../../validate"; import { adicionarProfessorNaTurma, - criarProfessor as criarProfessorDatabase + criarProfessor as criarProfessorDatabase, + verProfessoresNaTurma } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; +import { validate as validarUUID } from "uuid"; const erros = { inesperado: "Aconteceu um erro inesperado", emailExiste: "Email já existe", professorNaoEcontrada: "Professor não econtrada", - turmaNaoEcontrada: "Turma não econtrada" + turmaNaoEcontrada: "Turma não econtrada", + turmaIDInvalido: "O turmaID precisa ser um id válido" }; export const professorRouter = express.Router(); professorRouter.post("/", criarProfessor); professorRouter.put("/turma", adicionarTurma); +professorRouter.get("/turma/:turmaID", verTurma); async function criarProfessor(request: Request, response: Response): Promise { const { @@ -85,3 +89,21 @@ async function adicionarTurma(request: Request, response: Response) response.status(500).send(erros.inesperado); } } + +export async function verTurma(request: Request, response: Response): Promise { + const { turmaID } = request.params; + if (!validarUUID(turmaID)) { + response.status(400).send(erros.turmaIDInvalido); + return; + } + + try { + const professores = await verProfessoresNaTurma(turmaID); + response.send({ + quantidate: professores.length, + professores + }); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} From 089edfb6f9f7cbcfd1d961dc2f6270c330d95d42 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 16:52:23 -0400 Subject: [PATCH 10/29] Adicionando a funcionalidade de ver os professores e estudantes por turma --- src/database/mysql/estudante.ts | 16 ++++++++++++++++ src/database/mysql/professor.ts | 16 ++++++++++++++++ src/handlers/estudante/index.ts | 26 ++++++++++++++++++++++++-- src/handlers/professor/index.ts | 26 ++++++++++++++++++++++++-- 4 files changed, 80 insertions(+), 4 deletions(-) diff --git a/src/database/mysql/estudante.ts b/src/database/mysql/estudante.ts index 395c8f0..71aee24 100644 --- a/src/database/mysql/estudante.ts +++ b/src/database/mysql/estudante.ts @@ -20,6 +20,22 @@ export async function criarEstudante(estudante: Omit) }; } +export async function verEstudantesNaTurma(turmaID: ID) +: Promise[]> { + const database = await connection("LabenuSystem_Estudante") + .select("id", "nome", "email", "data_de_nascimento") + .where({ turma_id: turmaID }); + + return database.map(({ + id, nome, data_de_nascimento, email + }) => ({ + id, + email, + nome, + dataDeNascimento: data_de_nascimento + })); +} + export async function adicionarEstudanteNaTurma(estudanteID: ID, turmaID: ID) : Promise { return connection("LabenuSystem_Estudante") diff --git a/src/database/mysql/professor.ts b/src/database/mysql/professor.ts index b290bbc..7370642 100644 --- a/src/database/mysql/professor.ts +++ b/src/database/mysql/professor.ts @@ -20,6 +20,22 @@ export async function criarProfessor(professor: Omit) }; } +export async function verProfessoresNaTurma(turmaID: ID) +: Promise[]> { + const database = await connection("LabenuSystem_Professor") + .select("id", "nome", "email", "data_de_nascimento") + .where({ turma_id: turmaID }); + + return database.map(({ + id, nome, data_de_nascimento, email + }) => ({ + id, + email, + nome, + dataDeNascimento: data_de_nascimento + })); +} + export async function adicionarProfessorNaTurma(professorID: ID, turmaID: ID) : Promise { return connection("LabenuSystem_Professor") diff --git a/src/handlers/estudante/index.ts b/src/handlers/estudante/index.ts index dacd11d..4c8b57a 100644 --- a/src/handlers/estudante/index.ts +++ b/src/handlers/estudante/index.ts @@ -2,21 +2,25 @@ import express, { Request, Response } from "express"; import { criarEstudanteSchema, estudanteAdicionarTurmaSchema } from "../../validate"; import { adicionarEstudanteNaTurma, - criarEstudante as criarEstudanteDatabase + criarEstudante as criarEstudanteDatabase, + verEstudantesNaTurma } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; +import { validate as validarUUID } from "uuid"; const erros = { inesperado: "Aconteceu um erro inesperado", emailExiste: "Email já existe", estudanteNaoEcontrada: "Estudante não econtrada", - turmaNaoEcontrada: "Turma não econtrada" + turmaNaoEcontrada: "Turma não econtrada", + turmaIDInvalido: "O turmaID precisa ser um id válido" }; export const estudanteRouter = express.Router(); estudanteRouter.post("/", criarEstudante); estudanteRouter.put("/turma", adicionarTurma); +estudanteRouter.get("/turma/:turmaID", verTurma); async function criarEstudante(request: Request, response: Response): Promise { const { @@ -85,3 +89,21 @@ async function adicionarTurma(request: Request, response: Response) response.status(500).send(erros.inesperado); } } + +export async function verTurma(request: Request, response: Response): Promise { + const { turmaID } = request.params; + if (!validarUUID(turmaID)) { + response.status(400).send(erros.turmaIDInvalido); + return; + } + + try { + const estudantes = await verEstudantesNaTurma(turmaID); + response.send({ + quantidate: estudantes.length, + estudantes + }); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} diff --git a/src/handlers/professor/index.ts b/src/handlers/professor/index.ts index 5807336..6bec256 100644 --- a/src/handlers/professor/index.ts +++ b/src/handlers/professor/index.ts @@ -2,21 +2,25 @@ import express, { Request, Response } from "express"; import { criarProfessorSchema, professorAdicionarTurmaSchema } from "../../validate"; import { adicionarProfessorNaTurma, - criarProfessor as criarProfessorDatabase + criarProfessor as criarProfessorDatabase, + verProfessoresNaTurma } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; +import { validate as validarUUID } from "uuid"; const erros = { inesperado: "Aconteceu um erro inesperado", emailExiste: "Email já existe", professorNaoEcontrada: "Professor não econtrada", - turmaNaoEcontrada: "Turma não econtrada" + turmaNaoEcontrada: "Turma não econtrada", + turmaIDInvalido: "O turmaID precisa ser um id válido" }; export const professorRouter = express.Router(); professorRouter.post("/", criarProfessor); professorRouter.put("/turma", adicionarTurma); +professorRouter.get("/turma/:turmaID", verTurma); async function criarProfessor(request: Request, response: Response): Promise { const { @@ -85,3 +89,21 @@ async function adicionarTurma(request: Request, response: Response) response.status(500).send(erros.inesperado); } } + +export async function verTurma(request: Request, response: Response): Promise { + const { turmaID } = request.params; + if (!validarUUID(turmaID)) { + response.status(400).send(erros.turmaIDInvalido); + return; + } + + try { + const professores = await verProfessoresNaTurma(turmaID); + response.send({ + quantidate: professores.length, + professores + }); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} From 49ebae03a8aa6aacba61f07f3d9f8c8c57d58239 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 17:39:01 -0400 Subject: [PATCH 11/29] Adicionando deploy no heroku --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index ebdbffe..3b5c2fb 100644 --- a/package.json +++ b/package.json @@ -3,6 +3,7 @@ "version": "0.1.0", "private": true, "scripts": { + "start": "cd semana17/LabenuSystem && npm install && npm start", "lint": "tsc && eslint ." }, "devDependencies": { From 65d84810550bf51381aaf8e2ca862638d6c6abb3 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 17:41:37 -0400 Subject: [PATCH 12/29] Resolvendo bug no deploy --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 98319ca..172c006 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "express": "^4.17.1", "knex": "^0.95.7", "mysql": "^2.18.1", + "typescript": "^4.3.5", "uuid": "^8.3.2", "yup": "^0.32.9" }, From 8197973e6d4b4b4dd06ef3e1b948815828df508c Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 17:41:37 -0400 Subject: [PATCH 13/29] Resolvendo bug no deploy --- semana17/LabenuSystem/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/semana17/LabenuSystem/package.json b/semana17/LabenuSystem/package.json index 98319ca..172c006 100644 --- a/semana17/LabenuSystem/package.json +++ b/semana17/LabenuSystem/package.json @@ -16,6 +16,7 @@ "express": "^4.17.1", "knex": "^0.95.7", "mysql": "^2.18.1", + "typescript": "^4.3.5", "uuid": "^8.3.2", "yup": "^0.32.9" }, From ed0e987fb08c7c37f341bf2660d6a12fc1d258ec Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 17:44:43 -0400 Subject: [PATCH 14/29] Arrumando bug no deploy --- package.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/package.json b/package.json index 172c006..fa77d11 100644 --- a/package.json +++ b/package.json @@ -18,9 +18,7 @@ "mysql": "^2.18.1", "typescript": "^4.3.5", "uuid": "^8.3.2", - "yup": "^0.32.9" - }, - "devDependencies": { + "yup": "^0.32.9", "@types/cors": "^2.8.12", "@types/express": "^4.17.13", "@types/node": "^16.4.0", From ae89b9ae1204ee9ee7ac99644e51223f6b4e0df1 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 17:44:43 -0400 Subject: [PATCH 15/29] Arrumando bug no deploy --- semana17/LabenuSystem/package.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/semana17/LabenuSystem/package.json b/semana17/LabenuSystem/package.json index 172c006..fa77d11 100644 --- a/semana17/LabenuSystem/package.json +++ b/semana17/LabenuSystem/package.json @@ -18,9 +18,7 @@ "mysql": "^2.18.1", "typescript": "^4.3.5", "uuid": "^8.3.2", - "yup": "^0.32.9" - }, - "devDependencies": { + "yup": "^0.32.9", "@types/cors": "^2.8.12", "@types/express": "^4.17.13", "@types/node": "^16.4.0", From 76263e56e083000b971ff5c32cee4840bdf34aca Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 17:52:59 -0400 Subject: [PATCH 16/29] =?UTF-8?q?Mudando=20a=20l=C3=B3gica=20de=20como=20a?= =?UTF-8?q?=20porta=20do=20servidor=20=C3=A9=20declarado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index ec1c3ef..f08d162 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,7 +4,7 @@ import cors from "cors"; import { estudanteRouter, turmaRouter } from "./handlers"; import { professorRouter } from "./handlers/professor"; -const serverPort = process.env.NODE_PORT || 3003; +const serverPort = process.env.PORT || process.env.NODE_PORT || 3003; const server = express(); server.use(express.json()); From 0b502d1e8195e6811b59f029bf360a09716411ad Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 17:52:59 -0400 Subject: [PATCH 17/29] =?UTF-8?q?Mudando=20a=20l=C3=B3gica=20de=20como=20a?= =?UTF-8?q?=20porta=20do=20servidor=20=C3=A9=20declarado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- semana17/LabenuSystem/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/semana17/LabenuSystem/src/index.ts b/semana17/LabenuSystem/src/index.ts index ec1c3ef..f08d162 100644 --- a/semana17/LabenuSystem/src/index.ts +++ b/semana17/LabenuSystem/src/index.ts @@ -4,7 +4,7 @@ import cors from "cors"; import { estudanteRouter, turmaRouter } from "./handlers"; import { professorRouter } from "./handlers/professor"; -const serverPort = process.env.NODE_PORT || 3003; +const serverPort = process.env.PORT || process.env.NODE_PORT || 3003; const server = express(); server.use(express.json()); From e72a08cb691f3eb1759b35ac77e914a9f1c19509 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 18:04:38 -0400 Subject: [PATCH 18/29] Vendo erro no heroku --- src/handlers/professor/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/handlers/professor/index.ts b/src/handlers/professor/index.ts index 6bec256..83919fe 100644 --- a/src/handlers/professor/index.ts +++ b/src/handlers/professor/index.ts @@ -104,6 +104,7 @@ export async function verTurma(request: Request, response: Response): Promise Date: Sun, 1 Aug 2021 18:04:38 -0400 Subject: [PATCH 19/29] Vendo erro no heroku --- semana17/LabenuSystem/src/handlers/professor/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts index 6bec256..83919fe 100644 --- a/semana17/LabenuSystem/src/handlers/professor/index.ts +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -104,6 +104,7 @@ export async function verTurma(request: Request, response: Response): Promise Date: Sun, 1 Aug 2021 18:09:01 -0400 Subject: [PATCH 20/29] Vendo erro no deploy --- src/handlers/professor/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/handlers/professor/index.ts b/src/handlers/professor/index.ts index 83919fe..3b9e5a1 100644 --- a/src/handlers/professor/index.ts +++ b/src/handlers/professor/index.ts @@ -7,6 +7,7 @@ import { } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; +import { connection } from "../../database/mysql/connection"; const erros = { inesperado: "Aconteceu um erro inesperado", @@ -105,6 +106,7 @@ export async function verTurma(request: Request, response: Response): Promise Date: Sun, 1 Aug 2021 18:09:01 -0400 Subject: [PATCH 21/29] Vendo erro no deploy --- semana17/LabenuSystem/src/handlers/professor/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts index 83919fe..3b9e5a1 100644 --- a/semana17/LabenuSystem/src/handlers/professor/index.ts +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -7,6 +7,7 @@ import { } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; +import { connection } from "../../database/mysql/connection"; const erros = { inesperado: "Aconteceu um erro inesperado", @@ -105,6 +106,7 @@ export async function verTurma(request: Request, response: Response): Promise Date: Sun, 1 Aug 2021 18:13:31 -0400 Subject: [PATCH 22/29] Arurmando bug --- src/handlers/professor/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/handlers/professor/index.ts b/src/handlers/professor/index.ts index 3b9e5a1..68efe06 100644 --- a/src/handlers/professor/index.ts +++ b/src/handlers/professor/index.ts @@ -7,7 +7,6 @@ import { } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; -import { connection } from "../../database/mysql/connection"; const erros = { inesperado: "Aconteceu um erro inesperado", From 8c3e06ad9af3b07e6af3d53a4047c1222353e185 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 18:13:31 -0400 Subject: [PATCH 23/29] Arurmando bug --- semana17/LabenuSystem/src/handlers/professor/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts index 3b9e5a1..68efe06 100644 --- a/semana17/LabenuSystem/src/handlers/professor/index.ts +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -7,7 +7,6 @@ import { } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; -import { connection } from "../../database/mysql/connection"; const erros = { inesperado: "Aconteceu um erro inesperado", From 81c00ec346a18c277c1346f045bb8f0f272fed82 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 18:38:41 -0400 Subject: [PATCH 24/29] Removendo console logs --- semana17/LabenuSystem/package.json | 10 +++++----- semana17/LabenuSystem/src/handlers/professor/index.ts | 2 -- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/semana17/LabenuSystem/package.json b/semana17/LabenuSystem/package.json index fa77d11..9493716 100644 --- a/semana17/LabenuSystem/package.json +++ b/semana17/LabenuSystem/package.json @@ -11,6 +11,10 @@ "author": "", "license": "ISC", "dependencies": { + "@types/cors": "^2.8.12", + "@types/express": "^4.17.13", + "@types/node": "^16.4.0", + "@types/uuid": "^8.3.1", "cors": "^2.8.5", "dotenv": "^10.0.0", "express": "^4.17.1", @@ -18,10 +22,6 @@ "mysql": "^2.18.1", "typescript": "^4.3.5", "uuid": "^8.3.2", - "yup": "^0.32.9", - "@types/cors": "^2.8.12", - "@types/express": "^4.17.13", - "@types/node": "^16.4.0", - "@types/uuid": "^8.3.1" + "yup": "^0.32.9" } } diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts index 68efe06..6bec256 100644 --- a/semana17/LabenuSystem/src/handlers/professor/index.ts +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -104,8 +104,6 @@ export async function verTurma(request: Request, response: Response): Promise Date: Sun, 1 Aug 2021 20:14:56 -0400 Subject: [PATCH 25/29] Adicionando a funcionalidade de ver professor e estudante por id --- .../src/database/mysql/estudante.ts | 17 ++++++++++ .../src/database/mysql/professor.ts | 17 ++++++++++ .../src/handlers/estudante/index.ts | 29 +++++++++++++++-- .../src/handlers/professor/index.ts | 32 ++++++++++++++++--- 4 files changed, 87 insertions(+), 8 deletions(-) diff --git a/semana17/LabenuSystem/src/database/mysql/estudante.ts b/semana17/LabenuSystem/src/database/mysql/estudante.ts index 71aee24..2755ce2 100644 --- a/semana17/LabenuSystem/src/database/mysql/estudante.ts +++ b/semana17/LabenuSystem/src/database/mysql/estudante.ts @@ -20,6 +20,23 @@ export async function criarEstudante(estudante: Omit) }; } +export async function verEstudante(id: ID): Promise { + const database = await connection("LabenuSystem_Estudante") + .select("*") + .where({ id }) + .first(); + + return database + ? { + id: database.id, + nome: database.nome, + email: database.email, + dataDeNascimento: database.data_de_nascimento, + turmaID: database.turma_id + } + : undefined; +} + export async function verEstudantesNaTurma(turmaID: ID) : Promise[]> { const database = await connection("LabenuSystem_Estudante") diff --git a/semana17/LabenuSystem/src/database/mysql/professor.ts b/semana17/LabenuSystem/src/database/mysql/professor.ts index 7370642..62265fb 100644 --- a/semana17/LabenuSystem/src/database/mysql/professor.ts +++ b/semana17/LabenuSystem/src/database/mysql/professor.ts @@ -20,6 +20,23 @@ export async function criarProfessor(professor: Omit) }; } +export async function verProfessor(id: ID): Promise { + const database = await connection("LabenuSystem_Professor") + .select("*") + .where({ id }) + .first(); + + return database + ? { + id: database.id, + nome: database.nome, + email: database.email, + dataDeNascimento: database.data_de_nascimento, + turmaID: database.turma_id + } + : undefined; +} + export async function verProfessoresNaTurma(turmaID: ID) : Promise[]> { const database = await connection("LabenuSystem_Professor") diff --git a/semana17/LabenuSystem/src/handlers/estudante/index.ts b/semana17/LabenuSystem/src/handlers/estudante/index.ts index 4c8b57a..17e59bc 100644 --- a/semana17/LabenuSystem/src/handlers/estudante/index.ts +++ b/semana17/LabenuSystem/src/handlers/estudante/index.ts @@ -3,7 +3,8 @@ import { criarEstudanteSchema, estudanteAdicionarTurmaSchema } from "../../valid import { adicionarEstudanteNaTurma, criarEstudante as criarEstudanteDatabase, - verEstudantesNaTurma + verEstudantesNaTurma, + verEstudante as verEstudanteDatabase } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; @@ -13,7 +14,8 @@ const erros = { emailExiste: "Email já existe", estudanteNaoEcontrada: "Estudante não econtrada", turmaNaoEcontrada: "Turma não econtrada", - turmaIDInvalido: "O turmaID precisa ser um id válido" + turmaIDInvalido: "O turmaID precisa ser um id válido", + IDInvalido: "O estudanteID precisa ser um id válido" }; export const estudanteRouter = express.Router(); @@ -21,6 +23,7 @@ export const estudanteRouter = express.Router(); estudanteRouter.post("/", criarEstudante); estudanteRouter.put("/turma", adicionarTurma); estudanteRouter.get("/turma/:turmaID", verTurma); +estudanteRouter.get("/:id", verEstudante); async function criarEstudante(request: Request, response: Response): Promise { const { @@ -90,7 +93,7 @@ async function adicionarTurma(request: Request, response: Response) } } -export async function verTurma(request: Request, response: Response): Promise { +async function verTurma(request: Request, response: Response): Promise { const { turmaID } = request.params; if (!validarUUID(turmaID)) { response.status(400).send(erros.turmaIDInvalido); @@ -107,3 +110,23 @@ export async function verTurma(request: Request, response: Response): Promise { + const { id } = request.params; + if (!validarUUID(id)) { + response.status(400).send(erros.IDInvalido); + return; + } + + try { + const professor = await verEstudanteDatabase(id); + if (!professor) { + response.status(404).send(erros.estudanteNaoEcontrada); + return; + } + + response.send(professor); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts index 6bec256..edab972 100644 --- a/semana17/LabenuSystem/src/handlers/professor/index.ts +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -3,7 +3,8 @@ import { criarProfessorSchema, professorAdicionarTurmaSchema } from "../../valid import { adicionarProfessorNaTurma, criarProfessor as criarProfessorDatabase, - verProfessoresNaTurma + verProfessoresNaTurma, + verProfessor as verProfessorDatabase } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; @@ -13,7 +14,8 @@ const erros = { emailExiste: "Email já existe", professorNaoEcontrada: "Professor não econtrada", turmaNaoEcontrada: "Turma não econtrada", - turmaIDInvalido: "O turmaID precisa ser um id válido" + turmaIDInvalido: "O turmaID precisa ser um id válido", + IDInvalido: "O professorID precisa ser um id válido" }; export const professorRouter = express.Router(); @@ -21,6 +23,7 @@ export const professorRouter = express.Router(); professorRouter.post("/", criarProfessor); professorRouter.put("/turma", adicionarTurma); professorRouter.get("/turma/:turmaID", verTurma); +professorRouter.get("/:id", verProfessor); async function criarProfessor(request: Request, response: Response): Promise { const { @@ -58,8 +61,7 @@ async function criarProfessor(request: Request, response: Response): Promise { +async function adicionarTurma(request: Request, response: Response): Promise { const { turmaID, professorID } = request.body; try { @@ -90,7 +92,7 @@ async function adicionarTurma(request: Request, response: Response) } } -export async function verTurma(request: Request, response: Response): Promise { +async function verTurma(request: Request, response: Response): Promise { const { turmaID } = request.params; if (!validarUUID(turmaID)) { response.status(400).send(erros.turmaIDInvalido); @@ -107,3 +109,23 @@ export async function verTurma(request: Request, response: Response): Promise { + const { id } = request.params; + if (!validarUUID(id)) { + response.status(400).send(erros.IDInvalido); + return; + } + + try { + const professor = await verProfessorDatabase(id); + if (!professor) { + response.status(404).send(erros.professorNaoEcontrada); + return; + } + + response.send(professor); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} From d69a074f1a2da0a7365614e60df4c0286ff1e50f Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 20:32:21 -0400 Subject: [PATCH 26/29] Adicionando a funcionalidade de remover professor e estudante das turmas --- .../src/database/mysql/estudante.ts | 7 ++++++ .../src/database/mysql/professor.ts | 7 ++++++ .../src/handlers/estudante/index.ts | 25 ++++++++++++++++++- .../src/handlers/professor/index.ts | 25 ++++++++++++++++++- 4 files changed, 62 insertions(+), 2 deletions(-) diff --git a/semana17/LabenuSystem/src/database/mysql/estudante.ts b/semana17/LabenuSystem/src/database/mysql/estudante.ts index 2755ce2..78cea7d 100644 --- a/semana17/LabenuSystem/src/database/mysql/estudante.ts +++ b/semana17/LabenuSystem/src/database/mysql/estudante.ts @@ -1,5 +1,6 @@ import { v1 as uuidV1 } from "uuid"; import { Estudante, EstudanteDatabase, ID } from "../../@types"; +import { TURMA_ZERO_ID } from "../../handlers"; import { connection } from "./connection"; export async function criarEstudante(estudante: Omit) @@ -60,3 +61,9 @@ export async function adicionarEstudanteNaTurma(estudanteID: ID, turmaID: ID) .where({ id: estudanteID }); } +export async function removerEstudanteDaTurma(id: ID): Promise { + return connection("LabenuSystem_Estudante") + .update({ turma_id: TURMA_ZERO_ID }) + .where({ id }); +} + diff --git a/semana17/LabenuSystem/src/database/mysql/professor.ts b/semana17/LabenuSystem/src/database/mysql/professor.ts index 62265fb..0963461 100644 --- a/semana17/LabenuSystem/src/database/mysql/professor.ts +++ b/semana17/LabenuSystem/src/database/mysql/professor.ts @@ -1,5 +1,6 @@ import { v1 as uuidV1 } from "uuid"; import { ID, Professor, ProfessorDatabase } from "../../@types"; +import { TURMA_ZERO_ID } from "../../handlers"; import { connection } from "./connection"; export async function criarProfessor(professor: Omit) @@ -60,3 +61,9 @@ export async function adicionarProfessorNaTurma(professorID: ID, turmaID: ID) .where({ id: professorID }); } +export async function removerProfessorDaTurma(id: ID): Promise { + return connection("LabenuSystem_Professor") + .update({ turma_id: TURMA_ZERO_ID }) + .where({ id }); +} + diff --git a/semana17/LabenuSystem/src/handlers/estudante/index.ts b/semana17/LabenuSystem/src/handlers/estudante/index.ts index 17e59bc..feb9cc3 100644 --- a/semana17/LabenuSystem/src/handlers/estudante/index.ts +++ b/semana17/LabenuSystem/src/handlers/estudante/index.ts @@ -4,7 +4,8 @@ import { adicionarEstudanteNaTurma, criarEstudante as criarEstudanteDatabase, verEstudantesNaTurma, - verEstudante as verEstudanteDatabase + verEstudante as verEstudanteDatabase, + removerEstudanteDaTurma } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; @@ -24,6 +25,7 @@ estudanteRouter.post("/", criarEstudante); estudanteRouter.put("/turma", adicionarTurma); estudanteRouter.get("/turma/:turmaID", verTurma); estudanteRouter.get("/:id", verEstudante); +estudanteRouter.delete("/:id/turma", removerDaTurma); async function criarEstudante(request: Request, response: Response): Promise { const { @@ -130,3 +132,24 @@ async function verEstudante(request: Request, response: Response): Promise response.status(500).send(erros.inesperado); } } + +async function removerDaTurma(request: Request, response: Response): Promise { + const { id } = request.params; + if (!validarUUID(id)) { + response.status(400).send(erros.IDInvalido); + return; + } + + try { + const professor = await removerEstudanteDaTurma(id); + if (!professor) { + response.status(404).send(erros.estudanteNaoEcontrada); + return; + } + + response.send("Estudante removido da turma"); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} + diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts index edab972..31beaab 100644 --- a/semana17/LabenuSystem/src/handlers/professor/index.ts +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -4,7 +4,8 @@ import { adicionarProfessorNaTurma, criarProfessor as criarProfessorDatabase, verProfessoresNaTurma, - verProfessor as verProfessorDatabase + verProfessor as verProfessorDatabase, + removerProfessorDaTurma } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; @@ -24,6 +25,7 @@ professorRouter.post("/", criarProfessor); professorRouter.put("/turma", adicionarTurma); professorRouter.get("/turma/:turmaID", verTurma); professorRouter.get("/:id", verProfessor); +professorRouter.delete("/:id/turma", removerDaTurma); async function criarProfessor(request: Request, response: Response): Promise { const { @@ -129,3 +131,24 @@ async function verProfessor(request: Request, response: Response): Promise response.status(500).send(erros.inesperado); } } + +async function removerDaTurma(request: Request, response: Response): Promise { + const { id } = request.params; + if (!validarUUID(id)) { + response.status(400).send(erros.IDInvalido); + return; + } + + try { + const professor = await removerProfessorDaTurma(id); + if (!professor) { + response.status(404).send(erros.professorNaoEcontrada); + return; + } + + response.send("Professor removido da turma"); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} + From d47eb0aac5441bf309e6683097815f50e2774edb Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 20:48:56 -0400 Subject: [PATCH 27/29] Adicionando a funcionalidades de remover estudante e professor --- .../src/database/mysql/estudante.ts | 10 ++++++++ .../src/database/mysql/professor.ts | 10 ++++++++ .../src/handlers/estudante/index.ts | 25 ++++++++++++++++++- .../src/handlers/professor/index.ts | 24 +++++++++++++++++- 4 files changed, 67 insertions(+), 2 deletions(-) diff --git a/semana17/LabenuSystem/src/database/mysql/estudante.ts b/semana17/LabenuSystem/src/database/mysql/estudante.ts index 78cea7d..3e2897e 100644 --- a/semana17/LabenuSystem/src/database/mysql/estudante.ts +++ b/semana17/LabenuSystem/src/database/mysql/estudante.ts @@ -67,3 +67,13 @@ export async function removerEstudanteDaTurma(id: ID): Promise { .where({ id }); } +export async function removerEstudante(id: ID): Promise { + connection("LabenuSystem_Estudante_Passatempo") + .del() + .where({ estudante_id: id }); + + return connection("LabenuSystem_Estudante") + .del() + .where({ id }); +} + diff --git a/semana17/LabenuSystem/src/database/mysql/professor.ts b/semana17/LabenuSystem/src/database/mysql/professor.ts index 0963461..f7b7cd2 100644 --- a/semana17/LabenuSystem/src/database/mysql/professor.ts +++ b/semana17/LabenuSystem/src/database/mysql/professor.ts @@ -67,3 +67,13 @@ export async function removerProfessorDaTurma(id: ID): Promise { .where({ id }); } +export async function removerProfessor(id: ID): Promise { + connection("LabenuSystem_Professor_Especialidade") + .del() + .where({ professor_id: id }); + + return connection("LabenuSystem_Professor") + .del() + .where({ id }); +} + diff --git a/semana17/LabenuSystem/src/handlers/estudante/index.ts b/semana17/LabenuSystem/src/handlers/estudante/index.ts index feb9cc3..21c744f 100644 --- a/semana17/LabenuSystem/src/handlers/estudante/index.ts +++ b/semana17/LabenuSystem/src/handlers/estudante/index.ts @@ -5,7 +5,8 @@ import { criarEstudante as criarEstudanteDatabase, verEstudantesNaTurma, verEstudante as verEstudanteDatabase, - removerEstudanteDaTurma + removerEstudanteDaTurma, + removerEstudante as removerEstudanteDatabase } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; @@ -25,6 +26,7 @@ estudanteRouter.post("/", criarEstudante); estudanteRouter.put("/turma", adicionarTurma); estudanteRouter.get("/turma/:turmaID", verTurma); estudanteRouter.get("/:id", verEstudante); +estudanteRouter.delete("/:id", removerEstudante); estudanteRouter.delete("/:id/turma", removerDaTurma); async function criarEstudante(request: Request, response: Response): Promise { @@ -153,3 +155,24 @@ async function removerDaTurma(request: Request, response: Response): Promise { + const { id } = request.params; + if (!validarUUID(id)) { + response.status(400).send(erros.IDInvalido); + return; + } + + try { + const professor = await removerEstudanteDatabase(id); + if (!professor) { + response.status(404).send(erros.estudanteNaoEcontrada); + return; + } + + response.send("Estudante removido"); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} + diff --git a/semana17/LabenuSystem/src/handlers/professor/index.ts b/semana17/LabenuSystem/src/handlers/professor/index.ts index 31beaab..7a4d164 100644 --- a/semana17/LabenuSystem/src/handlers/professor/index.ts +++ b/semana17/LabenuSystem/src/handlers/professor/index.ts @@ -5,7 +5,8 @@ import { criarProfessor as criarProfessorDatabase, verProfessoresNaTurma, verProfessor as verProfessorDatabase, - removerProfessorDaTurma + removerProfessorDaTurma, + removerProfessor as removerProfessorDatabase } from "../../database/mysql"; import { TURMA_ZERO_ID } from "../turma"; import { validate as validarUUID } from "uuid"; @@ -25,6 +26,7 @@ professorRouter.post("/", criarProfessor); professorRouter.put("/turma", adicionarTurma); professorRouter.get("/turma/:turmaID", verTurma); professorRouter.get("/:id", verProfessor); +professorRouter.delete("/:id", removerProfessor); professorRouter.delete("/:id/turma", removerDaTurma); async function criarProfessor(request: Request, response: Response): Promise { @@ -152,3 +154,23 @@ async function removerDaTurma(request: Request, response: Response): Promise { + const { id } = request.params; + if (!validarUUID(id)) { + response.status(400).send(erros.IDInvalido); + return; + } + + try { + const professor = await removerProfessorDatabase(id); + if (!professor) { + response.status(404).send(erros.professorNaoEcontrada); + return; + } + + response.send("Professor removido"); + } catch (erro) { + response.status(500).send(erros.inesperado); + } +} From 3e0bd6f9635a3b96d79393f7df13f237046949a1 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 21:41:35 -0400 Subject: [PATCH 28/29] Adicionando a funcionalidade de mudar turma de modulo --- .../LabenuSystem/src/database/mysql/turma.ts | 6 ++- .../src/handlers/estudante/index.ts | 10 ++-- .../src/handlers/professor/index.ts | 2 +- .../LabenuSystem/src/handlers/turma/index.ts | 49 +++++++++++++++---- semana17/LabenuSystem/src/validate/index.ts | 3 ++ 5 files changed, 54 insertions(+), 16 deletions(-) diff --git a/semana17/LabenuSystem/src/database/mysql/turma.ts b/semana17/LabenuSystem/src/database/mysql/turma.ts index d7e61bd..3ff3f82 100644 --- a/semana17/LabenuSystem/src/database/mysql/turma.ts +++ b/semana17/LabenuSystem/src/database/mysql/turma.ts @@ -1,6 +1,6 @@ import { v1 as uuidV1 } from "uuid"; import { connection } from "./connection"; -import { Turma, TurmaDatabase } from "../../@types"; +import { ID, Turma, TurmaDatabase } from "../../@types"; export async function criarTurma(turma: Omit): Promise { const turmaNova: TurmaDatabase = { @@ -19,3 +19,7 @@ export async function criarTurma(turma: Omit): Promise { id: turmaNova.id }; } + +export async function mudarModulo(id: ID, modulo:Turma["modulo"]): Promise { + return connection("LabenuSystem_Turma").update({ modulo }).where({ id }); +} diff --git a/semana17/LabenuSystem/src/handlers/estudante/index.ts b/semana17/LabenuSystem/src/handlers/estudante/index.ts index 21c744f..9b8fcf2 100644 --- a/semana17/LabenuSystem/src/handlers/estudante/index.ts +++ b/semana17/LabenuSystem/src/handlers/estudante/index.ts @@ -49,14 +49,14 @@ async function criarEstudante(request: Request, response: Response): Promise { const turmaNova = await criarTurmaDatabase(turma); - response.send(turmaNova); - } catch (error) { - if (error.name === "ValidationError") { - response.status(400).send(error.errors); + response.status(201).send(turmaNova); + } catch (erro) { + if (erro.name === "ValidationError") { + response.status(400).send(erro.errors); return; } - if (error.code === "ER_DUP_ENTRY") { + if (erro.code === "ER_DUP_ENTRY") { response.status(409).send(erros.nomeExiste); return; } @@ -53,3 +58,29 @@ async function criarTurma(request: Request, response: Response): Promise { } } +async function mudarModulo(request: Request, response: Response): Promise { + const { id, modulo } = request.body; + + try { + await mudarModuloSchema.validate({ + id, + modulo + }, { abortEarly: false }); + + const turma = await mudarModuloDatabase(id, modulo); + if (!turma) { + response.status(404).send(erros.turmaNaoEcontrada); + return; + } + + response.send("Modulo atualizado com sucesso"); + } catch (erro) { + if (erro.name === "ValidationError") { + response.status(400).send(erro.errors); + return; + } + + response.status(500).send(erros.inesperado); + } +} + diff --git a/semana17/LabenuSystem/src/validate/index.ts b/semana17/LabenuSystem/src/validate/index.ts index fcb3359..b29099b 100644 --- a/semana17/LabenuSystem/src/validate/index.ts +++ b/semana17/LabenuSystem/src/validate/index.ts @@ -26,6 +26,9 @@ export const turmaSchema: yup.SchemaOf = yup.object({ export const criarTurmaSchema: yup.SchemaOf> = turmaSchema.omit([ "id" ]); +export const mudarModuloSchema: yup.SchemaOf> + = turmaSchema.pick([ "id", "modulo" ]); + //@ts-expect-error issue an yup https://github.com/jquense/yup/issues/1183 export const estudanteSchema: yup.SchemaOf = yup.object({ id: yup.string().uuid().defined(), From c0db478bd261766f2812cb37c2dfedab7365ef28 Mon Sep 17 00:00:00 2001 From: Thiago Felipe Date: Sun, 1 Aug 2021 21:56:28 -0400 Subject: [PATCH 29/29] =?UTF-8?q?Refatorando=20c=C3=B3digo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/database/mysql/{estudante.ts => estudante/index.ts} | 6 +++--- .../src/database/mysql/{professor.ts => professor/index.ts} | 6 +++--- .../src/database/mysql/{turma.ts => turma/index.ts} | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) rename semana17/LabenuSystem/src/database/mysql/{estudante.ts => estudante/index.ts} (92%) rename semana17/LabenuSystem/src/database/mysql/{professor.ts => professor/index.ts} (92%) rename semana17/LabenuSystem/src/database/mysql/{turma.ts => turma/index.ts} (85%) diff --git a/semana17/LabenuSystem/src/database/mysql/estudante.ts b/semana17/LabenuSystem/src/database/mysql/estudante/index.ts similarity index 92% rename from semana17/LabenuSystem/src/database/mysql/estudante.ts rename to semana17/LabenuSystem/src/database/mysql/estudante/index.ts index 3e2897e..c155cf1 100644 --- a/semana17/LabenuSystem/src/database/mysql/estudante.ts +++ b/semana17/LabenuSystem/src/database/mysql/estudante/index.ts @@ -1,7 +1,7 @@ import { v1 as uuidV1 } from "uuid"; -import { Estudante, EstudanteDatabase, ID } from "../../@types"; -import { TURMA_ZERO_ID } from "../../handlers"; -import { connection } from "./connection"; +import { Estudante, EstudanteDatabase, ID } from "../../../@types"; +import { TURMA_ZERO_ID } from "../../../handlers"; +import { connection } from "../connection"; export async function criarEstudante(estudante: Omit) : Promise { diff --git a/semana17/LabenuSystem/src/database/mysql/professor.ts b/semana17/LabenuSystem/src/database/mysql/professor/index.ts similarity index 92% rename from semana17/LabenuSystem/src/database/mysql/professor.ts rename to semana17/LabenuSystem/src/database/mysql/professor/index.ts index f7b7cd2..eb92ba7 100644 --- a/semana17/LabenuSystem/src/database/mysql/professor.ts +++ b/semana17/LabenuSystem/src/database/mysql/professor/index.ts @@ -1,7 +1,7 @@ import { v1 as uuidV1 } from "uuid"; -import { ID, Professor, ProfessorDatabase } from "../../@types"; -import { TURMA_ZERO_ID } from "../../handlers"; -import { connection } from "./connection"; +import { ID, Professor, ProfessorDatabase } from "../../../@types"; +import { TURMA_ZERO_ID } from "../../../handlers"; +import { connection } from "../connection"; export async function criarProfessor(professor: Omit) : Promise { diff --git a/semana17/LabenuSystem/src/database/mysql/turma.ts b/semana17/LabenuSystem/src/database/mysql/turma/index.ts similarity index 85% rename from semana17/LabenuSystem/src/database/mysql/turma.ts rename to semana17/LabenuSystem/src/database/mysql/turma/index.ts index 3ff3f82..d99293f 100644 --- a/semana17/LabenuSystem/src/database/mysql/turma.ts +++ b/semana17/LabenuSystem/src/database/mysql/turma/index.ts @@ -1,6 +1,6 @@ import { v1 as uuidV1 } from "uuid"; -import { connection } from "./connection"; -import { ID, Turma, TurmaDatabase } from "../../@types"; +import { connection } from "../connection"; +import { ID, Turma, TurmaDatabase } from "../../../@types"; export async function criarTurma(turma: Omit): Promise { const turmaNova: TurmaDatabase = {