├── .env ├── .gitignore ├── package.json ├── src ├── controllers │ └── apiController.ts ├── instances │ └── pg.ts ├── models │ └── User.ts ├── routes │ └── api.ts └── server.ts └── tsconfig.json /.env: -------------------------------------------------------------------------------- 1 | PORT=4000 2 | 3 | PG_DB=auths 4 | PG_USER=postgres 5 | PG_PASSWORD=1234 6 | PG_PORT=5432 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | package-lock.json -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mod-api", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "start-dev": "nodemon -e ts,json src/server.ts" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "cors": "^2.8.5", 14 | "dotenv": "^10.0.0", 15 | "express": "^4.17.1", 16 | "pg": "^8.7.1", 17 | "pg-hstore": "^2.3.4", 18 | "sequelize": "^6.6.5", 19 | "validator": "^13.6.0" 20 | }, 21 | "devDependencies": { 22 | "@types/cors": "^2.8.12", 23 | "@types/express": "^4.17.13", 24 | "@types/node": "^16.6.1", 25 | "@types/sequelize": "^4.28.10", 26 | "@types/validator": "^13.6.3" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/controllers/apiController.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response } from 'express'; 2 | import { User } from '../models/User'; 3 | 4 | export const ping = (req: Request, res: Response) => { 5 | res.json({pong: true}); 6 | } 7 | 8 | export const register = async (req: Request, res: Response) => { 9 | if(req.body.email && req.body.password) { 10 | let { email, password } = req.body; 11 | 12 | let hasUser = await User.findOne({where: { email }}); 13 | if(!hasUser) { 14 | let newUser = await User.create({ email, password }); 15 | 16 | res.status(201); 17 | res.json({ id: newUser.id }); 18 | } else { 19 | res.json({ error: 'E-mail já existe.' }); 20 | } 21 | } 22 | 23 | res.json({ error: 'E-mail e/ou senha não enviados.' }); 24 | } 25 | 26 | export const login = async (req: Request, res: Response) => { 27 | if(req.body.email && req.body.password) { 28 | let email: string = req.body.email; 29 | let password: string = req.body.password; 30 | 31 | let user = await User.findOne({ 32 | where: { email, password } 33 | }); 34 | 35 | if(user) { 36 | res.json({ status: true }); 37 | return; 38 | } 39 | } 40 | 41 | res.json({ status: false }); 42 | } 43 | 44 | export const list = async (req: Request, res: Response) => { 45 | let users = await User.findAll(); 46 | let list: string[] = []; 47 | 48 | for(let i in users) { 49 | list.push( users[i].email ); 50 | } 51 | 52 | res.json({ list }); 53 | } -------------------------------------------------------------------------------- /src/instances/pg.ts: -------------------------------------------------------------------------------- 1 | import { Sequelize } from 'sequelize'; 2 | import dotenv from 'dotenv'; 3 | 4 | dotenv.config(); 5 | 6 | export const sequelize = new Sequelize( 7 | process.env.PG_DB as string, 8 | process.env.PG_USER as string, 9 | process.env.PG_PASSWORD as string, 10 | { 11 | dialect: 'postgres', 12 | port: parseInt(process.env.PG_PORT as string) 13 | } 14 | ); -------------------------------------------------------------------------------- /src/models/User.ts: -------------------------------------------------------------------------------- 1 | import { Model, DataTypes } from 'sequelize'; 2 | import { sequelize } from '../instances/pg'; 3 | 4 | export interface UserInstance extends Model { 5 | id: number; 6 | email: string; 7 | password: string; 8 | } 9 | 10 | export const User = sequelize.define('User', { 11 | id: { 12 | primaryKey: true, 13 | autoIncrement: true, 14 | type: DataTypes.INTEGER 15 | }, 16 | email: { 17 | type: DataTypes.STRING, 18 | unique: true 19 | }, 20 | password: { 21 | type: DataTypes.STRING 22 | } 23 | }, { 24 | tableName: 'users', 25 | timestamps: false 26 | }); -------------------------------------------------------------------------------- /src/routes/api.ts: -------------------------------------------------------------------------------- 1 | import { Router } from 'express'; 2 | 3 | import * as ApiController from '../controllers/apiController'; 4 | 5 | const router = Router(); 6 | 7 | router.post('/register', ApiController.register); 8 | router.post('/login', ApiController.login); 9 | 10 | router.get('/list', ApiController.list); 11 | 12 | export default router; -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | import express, { Request, Response, ErrorRequestHandler } from 'express'; 2 | import path from 'path'; 3 | import dotenv from 'dotenv'; 4 | import cors from 'cors'; 5 | import apiRoutes from './routes/api'; 6 | 7 | dotenv.config(); 8 | 9 | const server = express(); 10 | 11 | server.use(cors()); 12 | 13 | server.use(express.static(path.join(__dirname, '../public'))); 14 | server.use(express.urlencoded({ extended: true })); 15 | 16 | server.get('/ping', (req: Request, res: Response) => res.json({ pong: true })); 17 | 18 | server.use(apiRoutes); 19 | 20 | server.use((req: Request, res: Response) => { 21 | res.status(404); 22 | res.json({ error: 'Endpoint não encontrado.' }); 23 | }); 24 | 25 | const errorHandler: ErrorRequestHandler = (err, req, res, next) => { 26 | res.status(400); // Bad Request 27 | console.log(err); 28 | res.json({ error: 'Ocorreu algum erro.' }); 29 | } 30 | server.use(errorHandler); 31 | 32 | server.listen(process.env.PORT); -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ 8 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 | // "lib": [], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ 13 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | "outDir": "./dist", /* Redirect output structure to the directory. */ 18 | "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true, /* Enable all strict type-checking options. */ 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 | 37 | /* Additional Checks */ 38 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 43 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ 44 | // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ 45 | 46 | /* Module Resolution Options */ 47 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 48 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 49 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 50 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 51 | // "typeRoots": [], /* List of folders to include type definitions from. */ 52 | // "types": [], /* Type declaration files to be included in compilation. */ 53 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 54 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 55 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 56 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 57 | 58 | /* Source Map Options */ 59 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 60 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 61 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 62 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 63 | 64 | /* Experimental Options */ 65 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 66 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 67 | 68 | /* Advanced Options */ 69 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 70 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 71 | } 72 | } 73 | --------------------------------------------------------------------------------